Symfony send array with objects to javascript - php

How is it possible to send an array of objects (entity) back to Javascript after an Ajax request?
If I return the array with the objects with a JSON response, the array is empty in Javascript.
Dump of array:
array:2 [
0 => App\Entity\Firewalls {#744
-id: 2
-ip: "test.com"
-user: "admin"
-pass: "pw"
-status: App\Entity\Status {#741
-id: 2
-status: "Finalize"
-update: null
-time: null
-firewall: App\Entity\Firewalls {#744}
}
}

Do you have composer require symfony/serializer ? if not I recommend you use it.
You can the use symfony object normalizer and serialize an entity (or array of entities) into a json.
Create a serializer:
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;
$encoders = [new XmlEncoder(), new JsonEncoder()];
$normalizers = [new ObjectNormalizer()];
$serializer = new Serializer($normalizers, $encoders);
And use it with your entity or entities:
$this->serializer->serialize($data, 'json');
You can read more about this here.

I'd encode the json first like
$firewalls = [ 'your', 'firewalls' ];
$json = json_encode($firewalls);
echo $json;
then parse it back
$.ajax({
type: "POST",
url: "server.php",
dataType: "json",
success: function (firewalls) {
console.log(firewalls);
}
});
if the datatype is set as json, jQuery should automatically parse it. If it doesn't work, feel free to share what the browser's developer tools say.

Related

AngularJS - $http GET response is always [object Object]

I am just trying to fetch an array of key value pairs from PHP and send the response back to AngularJS $http GET request:
PHP Code get_projects.php file:
<?php
header('Content-Type: application/json');
$data = [{"id" => 1, "name" => 'Audi'}, {"id" => 2, "name" => 'BMW'}, {"id" => 3, "name" => 'Honda'}];
$encode = json_encode($data);
echo $encode;
?>
AngularJS Controller code:
app.controller('MainController', ['$scope', '$http', function ($scope, $http) {
$scope.name = 'Search';
$scope.projects = '';
$http({
method: 'GET',
url: 'includes/get_projects.php',
params: {}
}).then(function success(response) {
$scope.projects = response.data;
alert($scope.projects);
});
}]);
The alert($scope.projects); always returns [object Object]. The echo gettype($encode); prints string but the alert statement prints [object Object]. I have tried angular.fromJson() but still it prints [object Object].
I am really confused with the concept of json_encode() function in PHP. Please help me fix the problem.
You converted the PHP array to a string by serializing it using JSON. $encode therefore is a string, which is fine.
Your frontend now gets the response and (since it came with the content type of application/json) already deserialized it for you from a JSON string to a JavaScript object.
Attempting to convert an object to a string will give you something like [object Object]. alert isn't the right tool here since it can work with a string only.
Try console.log instead and check your devtools console output, there you'll see an explorable object. (Even better: In your devtools debugger, set a breakpoint in the success handler and inspect the object at that point.)
Bottom line: It's all working fine, you just didn't use the right method to look at your object.
#CherryDT I think i fixed the problem.
var make = [];
for (var key in response.data) {
if(response.data.hasOwnProperty(key)){
make.push({
"id": response.data[key].id,
"name": response.data[key].name
});
}
}
$scope.projects = JSON.stringify(make);
$scope.projects = angular.fromJson($scope.projects);
PHP send the array as string with json_encode.
AngularJS response.data takes the response as Object.
Loop through the response.data object and push the key/values to variable make.
Create a string with JSON.stringify.
Convert the JSON string to Object using angular.fromJson.
I have viewed couple of blogs which assign the response.data object directly to $scope variable but in my case it did not work.
AngularJS version i am using is : AngularJS v1.2.8

Unable to access object properties from URL params in Laravel

I am trying to access object properties from a request from my Angular app. I am using Laravel 5.1
Angular:
console.log('getQuestionAnswers', params);
return $http({
method: 'GET',
url: url + ver + '/questions/checkMany',
params: {
'questions[]' : params
},
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer ' + $rootScope.access_token
},
cache: true
});
Console.log of params:
Laravel:
public function getAnswers(Request $request)
{
$input = $request->all();
$question_objs = $input['questions'];
foreach ($question_objs as $question_answer_object) {
return $question_answer_object;
Response to Angular with: return $question_objs;
Response to Angular with: return $question_answer_object;
Looks like so far so good!
But if I try to access a property within laravel, like question_id:
return $question_answer_object['question_id'];
I get error:
"Illegal string offset 'question_id'
Laravel already parses the JSON,
// From Illuminate/Http/Request.php all() method:
if (! isset($this->json)) {
$this->json = new ParameterBag((array) json_decode($this->getContent(), true));
}
and when I return it, I can see it's an object. Why can't I access the properties? I've also tried json_decode without luck.
With JSON Decode:
$test = json_decode($question_answer_object, true);
return $test['question_id'];
This seems to work. But why?
Accessing the property on the object as such:
return $question_answer_object->question_id;
Gives the following error:
"Trying to get property of non-object"
The $question_answer_object['question_id'] variable is a string comprising JSON encoded data; to access that, you need to decode it first:
$decoded= json_decode($question_answer_object['question_id'], true);
return $decoded['question_id'];
If you're not sending the request as application/json, use $request->json().
You can get some information about this issues here.
Returned question is an object, not an array. You have to acces it with ->
return $question_answer_object->question_id;

How to get the POST request entity using Slim framework

I have sent JSON data using android java by setting it in the post entity like this:
HttpPost httpPostRequest = new HttpPost(URLs.AddRecipe);
StringEntity se = new StringEntity(jsonObject.toString());
httpPostRequest.setEntity(se);
How can I receive this json data in the php , where I am using Slim framework ?
I have tried this:
$app->post('/recipe/insert/', 'authenticate', function() use ($app) {
$response = array();
$json = $app->request()->post();
});
JSON is not parsed into $_POST superglobal. In $_POST you can find form data. JSON you can find in request body instead. Something like following should work.
$app->post("/recipe/insert/", "authenticate", function() use ($app) {
$json = $app->request->getBody();
var_dump(json_decode($json, true));
});
You need to get the response body. Save it in a variable. After that, verify if the variable is null and then decode your JSON.
$app->post("/recipe/insert/", "authenticate", function() use ($app) {
$entity = $app->request->getBody();
if(!$entity)
$app->stop();
$entity = json_decode($entity, true);
});

ZendFramework2 on ExtJS Grid Example (how to send json output correctly in zf2)

Firstly, sorry for my not very good english.
Problem:
I am trying to run extJS grid example using zf2. I am using this example.
What I need to do:
make array of objects in php
json_encode(this array)
accept json data in extjs script
easy! but I had problem.
How correctly send json data in zend framework2?
In example there was 'data.php' file where json output was created and outputed. How to make same in zf2?
I tried next steps. I created new action in Controller jsonAction() with this content:
public function jsonAction()
{
$view = new ViewModel();
$view->setTerminal(true); // turn off layout
$arr = array();
// creating data array to encode
$arr[] = new Student('Vlad', 'Sharikov');
$arr[] = new Student('Alina', 'Zaja');
$arr[] = new Student('Kam', 'Nurm');
$arr[] = new Student('Seva', 'Paren');
$arr[] = new Student('Dima', 'Glush');
//json output
echo '({"total":"'.count($arr).'","results":'.json_encode($arr).'})';
return $view;
}
View json.phtml is empty:
So, json output is available here: zf2/grid/json (zf2 is localhost domain)
Json output:
({"total":"5","results":[{"firstname":"Vlad","lastname":"Sharikov"},{"firstname":"Alina","lastname":"Zaja"},{"firstname":"Kam","lastname":"Nurm"},{"firstname":"Seva","lastname":"Paren"},{"firstname":"Dima","lastname":"Glush"}]})
Now I need to configure extjs script.
Ext.onReady (function () {
// create the data store
var store = new Ext.data.SimpleStore({
totalProperty: 'total', // total data, see json output
root: 'results', // see json output
url: 'http://zf2/grid/json',
fields: [
{name: 'firstname'},
{name: 'lastname'}
]
});
// load data
store.loadData({params:{start: 0, limit: 5}});
// create the grid
var grid = new Ext.grid.GridPanel({
store: store,
columns: [
{header: 'Firstame', width: 200, dataIndex: 'firstname'},
{header: 'Lastname', width: 200, dataIndex: 'lastname'}
],
stripeRows: true,
height:180,
width:450,
title:'I504 group',
bbar: new Ext.PagingToolbar({
pageSize: 5,
store: store,
displayInfo: true,
displayMsg: 'Displaying topics {0} - {1} of {2}',
emptyMsg: "No topics to display"
})
});
// render grid to the grid-example element (see p array-grid.html)
grid.render('grid-example');
});
There are url-field in 6 row. What I have to put there to make grid draws correctly? thats the question.
Or may be I am not right with my assumption that json should be created like I did (make controller etc). Sure, I am newbie. So suggest correctly way to do this, please.
Seems that you got it working, however, if you're interested in doing things a more ZF2 way, you can do the following:
1) Add ViewJsonStrategy to your view_manager config module.config.php:
<?php
'view_manager' => array(
// ...
'strategies' => array(
'ViewJsonStrategy',
)
),
2) In your controller, just construct the structure you want, and return a JsonModel:
<?php
namespace Application\Controller;
use Zend\View\Model\JsonModel;
class SomeController {
public function someAction(){
$arr = array();
// creating data array to encode
$arr[] = new Student('Vlad', 'Sharikov');
$arr[] = new Student('Alina', 'Zaja');
$arr[] = new Student('Kam', 'Nurm');
$arr[] = new Student('Seva', 'Paren');
$arr[] = new Student('Dima', 'Glush');
return new JsonModel(array('total'=>count($arr), 'results' => $arr));
}
}
Problem solved. Thank you!
Firstly, creating store:
var store = new Ext.data.JsonStore({
totalProperty: 'total', // total data, see json output
root: 'results', // see json output
url: './json',
fields: [
'firstname', 'lastname'
]
});
1) JsonStore, not SimpleStore; 2) fields : 'firstname', 'lastname' is engouht (not need {...})
Secondly,
Not!: store.loadData({params:{start: 0, limit: 5}});
This one is ok: store.load({params:{start: 0, limit: 5}});

Can't pass multidimentional array to php with ajax

Array I am trying to pass:
var params = [];
params['request'] = "movies";
params['param'] = [];
params['param']['sortBy'] = "title";
params['param']['sortOrder'] = "asc";
Ajax call:
return $.ajax({
type: "POST",
url: "http://192.168.0.100:83/getData.php",
cache:false,
data: params,
dataType:"json",
success: function(data){
if(data != null){
console.log(data);
}
Problem is that the php script only receives $_POST['request'], params is non-existent.
If I view params array in the console log before the ajax call I see this:
[request: "movies", param: Array[0]]
length: 0
param: Array[0]
length: 0
sortBy: "title"
sortOrder: "asc"
__proto__: Array[0]
request: "movies"
__proto__: Array[0]
It seems like the problem could be that "param" parameter is not passed because it is seen as empty (it is not, at least before it is passed to ajax call), but why this is happening I have no idea. What am I missing here?
You have declared params as an array [] but assigned object properties to it using the ["string"] notation. This resulted in empty arrays with additional properties appended to the Array object.
Instead, it should have been declared as an object literal, with another object literal nested inside.
var params = {
request: "movies",
param: {
sortBy: "title",
sortOrder: "asc"
}
};
The structure of the $_POST should be something like:
Array
(
[request] => movies
[param] => Array
(
[sortBy] => title
[sortOrder] => asc
)
)
You could send the data as JSON and decode it in php using json_decode():
$.ajax({
data: { paramData: JSON.stringify( params),
/* other ajax options*/
})
Then in php receive it with:
$params= json_decode($_POST['paramData']);
echo $params['request']; /* should return "movies" as response*/
Include json2.js library for older browsers that don't support JSON methods
EDIT: after a little testing will definitely need to change params to object and params.param to object, Changing [] to {} will accomplish this:
var params = {};
params['request'] = "movies";
params['param'] = {};
params['param']['sortBy'] = "title";
params['param']['sortOrder'] = "asc";
DEMO: http://jsfiddle.net/germk/2/

Categories