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(','));
}
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 an associative array. After I select my records from my table (with two columns: objName,objCost), I want to save them in my array like this:
array(
'objName'=>$row['objName'],
'objCost'=>$row['objCost']
)
How should I do this?
This is my code:
$output = '';
$arr = array();
$sql = "SELECT * FROM obj WHERE objName LIKE '%" . $_POST["search"] . "%'";
$result = $db->query($sql) or die(mysql_error());
if ($result->rowCount() != 0) {
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
//here i should insert my rows into my array
}
$json_arr = json_encode($arr,JSON_UNESCAPED_UNICODE);
echo $json_arr;
} else {
echo 'Data Not Found';
}
According to your code,
$arr[] = ['objName'=>$row['objName'],'objCost'=>$row['objCost']];
Then you can encode the array and pick up the object on the other side with javascript or php. Which ever suits you
json_encode($arr);
In you Ajax success, get the objects and use the values as you deem fit
success: function (data) {data = JSON.parse(data);
for(var i = 0; i < data.length; i++){
alert(data[i].objName);
}
}
see jQuery loop over JSON result from AJAX Success? on how to loop through your results in jquery
I need insert rows into a jQuery DataTable from AJAX. In AJAX I call a PHP file when I make a query to my mySql database, but I get show only a character in rows. It is because the format returned is incorrect, but I can't to parse the correct format.
$query = "..myquery..";
if ($row = mysql_fetch_array($sql)) {
do {
$arr []= $row['name'];
} while ($row = mysql_fetch_array($sql));
echo json_encode($arr); // Here I tried return array without json_encode and a lot of things...
}
I know that the format to add the rows with .DataTable().row.add() is the below, but I do not get the desired format.
[["Element software"], ["Software dist"],["Global envir"], ["Software"], ["Software list"]]
How can I get this format in the echo to returned this??
Thanks!
It is array of arrays, so you need to push an array to $arr, not a string:
$query = "..myquery..";
$arr = []; // init an empty array
// no need to do if() and do{}while() inside. You can just while(){} it
while($row = mysql_fetch_array($sql)){
$arr[]= [$row['name']]; // <== these square brackets do the trick
}
echo json_encode($arr); // still need to json_encode
do{
$arr[]= array($row['name']);
} while ($row = mysql_fetch_array($sql));
echo json_encode($arr);
Note the
$arr[]= array($row['name']);
instead of
$arr []= $row['name'];
One:two run mysql_fetch_array($sql) because php return null;
Two:code ajax for insert table .
$.ajax({
dataType:"json",
url:"recive.php",
type:"POST",
data:{id:id},
success: function(res){
for(var j=0;j<res.length;j++)
{
$("#tabel").append("<table ><tr><td style='width:100%;' > "+res[j].id+"</td></tr></table>");
}
}
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;
?>
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
}