convert doctrine resultset to json from findby query using zend json - php

I've seend much assistance for everything BUT transforming data when using the findBy query.
What I want is a json string of the resulset from this query ensuring that the objects are serialized so i can use this somewhere else:
$posts = $entityManager->getRepository(\Application\Entity\Post::class)
->findBy(['status'=>\Application\Entity\Post::STATUS_PUBLISHED],
['dateCreated'=>'DESC']);
Json::encode($posts,true) from Zend Framework Json but the data is not showing up when i do this.
The result will be a json encoded string with the entity objects that i can pass somewhere else
I will use for the decoding:
\Zend\Json\Decoder::decode($posts,\Zend\Json\Json::TYPE_OBJECT)
UNLESS I should be using \Zend\Json\Json::TYPE_ARRAY)

Here is the way I do it :
include : use Zend\Json\Json;
here is my example of function / action :
public function getListAction(){
$request = $this->getRequest();
if($request->isPost()){
// recuperer le produit choisi :
$element = $request->getPost("element");
$result = null;
$result = $this->getEntityManager()->getRepository('Application\Entity\Element')->findBy(array('etat' => 'valide' , 'pkElement' => $element));
$champs = array();
$i = 0;
foreach ($result as $value) {
$champs[$i] = array("id"=>$value->getPkElement() , "nom"=>$value->getNom());
$i++;
}
$data = array(
'result' => true,
'data' => $champs
);
return $this->getResponse()->setContent(Json::encode($data));
}
}
Then the call in the view.phtml :
$.post('/application/controller_name/getList', {element: $("select[name=element]").val()}, function(result) {
var options = $("select[name=element]");
var obj = JSON.parse(result);
var data = obj.data;
var selected = "";
options.empty();
for (var i = 0; i < data.length; i++) {
options.append($("<option />").val(data[i]['id']).text(data[i]['nom']));
}
});
Hope it helps.

Related

Generate JSON response on server with JsonArray and single fields

I am trying to build a JSON response from my server side, but it is not working as expected.
It is probably something simple but, I am not so good at PHP...
The basic expected response is a JSON with a single JsonArray and some other fields, for that, the relevant piece of code is shown here:
Sample of expected JSON response:
{
"pageNr": 2
"totalPages":28
"products":[
{
"user_name":"testUser001",
"product_ID":"4756373abdhg"
},
{
"user_name":"testUser002",
"product_ID":"475ggdfghghg"
},
{
"user_name":"testUser003",
"product_ID":"47466gdgbdhg"
},
{
"user_name":"testUser004",
"product_ID":"4000nfaergeb"
},
{
"user_name":"testUser005",
"product_ID":"adfer73abdhg"
}
]
}
Basic PHP code used to generate desired JSON (among sql query and other things):
$res = array();
$res2 = array();
while($r = mysqli_fetch_assoc($query2)) {
$res["user_name"] = $r["user_name"];
$res["product_ID"] = $r["prod_ID"];
array_push($res2,$res);
}
$response = ['pageNr' => $page];
$response = ['totalPages' => $totalPages];
$response = ['products' => $res2];
Response that this code is generating on Postman:
{
"products":[
{
"user_name":"testUser001",
"product_ID":"4756373abdhg"
},
{
"user_name":"testUser002",
"product_ID":"475ggdfghghg"
},
{
"user_name":"testUser003",
"product_ID":"47466gdgbdhg"
},
{
"user_name":"testUser004",
"product_ID":"4000nfaergeb"
},
{
"user_name":"testUser005",
"product_ID":"adfer73abdhg"
}
]
}
So, for some reason the JSON response is not accepting more fields pageNrand totalPages.
What is wrong here?.
Each assignment overwrites your array. You need to update it instead:
$res = array();
$res2 = array();
while($r = mysqli_fetch_assoc($query2)) {
$res["user_name"] = $r["user_name"];
$res["product_ID"] = $r["prod_ID"];
array_push($res2,$res);
}
$response = [];
$response['pageNr'] = $page;
$response['totalPages'] = $totalPages;
$response['products'] = $res2;
Try;
$res = array();
$res2 = array();
while($r = mysqli_fetch_assoc($query2)) {
$res["user_name"] = $r["user_name"];
$res["product_ID"] = $r["prod_ID"];
array_push($res2,$res);
}
$response .= ['pageNr' => $page];
$response .= ['totalPages' => $totalPages];
$response .= ['products' => $res2];

copying json object to javascript array

I want to copy json object to javascript array,
{
"profiledata1":{"id":0,"music":0,"image_x":130,"image_y":155,"mouth_x":0,"mouth_y":-28.125,"active":true,"default":false},
"profiledata2":{"id":1,"music":0,"image_x":130,"image_y":155,"mouth_x":0,"mouth_y":0,"active":true,"default":false},
"profiledata3":{"id":2,"music":0,"image_x":0,"image_y":0,"mouth_x":0,"mouth_y":0,"active":false,"default":false},
"profiledata4":{"id":3,"music":0,"image_x":0,"image_y":0,"mouth_x":0,"mouth_y":0,"active":false,"default":false},
"profiledata5":{"id":4,"music":0,"image_x":0,"image_y":0,"mouth_x":0,"mouth_y":0,"active":false,"default":false},
"upload":"http:\/\/localshost\/",
"format":"jpeg","status":1 }
This is my json object returned when i call some.php through ajax,
I want to copy profiledata1 to userdata_arr[0],profiledata2 to userdata_arr[1],profiledata3 to userdata_arr[2],profile4data to userdata_arr[3],profiledata5 to userdata_arr[5] in java script.
My java script is as follows,
$.ajax({
type: "POST",
url: "some.php",
data: {action:'load',
id:7}
}).done(function(o) {
var data = $.parseJSON(o);
if (!data || data === null) {
someError(true);
}else{
if(data.status==true){
userdata_arr[0] = data.profiledata1[0];
userdata_arr[1] = data.profiledata2[0];
userdata_arr[2] = data.profiledata3[0];
userdata_arr[3] = data.profiledata4[0];
userdata_arr[4] = data.profiledata5[0];
uploadDir = data.upload;
imgFormat = data.format;
somefunction();
}else{
someError(true);
}
}
});
when i execute this script i'm getting userdata_arr as undefined! Please help me to rectify this problem.
I'm also attaching the some.php here,
<?php
if ($_POST['action']=='load') {
$uid=$_POST['id'];
header("content-type:application/json");
// fetch contents from db with $uid;
$query = mysqli_query($link,$sql);
while ($row = mysqli_fetch_array($query)) {
$prof1 = $row['prof1'];
$prof2 = $row['prof2'];
$prof3 = $row['prof3'];
$prof4 = $row['prof4'];
$prof5 = $row['prof5'];
}
$jp1 = json_decode($prof1, 1);
$jp2 = json_decode($prof2, 1);
$jp3 = json_decode($prof3, 1);
$jp4 = json_decode($prof4, 1);
$jp5 = json_decode($prof5, 1);
echo json_encode($dta = array('profile1data' =>json_decode($prof1),'profile2data' =>json_decode($prof2),'profile3data' =>json_decode($prof3),'profile4data' =>json_decode($prof4),'profile5data' =>json_decode($prof5) ,'upload' =>'http://localhost/img/', 'format' =>'jpeg', 'status' =>1 )); ?>
Thanks in advance!
That's because you haven't declared your userdata_arr. To fix it, declare your array/object variable before using it. In your else code-block, do this:
else{
var userdata_arr = {}// declare your object
if(data.status==true){ //proceed to use your already-declared object, also notice the quote marks surrounding the object members/indexes
userdata_arr["0"] = data.profiledata1[0];
userdata_arr["1"] = data.profiledata2[0];
userdata_arr["2"] = data.profiledata3[0];
userdata_arr["3"] = data.profiledata4[0];
userdata_arr["4"] = data.profiledata5[0];
uploadDir = data.upload;
imgFormat = data.format;
somefunction();
}else{
someError(true);
}
}

Why php service do not get variables?

From UI I make call:
$http.post('services/loadCategory.php', {
'id' :'1',
'type' :'string'
}).then(function(response) {
debugger;
...
}, function(response) {
...
});
On PHP service I can't get variables from body POST request:
include ("bd.php");
header("Content-type: text/html; charset=windows-1251");
// ----- ----- ----- ----- -----
if (isset($_POST['type'])) {
$type = $_POST['type'];
}
if (isset($_POST['id'])) {
$id = $_POST['id'];
}
//
exit(json_encode(
array('type' => iconv('windows-1251', 'UTF-8', $_POST['type']),
'id' => iconv('windows-1251', 'UTF-8', $_POST['id'])
)));
Request from service: { id:'', type:'' } How fix that?
When posting JSON to PHP, the $_POST variable is empty. To get the raw JSON in your PHP, use the following:
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$data = json_decode(file_get_contents('php://input'), true);
}
You can then access the data with $data['id'] and $data['type']
Check the incoming $data with print_r($data);
After doing a quick search about this issue, it appears that PHP has a hard time deserializing the POST body sent by AngularJS. AngularJS sends all information JSON encoded (application/json) as compared to most other JavaScript variants which send the content as application/x-www-form-urlencoded.
To fix this, you should either set the content-type of your request to application/x-www-form-urlencoded or you can try one of the solutions below which came from a similar question.
Based on this question, it would seem that the following code (provided by Felipe Miosso) seems to solve the problem:
// Your app's root module...
angular.module('MyModule', [], function($httpProvider) {
// Use x-www-form-urlencoded Content-Type
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
/**
* The workhorse; converts an object to x-www-form-urlencoded serialization.
* #param {Object} obj
* #return {String}
*/
var param = function(obj) {
var query = '', name, value, fullSubName, subName, subValue, innerObj, i;
for(name in obj) {
value = obj[name];
if(value instanceof Array) {
for(i=0; i<value.length; ++i) {
subValue = value[i];
fullSubName = name + '[' + i + ']';
innerObj = {};
innerObj[fullSubName] = subValue;
query += param(innerObj) + '&';
}
}
else if(value instanceof Object) {
for(subName in value) {
subValue = value[subName];
fullSubName = name + '[' + subName + ']';
innerObj = {};
innerObj[fullSubName] = subValue;
query += param(innerObj) + '&';
}
}
else if(value !== undefined && value !== null)
query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
}
return query.length ? query.substr(0, query.length - 1) : query;
};
// Override $http service's default transformRequest
$httpProvider.defaults.transformRequest = [function(data) {
return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
}];
});
Alternatively, you might be able to fix this problem by adding the following line of code to your PHP:
$params = json_decode(file_get_contents('php://input'),true);

ajax to a php and get JSON from it

I have a php file that i connect to it with ajax and callback value is JSON
when i get data from php it dosnt show and when alert data i see Object
Where is my problem ?
PHP:
if(isset($_SERVER["HTTP_X_REQUESTED_WITH"])){
$query = mysql_query("select * from tab");
for ($i=0;$i<mysql_num_rows($query);$i++){
while($row = mysql_fetch_assoc($query)){
$title['t'][i] = $row['title'];
$title['d'][i] = $row['description'];
}
}
echo(json_encode($title));
exit();
?>
JS:
$('#button').click(function(){
$.ajax({
url : "test2.php",
data : $("#tab"),
type : "GET",
success : function(b){
b = eval('('+ b +')');
console.log((b['t']));
alert(b);
}
});
});
How can i get all of data from this JSON and show me corect it ?
Here's a full working example with single row fetch and multi row fetch, without using mysql_ syntax and using prepared statements to prevent sql injections.
And yes, DON'T use mysql specific syntax, like I mentioned here: I cant get the form data to go into database. What am I doing wrong?
function example()
{
var select = true;
var url = '../scripts/ajax.php';
$.ajax(
{
// Post select to url.
type : 'post',
url : url,
dataType : 'json', // expected returned data format.
data :
{
'select' : select // the variable you're posting.
},
success : function(data)
{
// This happens AFTER the PHP has returned an JSON array,
// as explained below.
var result1, result2, message;
for(var i = 0; i < data.length; i++)
{
// Parse through the JSON array which was returned.
// A proper error handling should be added here (check if
// everything went successful or not)
result1 = data[i].result1;
result2 = data[i].result2;
message = data[i].message;
// Do something with result and result2, or message.
// For example:
$('#content').html(result1);
// Or just alert / log the data.
alert(result1);
}
},
complete : function(data)
{
// do something, not critical.
}
});
}
Now we need to receive the posted variable in ajax.php:
$select = isset($_POST['select']) ? $_POST['select'] : false;
The ternary operator lets $select's value become false if It's not set.
Make sure you got access to your database here:
$db = $GLOBALS['db']; // An example of a PDO database connection
Now, check if $select is requested (true) and then perform some database requests, and return them with JSON:
if($select)
{
// Fetch data from the database.
// Return the data with a JSON array (see below).
}
else
{
$json[] = array
(
'message' => 'Not Requested'
);
}
echo json_encode($json);
flush();
How you fetch the data from the database is of course optional, you can use JSON to fetch a single row from the database or you can use it return multiple rows.
Let me give you an example of how you can return multiple rows with json (which you will iterate through in the javascript (the data)):
function selectMultipleRows($db, $query)
{
$array = array();
$stmt = $db->prepare($query);
$stmt->execute();
if($result = $stmt->fetchAll(PDO::FETCH_ASSOC))
{
foreach($result as $res)
{
foreach($res as $key=>$val)
{
$temp[$key] = utf8_encode($val);
}
array_push($array, $temp);
}
return $array;
}
return false;
}
Then you can do something like this:
if($select)
{
$array = array();
$i = 0;
$query = 'SELECT e.result1, e.result2 FROM exampleTable e ORDER BY e.id ASC;';
foreach(selectMultipleRows($db, $query) as $row)
{
$array[$i]["result1"] = $row['result1'];
$array[$i]["result2"] = $row['result2'];
$i++;
}
if(!(empty($array))) // If something was fetched
{
while(list($key, $value) = each($array))
{
$json[] = array
(
'result1' => $value["result1"],
'result2' => $value["result2"],
'message' => 'success'
);
}
}
else // Nothing found in database
{
$json[] = array
(
'message' => 'nothing found'
);
}
}
// ...
Or, if you want to KISS (Keep it simple stupid):
Init a basic function which select some values from the database and returns a single row:
function getSingleRow($db, $query)
{
$stmt = $db->prepare($query);
$stmt->execute();
// $stmt->execute(array(":id"=>$someValue)); another approach to execute.
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if($result)
{
$array = (
'result1' => $result['result1'],
'result2' => $result['result2']
);
// An array is not needed for a single value.
return $array;
}
return false;
}
And then fetch the row (or the single value) and return it with JSON:
if($select)
{
// Assume that the previously defined query exists.
$results = getSingleRow($db, $query);
if($results !== false)
{
$json[] = array
(
'result1' => $results['result1'],
'result2' => $results['result2'],
'message' => 'success'
);
}
else // Nothing found in database
{
$json[] = array
(
'message' => 'nothing found'
);
}
}
// ...
And if you want to get the value of $("#tab") then you have to do something like $("#tab").val() or $("#tab").text().
I hope that helps.
I suggest to use either:
b = jQuery.parseJSON(data)
see more here
or
$.getJSON
instead of eval()

why does getting array length give undefined?

i have this code:
$.getJSON('newMessageDetails', function (json)
{
var old_id = document.getElementById("td_id").value;
var messages_count = Object.keys(json).length;
console.log(messages_count);
console.log(json);
last_id = json[messages_count]["msgId"];
});
the json[messages_count]["msgId"] gives undefined in the console??
my newMessageDetails:
public function executeNewMessageDetails(sfWebRequest $request)
{
$profile_id = $this->getUser()->getAttribute('profile_id','zero');
$new_msgs = RcMessageBoxTablePeer::getNewMessages($profile_id);
$hr=2;
$i=1;
if (count($new_msgs) >= 1)
{
foreach ($new_msgs as $row)
{
$date = $row->getCreatedAt();
//$cd = strtotime($date);
//$newdate = date('Y-m-d H:i:s', mktime(date('h',$cd), date('i',$cd), date('s',$cd), date('m',$cd), date('d',$cd), date('Y',$cd)));
$subject = $row->getSubject();
$message = $row->getMessage();
$from = $row->getProfileIdFrom();
$id = $row->getId();
$uc_record = RcProfileTablePeer::getById($from);
$uc_from = $uc_record->getUniqueCode();
$output[$i] = array("td_date" => $date, "td_subject" => $subject, "td_from" => $uc_from, "td_message" => $message, "msgId" => $id , "i" => $i);
$i++;
}
return $this->renderText(json_encode($output));
}
}
console.log(json) gives:
5
list:98
Object
543: Object
544: Object
545: Object
546: Object
547: Object
i: 1
msgId: 547
td_date: "2011-11-29 11:33:05"
td_from: "CHARLIE000RC"
td_message: "tooltip show message test 2 id 547"
td_subject: "Freechat message"
can some-one explain please? dont know what im doing wrong though
thanks
Objects don't have a length property. try this.
var obj = jQuery.parseJSON(json);
obj.length();
or you can try this.
Object.keys(json).length;
If you would like a count of all keys you could rewrite it to this:
$.getJSON('newMessageDetails', function (json)
{
...;
var messages_count = Object.keys(json).length;
console.log(messages_count);
});
you should just iterate through the object and count . Thats the only way you can really know how many 'meaningful' objects you have in your object.

Categories