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
}
Related
The data returned by an API is in this format
[{"name":"Agnes ","amount":"40000"},{"name":"John","amount":"35000"},{"name":"Joyce","amount":"50000"},{"name":"Peter","value":"45000"}]
I want to re-format that output so that it looks like this:
Agnes-40000, John-35000, Joyce-50000, Peter-45000
So, I wrote something like this, letting $data represent the returned data above;
$new = json_decode($data);
foreach ($new as $key => $jsons) {
foreach($new as $key => $value) {
echo $value;
echo ",";
}
}
But the output I get is like: Agnes,40000, John,35000, Joyce,50000, Peter,45000
How do I write the javascript to display the data like
Agnes-40000, John-35000, Joyce-50000, Peter-45000
You have an array of objects. You need to concatenate the name and value properties.
$array = json_decode($data);
foreach ($array as $el) {
echo "{$el->name}-{$el->value},";
}
var jsonFromServer = '[{"name":"Agnes ","amount":"40000"},{"name":"John","amount":"35000"},{"name":"Joyce","amount":"50000"},{"name":"Peter","value":"45000"}]';
var json = JSON.parse(jsonFromServer);
var arrResult = []; // if array
//var textResult = ''; // if string
if(json && json.length){
for(var j = 0, jLen = json.length; j < jLen; j++){
var obIn = Object.values(json[j]);
var map = obIn.map(function(el){
return el.trim();
});
var res = map.join('-');
arrResult.push(res);
//textResult += res;
};
};
console.log(arrResult); // if array
//console.log(textResult); // if string
console result ["Agnes-40000", "John-35000", "Joyce-50000", "Peter-45000"]
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;
?>
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(','));
}
I'm working on passing 2 fields of SQL through php to javascript. I have read many tutorials on how to create a multidimensional javascript array. Where I get confused is how to code from php to javascript. I have seen a couple of tutorials on how to get the php data to javascript, but none on how to do this with 2 dimensions.
My first hangup is that if I'm creating a multidimensional array I need to count the number of records in my sql data before I declare the java array right?
update:
I got the data to JSON format as suggested below. Is there a way for me to get all of the contents printed to the web page so that I can see them and then narrow down what is displayed?
update III:
code:
mysql_connect("localhost", "bikemap", "pedalhard") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
$data = mysql_query("SELECT * FROM gpsdata");
$new_row = array();
$new_column = array();
while($info = mysql_fetch_array($data)){
foreach( $info as $row_num => $row)
{
$thisItem = $row;
$new_row[] = $thisItem;
}
array_push($new_column = $new_row);
}
$json = json_encode($new_column);
echo $json;
?>
Working code:
$data = mysql_query("SELECT * FROM gpsdata");
$aData = array();
while($row = mysql_fetch_assoc($data))
$aData[$row['idgpsdata']] = array($row['userID'],$row['date'],$row['lat'], $row['longi'], $row['alt']);
$json = json_encode($aData);
echo $json;
Fill a PHP array first, it's easier than building the string for a javascript array. Then - as ThiefMaster said as comment - use JSON to make the javascript array.
In PHP, you can use JSON PECL extension
<?php
$arr = array( 1=>array(3,4),
2=>array(4,5));
$json = json_encode($arr);
echo $json;
?>
Output
{"1":[3,4],"2":[4,5]}
In Javascript
var obj = JSON.parse('{"1":[3,4],"2":[4,5]}');
for(var i in obj){
for(var j in obj[i]) {
console.log(obj[i][j]);
}
}
JSON.Parse is for Gecko (Firefox alike), for cross-browser javascript JSON parse check jQuery.parseJSON or https://stackoverflow.com/search?q=json+parse+javascript
Sample implementation in PHP/jQuery, would be something like this:
json.php
$arr = array( 1=>array('Name', 'Age'),
2=>array('Fares','18'));
$json = json_encode($arr);
echo $json;
json.html
<html><head></head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<script>
$.getJSON('json.php', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
});
</script>
</body>
</html>
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
}