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));
Related
can anyone explain the purpose of json_encode when doing a .post query.
This is what i often see in other's coding.
.post php script
...
...
echo json_encode($a);
I mean if i want to do a return from a .post script and returning an array via .post. Wouldn't i just need to do the following?
.post php script
...
...
$a = array("foo", "bar", "hallo", "world");
$string=implode(',',$a) in my php script
return $string;
javascript
$.post('$url',function(data){
data_arr=data.split(',');
//After which just get the values in the array
alert(data_arr[0]); //ALERTS 'foo'
alert(data_arr[1]); //ALERTS 'bar'
});
If anyone can just help by clearing this up for me and let me see the light for using json in this purpose, that would be great.
Perhaps its also due to my inept knowledge of JSON as well.
Would greatly appreciate it if anyone can advise me on why is it better to use JSON encode in this case and how am i suppose to use it via a .post request instead of just echoing out the string and split it later.
Thanks.
Using json_encode ensures that your data is always valid.
It doesn't really matter for simple data that you have control over, though imagine if someday you have a comma inside one of the values. With JSON encoded strings, you don't have to worry about an arbitrary separator token.
Also, with JSON you can easily encode Objects/Arrays without needing to reinvent the wheel.
First of all, in my opinion and practise, JSON syntax is fairly similar to Javascript objects and it's great when dealing with more complex data types that have to be sent/requested and parsed later on.
For example:
If you're doing a post request and you're serializing all the form fields which you validate server side (using PHP) you're most likely going to need to use key => value pairs like textbox_name => value. It's more logical to do it that way, than to select values by numeric indexes (what if the form layout changes?)
Example code using commas:
<?php
$array = array('Tom', 'Hanks', 'Football');
$string = join(',',$array);
echo $string; //it's obvious - the output is Tom,Hanks,Football
?>
The javascript that receives the string
$.post(url,{},function(data){
var values = data.split(',')
$("#name").text(values[0]);
$("#surname").text(values[1]);
$("#interests").text(values[2]);
});
So it makes sense right? But wouldn't it more sense to do this instead:
<?php
header('Content-type: application/json');
$array = array('name' => 'Tom', 'surname' => 'Hanks', 'interests' => 'Football');
echo json_encode($array);
?>
And the javascript:
$.post(url,{},function(data){
for(index in data) {
$("#"+index).text(data[index]);
}
//or
$("#name").text(data.name);
$("#surname").text(data.surname);
$("#interests").text(data.interests);
});
The same goes with parsing response data with Javascript. Having an object is more logical than having a CSV string.
Obviously it depends on the use case, but in general JSON gives you a logical structure of stringified Objects/Arrays which can be translated back into objects and arrays and looped through or manipulated in any way.
Also JSON is now a standard. Everyone uses it which means that it's not for no reason.
In other words - JSON data makes more sense.
Here's my server side PHP script:
echo json_encode(
array(
"1" => "foo",
"2" => "bar"
)
);
The indexes are strings.
I'm fetching this array through $.ajax() with jQuery, and using Chrome's developer tools I can see that it's interpreting the indexes as numeric values and not strings.
How can I preserve that string type when passing the JSON from the server to the client? Or is the concept of type completely lost when transferring JSON data from a server to a client?
Strings can be numeric and strings, and even booleans, thanks to type coercion and duck typing (if it looks, walks, and quacks like a duck, it is a duck), since both are loosely typed languages. You should be just fine handling it like a string.
In the case of Chrome developer tools, you have a string that consists only of numeric characters. Therefore, it's also a numeric data type (it "looks like a duck").
Perhaps if you explain what, exactly, it is you're doing that isn't working, we could help you with a better way.
This is because in PHP, what javaScript calls an object is an array in php. In JavaScript, array indexes cannot be strings, they must be positive integers.
If you want JavaScript to interpret that as an array, give it a 0 index and make the indexes integers rather than strings.
Your code already does what you want it to do. The keys are strings.
http://jsfiddle.net/XC85h/
var jsonStr = '{"1":"foo","2":"bar"}';
var obj = JSON.parse(jsonStr);
for (key in obj) {
console.log(typeof key, key); // string 1, string 2
}
Edit (per comments)
Never rely on the sort order of a JavaScript object, it may vary between browsers.
I have stored a 2d array in a MySql db
[["c0"]["33925"],["c1"]["39280"],["c2"]["34079"],["c3"]["34091"],["c4"]["34108"]]
I want to convert this into a javascript array.
I am using a php page to get the array using xmlhttp.responseText;
which gets the array, but I can't do anything with it;
var layoutArray = new Array();
layoutArray = xmlhttp.responseText;
alert(layoutArray[0][0]);
Try to eval the array because you are getting a string back:
layoutArray = eval(xmlhttp.responseText);
In general you should avoid the use of eval especially if the data you are running eval on is coming from your users. However if only you can tamper with this value, then eval is safe.
i would store the array as a JSON string like feeela said.
var layoutArray = {"c0":"33925","c1":"39280","c2":"34079","c3":"34091","c4":"34108"}
for (key in layoutArray){
console.log(layoutArray[key])
}
just use serialize before putting it into the database and unserialize when extracting it. You'll have your json structure without using eval on the clientside.
If you are sending back the result using a PHP script, and "must" store the data as an array instead of JSON to begin with, I would just json_encode the array and return that:
Working example
$array = array("1" => "PHP code tester Sandbox Online",
"foo" => "bar", 5 , 5 => 89009,
"case" => "Random Stuff");
echo json_encode($array)
i have an simple array:
array
0 => string 'Kum' (length=3)
1 => string 'Kumpel' (length=6)
when I encode the array using json_encode(), i get following:
["Kum","Kumpel"]
My question is, what is the reason to get ["Kum","Kumpel"] instead of { "0" : "Kum", "1" : "Kumpel" }?
"{}" brackets specify an object and "[]" are used for arrays according to JSON specification. Arrays don't have enumeration, if you look at it from memory allocation perspective. It's just data followed by more data, objects from other hand have properties with names and the data is assigned to the properties, therefore to encode such object you must also pass the correct property names. But for array you don't need to specify the indexes, because they always will be 0..n, where n is the length of the array - 1, the only thing that matters is the order of data.
$array = array("a","b","c");
json_encode($array); // ["a","b","c"]
json_encode($array, JSON_FORCE_OBJECT); // {"0":"a", "1":"b","2":"c"}
The reason why JSON_FORCE_OBJECT foces it to use "0,1,2" is because to assign data to obeject you must assign it to a property, since no property names are given by developer (only the data) the encoder uses array indexes as property names, because those are the only names which would make sense.
Note: according to PHP manual the options parameters are only available from PHP 5.3.
For older PHP versions refer to chelmertz's answer for a way to make json_encode to use indexes.
As Gumbo said, on the JS-side it won't matter. To force PHP into it, try this:
$a = new stdClass();
$a->{0} = "Kum";
$a->{1} = "Kumpel";
echo json_encode($a);
Not that usable, I'd stick with the array notation.
Just cast as an object and it will work fine...the JSON_FORCE_OBJECT parameter does exactly the same thing.
json_encode((object)$array);
Don't forget to convert it back into a php array so you can access its values in php:
$array = (object)$array;
$array = (array)$array;
json_encode($array);
Since you’re having a PHP array with just numeric keys, there is no need to use a JavaScript object. But if you need one, try Maiku Mori’s suggestion.
I personally think this is a bug that needs to be fixed in PHP. JSON_FORCE_OBJECT is absolutely not an answer. If you try to do any sort of generic programming you get tripped up constantly. For example, the following is valid PHP:
array("0" => array(0,1,2,3), "1" => array(4,5,6,7));
And should be converted to
{"0": [0,1,2,3], "1": [4,5,6,7]}
Yet PHP expects me to either accept
[[0,1,2,3],[4,5,6,7]]
or
{"0":{"0":1,"1":1,"2":2,"3":3},"1":{"0":4,"1":5,"2":6,"3":7}}
Neither of which are right at all. How can I possibly decode an object like that? What possible reason is there to ever change something that is clearly using strings as indexes? It's like PHP was trying to be clever to help out idiotic people who can't differentiate strings from ints, but in the process messed up anyone legitimately using strings as indexes, regardless of what the value COULD be turned into.
I'm looking at this function: serialize() for PHP and I don't really understand what is it's function. Can someone provide a simple example with output?
Basically, the goal of serialize is to transform any (alsmost) kind of data to a string, so it can be transmitted, stored, ...
A quick example :
$my_array = array(
'a' => 10,
'glop' => array('test', 'blah'),
);
$serialized = serialize($my_array);
echo $serialized;
Will get you this output :
a:2:{s:1:"a";i:10;s:4:"glop";a:2:{i:0;s:4:"test";i:1;s:4:"blah";}}
And, later, you can unserialize that string, to get the original data back :
$serialized = 'a:2:{s:1:"a";i:10;s:4:"glop";a:2:{i:0;s:4:"test";i:1;s:4:"blah";}}';
$data = unserialize($serialized);
var_dump($data);
Will get you :
array
'a' => int 10
'glop' =>
array
0 => string 'test' (length=4)
1 => string 'blah' (length=4)
Common uses include :
Ability to transmit (almost) any kind of PHP data from one PHP script to another
Ability to store (almost) any kind of PHP data in a single database field -- even if it's not quite a good practice on the database-side, it can sometimes be usefull
Ability to store data in some caching mecanism (APC, memcached, files, ...), in which you can only store strings
Note, though, that using serialize is great when you are only working with PHP (as it's a PHP-specific format, that's able to work with almost any kind of PHP data, and is really fast) ; but it's not that great when you have to also work with something else than PHP (as it's PHP-specific). In those cases, you can use XML, JSON (see json_encode and json_decode), ...
In the PHP manual, you can also read the Object Serialization section, btw.
If you want to save an array or object normalised in a database row for example, serialize() (and unserialize()) are your friends, because you can't store an array or object flattened without first turning it into a string.
json_encode() and json_decode() are similar except they encode as JSON.
See this example, should be pretty clear.