Stored array into Javascript - php

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)

Related

How to pass an object in query string in PHP

I see many questions about passing an array as a query string in PHP, and it seems the prevailing way is using brackets as in key[]=foo&key[]=bar.
However I cannot find a straight answer about how to send an object (or a key=>value associative array - same thing) as a query string.
Currently, however I do it is:
STRING
?foo=bar&hello=world
Then on the server side, I would do:
<?php
$array = array();
$array['foo']=$_GET['foo'];
$array['hello']=$_GET['hello'];
?>
Of course when using $_POST, this is very simple with an ajax request. Any object you send automatically serializes and isn't a problem.
Is this the best way to handle it, or is there some other standard for sending an object in a query string using PHP?
You can use an associative array in a form and in the query string:
object[foo]=bar&object[hello]=world
To build it URL encoded:
$data['object']['foo'] = 'bar';
$data['object']['hello'] = 'world';
echo http_build_query($data);
Yields:
object%5Bfoo%5D=bar&object%5Bhello%5D=world
You can go many levels and/or use dynamically added elements. In general, in text form, it looks just like a PHP array
object[foo][more][even more][]
Or:
object[foo][][more][even more]

send an Array from Android to PHP Script over HTTP and get the data

I would like to send an integer array with 30 values Integer[] temp = new Integer[30] over HTTP (POST) to PHP an get the data in PHP again. How can I do that? I know how to send a single value, like a string, but not how to send an array.
One way is to serialize the array in the way the php serialize command does it.
After receiving the string value(by the method you currently use), you can use the unserialize command to get the array in your php code.
Here is a litle php example to demonstrate the workflow.
$arr = array(1,2,3,4,5,6);
$stringArr = serialize($arr);
echo $stringArr;
echo "<br/>";
$arr2 = unserialize($stringArr);
if ($arr === $arr2)
{
echo "arrays are equal";
}
The output of the script is:
a:6:{i:0;i:1;i:1;i:2;i:2;i:3;i:3;i:4;i:4;i:5;i:5;i:6;}
arrays are equal
The main difficulty is to construct the resulting string for complex structures (in your case, it is pretty straight forward for an array of integers).
This fact results in the second approach.
One can use a serialization API or another notation than used by the php example.
As stated by the others, JSON is one of the widespread notations.
PHP also provides a possibility to serialize and unserialize json objects.
Simply use json_decode and look at the example in the manual.

Json_encode for .post?

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.

PHP multidimensional array to JSON

So im trying to figure out the best way to get MySql table data into either a multidimensional PHP array or convert that multidimensional array into a json string.
Essentially what im trying to do is have a php include that returns the JSON string so i can iterate through it. I am needing a single key with multiple values, so im not 100% sure that im headed in the right direction.
I want to assign multiple values to the same key, for example:
[{"key1": "package1", "package2", "package3"}, {"key2": "package1", "package2", "package3", "package4"}]
I think that is not going to work right? Because i dont have any type of index's?
That is not valid JSON. The structure you are looking for would be something like:
[
{"key1": ["package1", "package2", "package3"]},
{"key2": ["package1", "package2", "package3", "package4"}]
^ An array as the value to the key "key1", "key2", etc..
]
At the PHP side, you would need something like:
For every row fetched from MySQL
$arr[$key] = <new array>
for each package:
append package to $arr[$key]
echo out json_encode($arr)
JS arrays have an implicit array keying, starting at index 0. What you've got is a perfectly valid JS array, the equivalent of having written:
var x = []; // create new empty array
x[0] = {"key1": .... }; // first object
x[1] = {"key2": ....} // second object
Note that the contents of your {} sub-objects is NOT valid.
You should never EVER built a JSON string by hand. It's too unreliable and easy to mess up. It's just easier to use a native data structure (php arrays/objects), then json_encode() them. Ditto on the other end of the process - don't decode the string manually. Convert to a native data structure (e.g. json_decode(), JSON.parse()) and then deal with the native structure directly.
essentially, JSON is a transmission format, not a manipulation format.

javascript array to php

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));

Categories