I have an array of People objects. I'm sending them to PHP but the way to get my objects back in PHP so I can manipulate them seems convoluted. Here's what I have, but it doesn't seem to return anything back to my AJAX Call. Right now I just have 1 Person Object in my array but I want to make sure everything is fine before I advance. In short, when I decode my JSON shouldn't it convert it to an Object in PHP? In the end I want an array of PHP objects that are People
Jquery
var people = new Array();
var person = new Person("Michael", "Jackson", 50);
localStorage.setItem(person.firstName + " " + person.lastName, JSON.stringify(person));
function Person(firstName, lastName, age)
{
this.firstName=firstName;
this.lastName=lastName;
this.age=age;
}
function getStorage(){
var tempPerson;
for(var i = 0; i < localStorage.length; i++)
{
tempPerson = $.parseJSON(localStorage.getItem(localStorage.key(i)));
people.push(tempPerson);
}
}
function getPeople(){
$.post(
"people.php",
{people : people},
function(data)
{
alert(data);
}
);
}
getStorage();
getPeople();
PHP
<?php
$personObj = Array();
$people = $_POST['people'];
for($i = 0; $i < count($people); $i++)
{
foreach($people[$i] as $person)
{
$streamObj = json_decode($person);
}
}
echo $personObj->$firstName;
In addition to making the change suggested by #Even Hahn, you need to change the data you are posting as follows:
$.post(
"people.php",
{people : JSON.stringify(people)},
function(data)
{
alert(data);
}
);
This way a single name/value pair is posted. The name is "people" and the value is a JSON encoded string of the array of Person objects.
Then when you call the following in the PHP code, you are decoding that JSON encoded string into an array on the PHP side.
$people = json_decode($_POST['people']);
I also see where you assign $personObj to an array, but I don't see where you put anything in the array.
Try moving your JSON decoding in your PHP:
$personObj = Array();
$people = json_decode($_POST['people']);
for($i = 0; $i < count($people); $i++)
{
foreach($people[$i] as $person)
{
$streamObj = $person;
}
}
echo $personObj->$firstName;
This is because $_POST['people'] is a JSON string which needs to be decoded.
Perhaps the PHP codes should be look like this:
<?php
$personObj = Array();
$people = $_POST["people"];
foreach($people as $p)
{
$val = str_replace("\\","",$p);
$personObj = json_decode($val);
}
echo $personObj->firstName;
?>
Related
Right now I have this PHP:
$columns = array(*/Data*/);
echo json_encode($columns);
And this is sent through an AJAX GET request with JQuery.
var columns = jQuery.parseJSON(response);
I would like to be able to send more than one array in the json_encode() is there any way to do this and how would you parse it with jQuery?
Sure, you could send an array of array. PHP associative array will become a javascript object.
In PHP:
$data = array();
$data['fruits'] = array('apple','banana','cherry');
$data['animals'] = array('dog', 'elephant');
echo json_encode($data);
and then on jQuery
var data = jQuery.parseJSON(response);
then you could then do something like this to access the values
console.log(data.fruits[0]); // apple
console.log(data.animals[1]); // elephant
The code should be like the following:
$columns = array(/*Data*/);
$columns1 = array(/*Data1*/);
echo json_encode(array($columns,$columns1));
in jQuery use
var columns_array=jQuery.parseJSON(response);
columns=columns_array[0];
columns1=columns_array[1];
$data1 = array();
$data2 = array();
$data1[] = array('apple','banana','cherry');
$data2[] = array('dog', 'elephant');
echo json_encode(array($data1,$data2));
in ajax,
console.log(response[0][0])//apple
console.log(response[1][0])//dog.....
After you have populated all the arrays namely $array1_json, $array2_json etc in my case,
$number_of_array1elements = count($array1_json);
$number_of_array2elements = count($array2_json);
$number_of_array3elements = count($array3_json);
array_unshift($array1_json , $number_of_array1elements);
// pushes element to the start of array1_json
array_unshift($array2_json , $number_of_array2elements);
array_unshift($array3_json , $number_of_array3elements);
and similarly for other arrays.
echo json_encode( array_merge($array1_json, $array2_json, $array3_json) );
In your .js file, use:
var val = xmlhttp.responseText;
var jsonData = JSON.parse(val);
var number_of_array1elements = jsonData[0];
for (var i = 1; i <= number_of_array1elements; i++ )
{
// use jsonData[i] to select the required element and do whatever is needed with it
}
var number_of_array2elements = jsonData[i];
for ( i = i+1; i <= number_of_array1elements+number_of_array2elements+1; i++ )
{
// use jsonData[i] to select the required element and do whatever is needed with it
}
I have Json Data with multiple array, and i try to get the data inside effect_property, but it keep return nothing.
Here is my code
$json = file_get_contents('data.json');
$json_data = json_decode($json,true);
for($i = 0; $i < $count_data_action; $i++){
$path_data_action = $json_data[t03_action][data][$i][effect_property];
}
when i print the $path_data_action it show something like this:
{"duration":1,"delay":0,"propTo":{"source":"image","source_path":"../uploads/17041409353289557288/","source_file":"1704141604180616.jpg","source_name":"image1.jpg"},"beforeAction":"0","action_order":"1"}
How can i get the source_path?
Probably the JSON you are decoding with :
$json_data = json_decode($json,true);
contains another JSON string at key effect_property. You could change that to JSON Object and it should work fine.
Otherwise, you could use json_decode again, like :
for($i = 0; $i < $count_data_action; $i++){
$path_data_action = $json_data[t03_action][data][$i]effect_property];
$pathDataActionArr = json_decode($path_data_action , true);
$sourcePath = $pathDataActionArr['propTo']['sourcePath'];
}
Furthermore, to know any last occurred error with JSON encoding/decoding
json_last_error — Returns the last error occurred
UPDATE : I tried to decode the JSON you posted with code :
$fileContent = file_get_contents("/home/tarun/Desktop/test/abcd");
$jsonArray = json_decode($fileContent,true);
var_dump($jsonArray['t03_action']['data'][9]['effect_property']);
$effectPropertyArr = json_decode($jsonArray['t03_action']['data'][9]['effect_property'],true);
if(isset($effectPropertyArr['propTo']['source_path'])) {
var_dump($effectPropertyArr['propTo']['source_path']);
} else {
var_dump("No such key!");
}
Here, not all your elements of the array at key effect_property contains source_path. That's why :
if(isset($effectPropertyArr['propTo']['source_path'])) {
The above is working fine, with output :
/home/tarun/Desktop/test/temp.php:6:
string(205) "{"duration":1,"delay":0,"propTo":{"source":"image","source_path":"../uploads/18032022375907620062/","source_file":"1804100413270066.jpg","source_name":"Penguins.jpg"},"beforeAction":"0","action_order":"1"}"
/home/tarun/Desktop/test/temp.php:10:
string(32) "../uploads/18032022375907620062/"
// decoded array passed key of that array
$json_data['propTo']['source_path'];
try this ,Its working for me.
var data = {"duration":1,"delay":0,"propTo":{"source":"image","source_path":"../uploads/17041409353289557288/","source_file":"1704141604180616.jpg","source_name":"image1.jpg"},"beforeAction":"0","action_order":"1"}
alert(data.duration);
var Prop = data.propTo;
alert(Prop.source_path);`enter code here`
I'm sitting on this for a long time and can't find a solution:
By using the function json_ encode in php file (script below) i receives data from mysql as group of arrays e.g. ["9,8","15,14","18,17","29,40,10,9"],in the main file by use $.parseJSON function(script below),
receives a array with indexed object as ["9,8","15,14","18,17","29,40,10,9"....]
instead [9,8,15,14,18,17,29,40,10,9],
How merge all this object together??
I tried to use $.merge function, but doesn't work.Help??;-)
/////receive.php file//////
$ask = mysql_query("SELECT numbers FROM bying");
if(!ask)
{
die('incorrect ask'.mysql_error());
}
else{
$tab = array();
while ($row = mysql_fetch_assoc($ask))
{
$data=$row['numbers'];
array_push($tab,$data);
}
echo json_encode($tab);
mysql_free_result($ask);
}
html file with $.parseJSON function
$.post('receive.php', function(data)
{
var table1=[];
table1 = $.parseJSON(data);
var numbers=$.merge([],table1);)
for(var i=0;i<numbers.length;i++)
{
alert(numbers[i]);
}
}
It looks as $data is a comma separated string of numbers, if so, you can slit it on commas and then merge the two arrays:
$ask = mysql_query("SELECT numbers FROM bying");
if(!ask)
{
die('incorrect ask'.mysql_error());
}
else {
$tab = array();
while ($row = mysql_fetch_assoc($ask)) {
$data = explode( ',', $row['numbers'] );
$tab = array_merge( $tab, $data );
}
echo json_encode($tab);
mysql_free_result($ask);
}
Why not do it the 'obvious' way and iterate through the array yourself splitting each string on ',' and appending each parsed number to an array you construct as you go?
e.g.
var newNums = [];
for (var i=0; i<table1.length; i++) {
newNums = newNums.concat(table1[i].split(','));
}
A server sends me a $_POST request in the following format:
POST {
array1
{
info1,
info2,
info3
},
info4
}
So naturally, I could extract the info# very simply with $_POST['#info'].
But how do I get the the three info's in the array1?
I tried $_POST['array1']['info1'] to no avail.
Thanks!
a:2: {s:7:"payload";s:59:"{"amount":25,"adjusted_amount":17.0,"uid":"jiajia"}";s:9:"signature";s:40:"53764f33e087e418dbbc1c702499203243f759d4";}
is the serialized version of the POST
Use index notation:
$_POST['array1'][0]
$_POST['array1'][1]
$_POST['array1'][2]
If you need to iterate over a variable response:
for ($i = 0, $l = count($_POST['array1']); $i < $l; $i++) {
doStuff($_POST['array1'][$i]);
}
This more or less takes this shape in plain PHP:
$post = array();
$post['info'] = '#';
$post['array1'] = array('info1', 'info2', 'info3');
http://codepad.org/1QZVOaw4
So you can see it's really just an array in an array, with numeric indices.
Note, if it's an associative array, you need to use foreach():
foreach ($_POST['array1'] as $key => $val) {
doStuff($key, $val);
}
http://codepad.org/WW7U5qmN
try
$_POST['array1'][0]
$_POST['array1'][1]
$_POST['array1'][2]
You can simply use a foreach loop on the $_POST
foreach($_POST["array1"] as $info)
{
echo $info;
}
or you can access them by their index:
for($i = 0; $i<sizeof($_POST["array1"]); $i++)
{
echo $_POST["array1"][$i];
}
I load a php/json file. This is my json file:
echo '{';
echo '"position":[';
while($inhoud = mysql_fetch_array($result))
{
echo '{';
echo '"lat":"'.$inhoud['lat'].'",';
echo '"long":"'.$inhoud['long'].'",';
echo '}';
}
echo ']}';
This works. I want to load it in my javascript and do it like this:
$.getJSON('req/position.php', function(data) {
$.each(data, function(key, val) {
newLatLng = key;
});
});
but this doesn't work. It loads the file but i don't get this data. What should i do?
Thanks,
I think you have some syntax errors in the JSON output.
When you output "long" data, you append a comma , at the end, but you should not, because "long" is the last key of the object.
You print out an object in a while cycle. These objects are part of an array. So, except for the last one, you have to append a comma , after the closing }.
And, if I can ask, why you are not using the json_encode() PHP function, instead of build all the JSON string manually? With it, you build all the data as normal PHP array, and then encode (translate) it in JSON. You will avoid all these annoying syntax stuffs.
Just try it:
$data = array();
$data['position'] = array();
while($inhoud = mysql_fetch_array($result))
{
$data['position'][] = array(
"lat" => $inhoud['lat'],
"long" => $inhoud['long']
);
}
echo json_encode($data);
You have your co-ordinates defined in the array named position. You need to iterate through that. The Array contains objects with the properties lat and long. If you want to use the values, you should try something like:
$.getJSON('req/position.php'), function(data){
$.each(data.position, function(index, value){
var newLatLng = { latitude: value.lat, longitude: value.long };
});
});
Return proper header in PHP script
header('Content-type: application/json');
And it should work.
Also use json_encode to encode PHP values into valid JSON.
Constructing JSON in php through strings works but is primitive. Start constructing an array and use json_encode().
$arr = array();
while($inhoud = mysql_fetch_array($result)){
$temp = array();
$temp['lat'] = $inhoud['lat'];
$temp['long'] = $inhoud['long'];
$arr[] = $temp;
}
echo json_encode($arr);
If all that you select in your mysql query is 'lat' and 'long' you could also just place $inhoud into $arr inside your while loop like so.
while($inhoud = mysql_fetch_array($result)){
$arr[] = $inhoud;
}
If you do this just make sure you only select columns in your mysql query that you would want to output in JSON.
$.getJSON('req/position.php', function(data) {
var obj = JSON.parse(data);
// At this point, obj is an object with your JSON data.
});
Source: MDN