Problem: returns array, but not in json.
Result: must return array with in array. outer array has key with numbers and value is array with keys "ID" and "NAME" and there values are assigned from database.
$i = 0;
$json_values = array();
while($sctg = mysql_fetch_assoc($get_sctg)){
$json_values[$i] = array("ID" => $sctg['ID'], "NAME" => $sctg['NAME']);
$i++;
}
echo json_encode($json_values);
Your code is perfectly fine - you just misunderstood the different between arrays and objects in JavaScript.
[{"ID":"4","NAME":"asdasd"},
{"ID":"3","NAME":"LOKS"},
{"ID":"1","NAME":"LOL"}]
This is JSON containing an array with three elements. Each element is an object with the properties ID and NAME.
Let's assume that array is stored in data. You can iterate over the objects in that array with a simple for loop:
for(var i = 0; i < data.length; i++) {
var row = data[i];
// Here you can use row.ID and row.NAME
}
I guess you expected your JSON to look like this:
{
0: {"ID":"4","NAME":"asdasd"},
1: {"ID":"3","NAME":"LOKS"},
2: {"ID":"1","NAME":"LOL"}
}
This would actually be bad since objects in JavaScript are not ordered (even though they actually are in most browsers, but that's not guaranteed!). So when iterating over the rows in such an element (using for(var key in data)), you would not necessarily get the row with ID=4 first just because its key is zero.
However, if you really want an object instead of an array for some reason (you don't!), you could always cast the array to object:
echo json_encode((object)$json_values);
As a side-note, usually it's a good idea to have an object as the top-level element in JSON for security reasons (you can redefine the array constructor and then include something with a top-level array with a script tag and thus access data usually protected by the same origin policy if it was accessed by an XHR request), so I'd change the PHP code like this:
echo json_encode(array('rows' => $json_values));
No need to use $i++; directly use
while($sctg = mysql_fetch_assoc($get_sctg)){
$json_values[] = array("ID" => $sctg['ID'], "NAME" => $sctg['NAME']);
}
and it will return you the JSON
Related
I'm trying to refresh the content of my cells of an table. Therefore, I have a JavaScript which contains an AJAX request to a .php file, which creates my content that I want to insert into my table via JavaScript. The .php files last command is something like echo json_encode($result);.
Back in the JavaScript it says:
var testarray = xmlhttp.response;
alert(testarray);
But the outut from the alert looks like:
{"1":{"1":"3","2":"0","3":"2","4":"0"}}{"1":{"1":"3","2":"0","3":"2","4":"0"},"2":{"1":"2","2":"1","3":"1","4":"1"}}...
So it seems the variable testarray isn't handled as an array but as a string. I already tried var testarray = JSON.parse(xmlhttp.response), but this doesn’t work. Neither does eval() works.
I don't know what to do, so the response of my request becomes an object.
There are 2 strange things in your json:
this part is not json valid: ...}{...
two object should be separated by comas
The notation is object with string indexes not array with int indexes
it should be something like: [[1,2,3,4],[5,6,7,8]]
for the point 1. it looks like you have a loop that concatenate many json
for the point 2. the object notation can be used as an array so it doesn't matter
Some code:
//the folowing code doesn't work: }{ is not parsable
var a=JSON.parse('{"1":{"1":"3","2":"0","3":"2","4":"0"}}{"1":{"1":"3","2":"0","3":"2","4":"0"},"2":{"1":"2","2":"1","3":"1","4":"1"}}');
//the folowing code work and the object can be used as an array
var a=JSON.parse('{"1":{"1":"3","2":"0","3":"2","4":"0"},"2":{"1":"2","2":"1","3":"1","4":"1"}}');
alert(JSON.stringify(a[1]));
//the folowing code displays the real notation of a javascript array:
alert(JSON.stringify([1,2,3,4]));
I think that the problem here might be that your arrays do not have index 0.
e.g. if you output this from the server - it would produce an object:
$result = [];
for ($i = 1; $i < 5; $i++) $result[$i] = $i;
echo json_encode($result); // outputs an object
if you output this from the server - it would produce an array:
$result = [];
for ($i = 0; $i < 5; $i++) $result[$i] = $i;
echo json_encode($result); // produces an array
Anyways, even if your server outputs array as object - you should still be able to access it normally in javascript:
var resp = xmlhttp.responseText, // "responseText" - if you're using native js XHR
arr = JSON.parse(resp); // should give you an object
console.log(arr[1]); // should give you the first element of that object
I have a php array that I assigned to a javascript variable with json_encode. The php array is numerical not associative.
Example: simpleArray[5][7]=1.50. I need to be able to access the 1.50 after the array has been json_encoded based on the index values.
PHP:
$simpleArray= [];
foreach($childProducts as $child) { //cycle through simple products to find applicable
$simpleArray[$child->getVendor()][$child->getColor()] = $child->getPrice();
var_dump ($simpleArray);
}
Javascript:
var simpleArray = <?=json_encode($simpleArray)?>;
//..lots of unrelated code
for(var i=0; i < IDs.length; i++)
{
console.log(simpleArray);//see the picture of me below
var colorSelected = $j("#attribute92 option:selected").val(); //integer value
$j('.details'+data[i].vendor_id).append('<li class="priceBlock">$'+simpleArray[i][colorSelected]+'</li>');
}
Console.log(simpleArray):
Here you are likely trying to access values that don't exist in your object:
simpleArray[i][colorSelected]
Based on your for loop definition, you can have i values of 0, 1, 2 which don't exist in the object shown (which has properties at keys: 3,4,5). Also your for loop has no relation at all to the number of items in your object, which I am not sure is intended.
Also, colorSelected derives it's value from a call to val() which returns a string you you probably want to change the line where it is defined to:
var colorSelected = parseInt($j("#attribute92 option:selected").val());
This will make it an integer value.
I have a PHP array that has a table id as the key and a table field as the value.
Example PHP:
while($row = mysql_fetch_array($result))
{
$id = $row['id'];
$array[$id] = $row['some_field'];
}
I then use json_encode($array) to get something like:
{"id1":"value1","abc":"123","xyz":"789"}
How can I loop through this in jQuery? From what I have found so far it seems like I need to know the key. So:
var obj = jQuery.parseJSON(jsonVar);
alert(obj.abc); //prints 123
But how can I get these values if I don't know the keys since they are dynamic?
Do I need to restructure my PHP array?
Once you encode an associative array in php into a JSON object it is no longer an array, it is an object with keys and values. You can iterate through them in javascript using for..in
for (var key in obj) {
console.log(obj[key]);
}
Note: for..in does not garuntee order, if you need to ensure order you will have to make your array indexed, instead of key=>value, and use a for loop (or while) instead.
You can get the keys of your array using Object.keys, then loop through them. Unlike for...in, this gives you the option to .sort() the keys before processing them:
var keys = Object.keys(obj).sort(); // sorting is optional
for (var i=0; i<keys.length; i++) {
var key = keys[i],
val = obj[key];
console.log(key+":"+val);
};
In older browsers, you'll need a polyfill to enable the Object.keys method. MDN has one on their documentation page.
I am trying to change the class of a list of elements based on information in a DB. I figure the easy way was via an array. I build the array on the php side as follows.
$setClassResult = array();
while($row = mysql_fetch_array( $result ))
{
$setClassResult= array_push_assoc($setClassResult, $row['item_id'], $row['parent']);
}
echo json_encode(array($setClassResult));
break;
which give me....
[{"830":"0","734":"830","733":"830","732":"830","735":"830","737":"830","736":"830","738":"830","739":"830","740":"830","741":"830","742":"830","872":"0","869":"872","868":"872","880":"872","964":"872"}]
to decode and change the elements I use.....
$.each(data, function(key, val) {
$("#recordsArray_"+key).toggleClass(val);
alert(key+" "+val);
});
The alert happens once with 0[object,Object] Is this because of the way I created the array? The first thing I notice wrong is the [ and ] around the JSON.
No need to add extra array, try with :
echo json_encode($setClassResult);
Your result is in array of object format:
[{"830":"0","734":"830","733":"830","732":"830","735":"830","737":"830","736":"830","738":"830","739":"830","740":"830","741":"830","742":"830","872":"0","869":"872","868":"872","880":"872","964":"872"}]
So when you iterate, it iterates through array first & says key is 0 & value is an object.so, if you later iterate through value which is an object, you will get it
or as soju if u dont require to store it in array of objects but a single object & iterate once.
I'm creating an array on the jquery side this way. The array is an array of arrays where each element is an array that looks like [jskey, jsvalue].
var jsarray = [];
// jsarray.push([jskey, jsvalue]);
jsarray.push([1, 123]);
jsarray.push([2, 98]);
jsarray.push([3, 107]);
jsarray.push([4, 34]);
I then add the array to an element of a form before it's submitted
$('#myform input[name=jsvalues]').val(jsarray);
On the php side, I'm expecting to receive an array of array, but all I get when I do a print_r() or var_dump() is a string that looks like this
string() "1,123,2,98,3,107,4,34"
Attribute values are strings. When you convert an array to a string, you get each element in that array converted to a string and separated by commas (unless you override the toString() method (hint: don't)).
I suggest converting the array to JSON and then assigning that to the form control. You can then parse the JSON in PHP.
http://json.org has links (at the bottom) to PHP and JS implementations of JSON serializers / deserializers.
David Dorward gave a really good solution.
To clarify a little bit, when you assign a complex object (like an array) to the attribute of a HTML element (that's what jQuery does when you call val()), the object is converted into a string (by calling the toString method on the object).
An array has a toString method that does exactly what you are experiencing: a list of the values inside the array separated by commas:
[1, [2, 3]].toString(); // returns "1,2,3"
To transmit complex objets, you can use JSON (JavaScript Object Notation) which is native in JS:
$('#myform input[name=jsvalues]').val(JSON.stringify(jsarray));
On the server side, PHP 5 has a really fast JSON API:
$jsvalues = json_decode($_POST['jsvalues']);
You could convert that string back into an array of arrays, assuming they were all pairs:
$arr = explode(",", $_POST['jsvalues']);
$jsvalues = array();
for ($i = 0; $i < count($arr); $i += 2) {
$jsvalues[] = array($arr[$i], $arr[$i + 1]);
}