I've looked around for a Javascript/jQuery function which emulates PHP's json_encode, but all the ones I find (listed bellow) don't work.
http://code.google.com/p/jquery-json/
http://phpjs.org/functions/json_encode:457
To check if it wasn't my array wasn't faulty I used phpjs var_dump with expected results.
Can anyone point me in the right direction?
The problem is that you cannot do this:
ret[$(this).attr("id")] = _recursiveItems(this);
because var ret = [] declares ret as an Array and not an Object and $(this).attr("id") is non-numeric (its value is head_1). It is attempting to create an associative array which is not supported.. JavaScript associative arrays are are meant to be numeric and even considered harmful.
If you change the declaration to var ret = {} then you can use jquery-json to convert the object to JSON. Here is a demo using the code in the question.
Related
I've one working REST API developed using Slim PHP framework.
It's working absolutely fine.
The only issue is when there is no error present i.e. an array $errors is empty it comes as an array in JSON response but when the array $errors contains any error like $errors['user_name'] then it comes as an object in JSON response.
Actually I want to return the array when error is present. How should I do this? Can someone please help me in this regard?
Thanks in advance.
When your $errors is not empty, pass it through json_encode and echo it.
It will give you JSON object in return,
then convert JSON object into JavaScript array. (see the following code.)
var o = {"0":"1","1":"2","2":"3","3":"4"}; // your response object here
var arr = Object.keys(o).map(function(k) { return o[k] });
console.log(arr);
Recently got a close issue with Symfony's JsonResponse::create()
Turns out arrays with index not starting at 0 will be encoded into objects, as well as arrays with "holes", and probably any array with at least one non-int key.
In other word, arrays with anything else than consecutive numeric keys starting from index 0 seem to be encoded as object.
I guess this is designed to avoid sending big empty arrays when you map a handful of datas with big indices like [14334, 839493, 246193], and is probably documented somewhere.
Learning if this is a Symfony of json_encode behavior from comments would be welcomed addition :)
Note : Even if you return an array, it seems necessary to wrap it in an object for GET request to prevent some XSSI and JSON-JavaScript Hijacking.
I am receiving some JSON from PHP like this (previewed in Firefox tools):
1:Object
0:Object
1:Object
2:Object
3:Object
Name: "SomeName"
I now want to iterate through the objects, but not the Name key. It seems if I do an $.each it includes the key/value pair. How can I avoid it? Also why can I choose a numerical value for the first Object (I have it "1") but not assign a value to it? I wish it could look like this for example
1:SomeNameIGaveIt
0:Object
1:Object
2:Object
3:Object
That would make my Name k/v pair obsolete.
JSON
{"1": {"Name":"SomeName", "0":{"data":"data"}. "1":{"data":"data"}}}
In JavaScript, a String is a "subclass" of Object. Lucky for you, there's the typeof operator;
in the Chrome console
var a = "foo" //makes a String
var b = {} //makes an empty Object
typeof a
"string"
typeof b
"object"
Using this, you can check to ensure something is not a string before doing an operation on it.
Other option: instead of iterating using the json $.each call, you could just iterate over it via a JavaScript for-loop. If you know the number of elements inside your SomeNameIGaveIt object is fixed, you could use a fixed number of iterations and then use the array indexing operator (SomeNameIGaveIt[index]), or use a for-in loop (for (var i in array){...})
If you use a for-in loop, you can check if the index is a number using typeof as mentioned above. Any of these approaches is going to yield pretty similar results, so pick whatever suits you best.
I have a multidiminsional array that I have created in php that is passed back to a jQuery script. I need to iterate through this array and process the data.
In Firebug I can see that the data is located at data.data.items. I've tried finding the length of the array using data.data.items.length, but it comes back as undefined. Interestingly, this worked prior to my php portion working correctly when it passed back an array of 8 empty items. Now that it's populated (and the indexes are strings), length doesn't work. There is also an object in each of the items. What's breaking this?
An Array in JavaScript is an object nonetheless. When setting values using strings (or anything that isn't an integer), you are actually setting a property of the object (you are actually doing this when setting it with integer keys as well, but it's handled slightly differently).
To the issue of its sudden breakage after using strings as keys, I would expect that PHP realizes when you have an honest-to-goodness array versus an associative array, thus it sends arrays (surrounded by []) when all keys are integers, and objects (surrounded by {}) otherwise. I believe in the string-keyed case, PHP is generating objects, and thus .length becomes undefined (rather than 0 as in an empty array).
To answer your question, there is a simple way to count the "length" of this data:
var i = 0;
for (var item in data.data.items) {
i++;
}
Which will iterate through each property of data.data.items and count them. Note that if you (or any library you include) adds a property to the Object prototype, this will not produce expected results. This is fairly uncommon, but you must be aware of it when using for..in.
You can address this by using the method Nagh suggested, which ignores properties not defined on that particular object:
var i = 0;
for (var item in data.data.items) {
if(data.data.items.hasOwnProperty(item)) {
i++;
}
}
You can always use "foreach" kind of loop. In this case, you don't need to know what array length is there or even is it array or not, since you can iterate over object properties aswell.
As Joe already has pointed, javascript doesn't have associative arrays and when you trying to use one - you end up with object with properties. However, if u sure, that only properties this object got - is your array you can use code like that:
for (i in arr) {
if (arr.hasOwnProperty(i)) {
//do something with arr[i]
}
}
However if you really need an array, consider using integer as an array index.
i want to send a javascript array to php using jquery ajax.
$.post("controllers/ajaxcalls/users.php",
{
links: links
});
where the second 'links' is a javascript array.
when i've got this array:
'1' ...
'1' => "comment1"
'2' => "link1"
'3' => "link2"
'4' => "link3"
'2' ...
'1' => "comment2"
'2' => "link4"
then using:
var jsonLinks = JSON.stringify(links);
alert(jsonLinks);
will give me:
[null,[null,"comment1","link1","link2","link3"],[null,"comment2","link4"]]
seems to me that something is wrong. what are the null:s and i cant use json_decode on php side to get the elements.
what function should i use to convert it to json and how do i access it on the php side?
tried this http://code.google.com/p/jquery-json/ but it will give exactly the same output as JSON.stringify() (they also say that in the documentation).
have struggled with this in some hours now...would appreciate some SPECIFIC help.
i just want to send an array from javascript to php...why is that so damn difficult:/
Answering the null part, JavaScript arrays are numeric and zero based:
>>> var foo = [];
>>> foo[5] = 'Five';
"Five"
>>> foo
[undefined, undefined, undefined, undefined, undefined, "Five"]
On the contrary, PHP allows missing (and mixed) keys:
<?php
$foo = array();
$foo[5] = 'Five';
print_r($foo);
?>
Array
(
[5] => Five
)
If you want to use arrays, I suggest you make them zero-based and prevent missing values. Otherwise, you could probably use objects instead.
There are some jQuery plugin that can encode to JSON (and decode from JSON).
For instance, you can take a look at jquery-json (quoting) :
This plugin exposes four new functions
onto the $, or jQuery object:
toJSON: Serializes a javascript object, number, string, or arry into
JSON.
evalJSON: Converts from JSON to Javascript, quickly, and is trivial.
secureEvalJSON: Converts from JSON to Javascript, but does so while
checking to see if the source is
actually JSON, and not with other
Javascript statements thrown in.
quoteString: Places quotes around a string, and inteligently escapes any
quote, backslash, or control
characters.
I'm not sure how you are trying to read this in your PHP script, but if it is related to you having 1-based arrays rather than 0-based arrays, then in javascript, you can remove the nulls (zeroth element) with:
var jsonLinks = JSON.stringify(links.slice(1));
Im running a javascript code which reads values from different XML files and it generates a multidimentional array based on those values. Now I need to pass this array to a PHP page. I tried different but it always pass the arrray as string not as an array.
Anyone has an idea :( ... and thank you very much
What Caleb said.
Use this and JSON encode your JS array to a string, send it over to PHP and use json_decode to decode it into a PHP array.
You need a JSON encoder/decoder to do that. Prototype has it implemented by default and with jQuery you can use jQuery-JSON
For example if you use Prototype as your JS library then you can convert your array into a string like that:
var example_multi_dim_arr = {"a":[1,2,3], "b": [4,5,6]};
var string_to_be_sent_to_server = Object.toJSON(example_multi_dim_arr);
And in the PHP side (assuming that the JSON string is passed to the script as a POST variable)
$multi_dim_arr = json_decode($_POST["variable_with_json"], true);
The last true field in json_decode indicates that the output should be in the form of an array ($multi_dim_arr["a"]) and not as an object ($multi_dim_arr->a).
NB! the function json_decode is not natively available in PHP 4, you should find a corresponding JSON class if you are using older versions of PHP. In PHP 5 everything should work fine.