looping over multidimensional array outputs individual characters - javascript

After an ajax call, my php script echos out a json_encoded multidimensional array. When I loop over the array in my javascript, it iterates over each individual character instead of the top-level array elements. Why?
js
$('.test').on('click',function(){
$.ajax({
url: 'http://domain.com/my/script,
}).done(function(multidimensionalArray) {
console.log(multidimensionalArray); //outputs the seemingly correct array
console.log(multidimensionalArray.length); //outputs number of characters (instead of the expected 20...)
})
});
php
public function calledByAjax() {
$items = namespace\items\GetList::getAll(array(
'limit' => 20 // This appropriately limits the results to 20, which is why 20 is expected above in the js
));
$items_array = array();
foreach($items as $key=>$item){
$temp = array (
'attr1' => $item->getPrivateVar1(),
'attr2' => $item->getPrivateVar2(),
'attr3' => $item->getPrivateVar3(),
);
$items_array[$key] = $temp;
}
echo json_encode($items_array);
exit(0);
}
console.log(multidimensionalArray)
[{"attr1":"The variable","attr2":"the variable","attr3":"the variable"},...
...so on for 20 items...
]
console.log(multidimensionalArray.length)
1562

You are not working with an object but with a string.
You need to make sure that the returned output from your php script (a string) gets parsed as json. The easiest way to do that is to specify the dataType:
$('.test').on('click',function(){
$.ajax({
url: 'http://domain.com/my/script',
dataType: 'json' // the expected data type is json,
// jQuery will parse it automatically
}).done(function(multidimensionalArray) {
console.log(multidimensionalArray); //outputs the seemingly correct array
console.log(multidimensionalArray.length); //outputs number of characters (instead of the expected 20...)
})
});

Related

How to split ajax result

$("select#product-id").change(function(){
$("input#product-name").val("Loading...");
var value = $(this).val();
$.ajax({
url: "http://localhost/api/purchase-entry-data.php",
data: {
product_id : value
},
type: "POST",
success: function(data){
$("input#product-name").val(data);
},
error: function (){
$("input#product-name").val("No Data Available");
}
});
});
I am tring to use ajax result in two places (there is two value in the ajax result 1. Product Name, 2. Product Size).
So how to split up that that result in two different values in php.
This depends how you are returning the data back to ajax. There are several ways you can do this.
Using split
In your purchase-entry-data.php file you could return data with a separator then use split to get both values. Just make sure you use a separator that will not be contained in the data returned. Here I used a pipe
echo "productDesc|productSize";
Then in jquery you can split it up and access each element in the array
var result= $(data).text().split('|');
var productDesc = result[0];
var productSize = result[1];
Using JSON
In your php file return the data in an array and JSON
<?php
$arr = array('productDesc' => 'Description', 'productSize' => 'Size');
echo json_encode($arr);
?>
Then in jquery access it like
data = $.parseJSON(data);

Loop Array to Modify Values (JavaScript to PHP and Back to JavaScript)

I'm working with JavaScript and PHP using arrays, the first step is create the array, here
var ListaA=[];
var i = 0, len = options.length;
while (i < len){
var tmp = {
'proyecto':'test',
'pendientes1':0,
'pendientes2':0,
'terminadas1':0,
'terminadas2':0,
'solucion':0
};
ListaA.push(tmp);
i++;
}
Then i send it to my PHP file like this
var laLista = JSON.stringify(ListaA);
$.get("php/operation.php?test="+ {'test' : laLista }, function( data ){
var tmp = {
'proyecto':""+value['proyecto']+"",
'pendientes1':""+value['pendientes1']+"",
'pendientes2':""+value['pendientes2']+"",
'terminadas1':""+value['terminadas1']+"",
'terminadas2':""+value['terminadas2']+"",
'solucion':""+value['solucion']+""
};
ListaA.push(tmp);
});
As you can see above i have ready the code to get the data which represents the array sent by the PHP file, so i got covered that part, my issue here is in my PHP file, here.
$arrayWork = json_decode($_POST['test']);
Then i want to loop, this time, just for testing i'm just taking one of the values and incresing it to watch the result, like this
foreach($arrayWork as $value){
$value['pendientes1']++; // this is not working for me
}
I got the following: "invalid argument supplied in foreach". So, what's wrong with my code? and which is the properly way to loop it and return it to my JavaScript?
I hope you can help me out with this issue. Thank you for your time and attention, good night.
Using this code
$arrayWork = json_decode($_POST['test']);
your json isn't really converted into an associated array, look at below
mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )
assoc
When TRUE, returned objects will be converted into associative arrays.
To convert json object into an array just add true to the second parameter to it
$arrayWork = json_decode($_POST['test'], true);**strong text**
To increment an index value in an array
foreach($arrayWork $key => as $value){
$arrayWork['pendientes1']++;
}
Edited.
also since you are using $_POST method change your ajax from $.get to $.post
$.post("php/operation.php?test="+ {'test' : laLista }, function( data ){
var result = JSON.parse(data); // parse json string into json object
...
});
If you want to read $_POST, you have to make a POST request:
$.ajax({
url:'php/operation.php',
type:"POST",
data: { test: ListaA },
contentType:"application/json; charset=utf-8",
dataType:"json",
success: function(){
...
}
})
You can't use $.post, because you have to set the contentType to JSON.
Important: you don't need to run JSON.stringifyyourself, jQuery will take care of it for you - so pass the original ListaA array.

Preserving order of an associative PHP array while passing it to javascript through ajax

So Here is my php file code
GetUserArray.php
$Users = array('7'=>'samei', '4'=>"chaya", '10'=>'abetterchutia');
echo json_encode($Users);
and this is my ajax request
$.ajax({
url: './GetUserArray.php',
type: 'POST',
dataType: "json",
success: function(users) {
console.log(users);
$.each( users, function( key, value ) {
console.log(key, value);
});
}
});
now what it gives me is in the console is an object sorted by the keys of that array while i want the orignal order which was 7 4 10 in my php file
Object {4: "chaya", 7: "samei", 10: "abetterchutia"}
4 chutiya
7 sali
10 abetterchutia
The problem with using hashmaps is that they don't actually specify order. Though, in PHP, an array is actually an ordered hashmap, so it does. Once you translate that into an object in Javascript, the order is no longer preserved. The only way to guarantee order in Javascript is to use an array.
So in PHP this works as expected and preserves order.
$arr = [4 => "I'm first", 1 => "I'm second", 3 => "I'm third"];
foreach($arr as $value) {
echo $value, "\n";
}
Which gives us
I'm first
I'm second
I'm third
But encode that to Javascript Object Notation (i.e. JSON) and you get an object, because in Javascript arrays don't have keys, they have indexes.
echo json_encode($arr);
Gives us...
{"4":"I'm first","1":"I'm second","3":"I'm third"}
If you tried to do the same in Javascript with this object you might not get the same order
var obj = {"4":"I'm first","1":"I'm second","3":"I'm third"};
var s = "";
for(var x in obj) {
s += + obj[x] + "\n";
}
document.write("<pre>" + s + "</pre>");
This might give you something more like...
I'm second
I'm third
I'm first
So the only way to fix that is to use an array...
json_encode(array_values($arr));
Now this gives us...
["I'm first","I'm second","I'm third"]
And the order is maintained.
However, if you want to preserve the keys as well, you'll have to create an array of objects.
$json = [];
foreach($arr as $key => $value) {
$json[] = [$key => $value];
}
echo json_encode($json);
Now you get...
[{"4":"I'm first"},{"1":"I'm second"},{"3":"I'm third"}]
Which in javascript, works perfectly as expected...
for(var x in obj) {
for(var n in obj[x]) {
obj[x][n]; // now you can both maintain order and have access to the key
}
}

PHP json_encode function is not working on ajax call

In page load I am calling this function
function myFunction(selectedCinemaID) {
$.ajax({
type: "POST",
url: "show_details.php",
data: {cinema_id: selectedCinemaID }
}).done(function( show_list ) {
console.log(show_list.length);
});
And my code in show_details.php
$query = "SELECT * FROM `show` WHERE cinema_id=2;";
$result = mysql_query($query);
if($result){
$show_list = array();
while($row = mysql_fetch_array($result)){
array_push ($show_list, array($row['id'], $row['cinema_id'], row['show_time']));
}
echo json_encode($show_list);
} else {
echo mysql_error();
}
In my database I have only two row and three column but the length showed in the console is 64. But according to the database length should be 2. console.log(show_list) output [["2","2","2014-11-01 01:00:00"],["3","2","2014-11-01 04:00:00"]] but it seems everything here is treated as an array element or string. What is wrong in this code?
You haven't told jquery that you're sending JSON. As such, it'll treat the json text that the server is sending as text. That means
console.log(show_list.length);
is outputting the length of the json string, not the count/size of the array you're building in PHP.
You need either
$.getJSON(....);
or
$.ajax(
dataType: 'json'
...
)
However, note that if your mysql query fails for any reason, then outputting the mysql error message as your are will cause an error in jquery - it'll be expecting JSON, and you could potentially be sending it a mysql error message, which is definitely NOT json.
Once you switch to JSON mode, you should never send anything OTHER than json:
if (query ...)
output json results
} else {
echo json_encode(array('error' => mysql_error()));
}
The JavaScript function .length is counting the length of the entire serialized array string. You need to parse it first:
.done(function( show_list ) {
var data = JSON && JSON.parse( show_list ) || $.parseJSON( show_list );
console.log( data.length );
});
Thanks,
Andrew

Accessing elements within a data structure

I've had a good search and am stumped. It may be a simple answer, but after 80 hours of work so far this week, I just can't see it...
In my app I pass some variables to a Web Service, which passes back a single structure containing key/value pairs.
$.ajax({
type: "POST",
url: "it_submitcall.php",
data: {callService: "getcall", callid: $("#callNumber").val()},
dataType: "HTML",
success: function(data){
//do stuff here
},
error: function(data){
// unable to communicate with web service stuff here
}
});
The response I get back is
Array
(
[CALLID] => 44497
[CALLERNAME] => Chris
[TEAMID] => 1175
)
How do I access the elements above in javascript? Any pointers would be greatly appreciated...
Many thanks.
On the PHP side use json_encode to turn the Array into JSON e.g:
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
Then on the JavaScript side use JSON.parse() to get a JavaScript object back - in your case:
success: function(data){
var obj = JSON.parse(data);
},
As #phenomnomnominal notes, you can use json_encode() on a PHP object to turn it to JSON (and, notably, json_decode() to turn it from JSON to a PHP object)
Once you've got that down, nicely, PHP and JS "hash"-like objects act a lot alike (in PHP, we call these associative arrays and in JavaScript, object literals).
In php, you access an array $your_var like this:
$value = $your_var[ 'key' ];
You can also use variables:
$key = 'key';
$value = $your_var[ $key ];
In JavaScript, it's very similar:
var value = your_var[ 'key' ];
Alternatively:
var key = 'key';
var value = your_var[ key ];
And there's one more syntax that's helpful and more efficient when you don't need variable access to a key:
var value = your_var.key

Categories