pass multidimentional array from javascript to php - php

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.

Related

how to convert a text into an associative array?

Hi this is the code i am following in my project.
$reports = $this->curl->simple_get('url');
echo is_array($reports)?"Is Array":"Not Array";exit;
It's giving Not Array as output.
I want to convert that into associative array.
The data you are getting is probably not an array, but a string containing an array structure, e.g. output by print_r(). This kind of data will not automatically be converted back into a PHP array.
To use this you can use a similar solution as brought out here:
Create variable from print_r output
it describes the print_r_reverse function that's brought out in php.net page.
how ever - this is kind of an ugly hack. I would suggest to change the page content and use json_encode() in the "url" page, and parse the content using json_decode()

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.

How to return multiple items with AJAX and PHP

Is it possible to return multiple items via AJAX and PHP? I am reading up on it and it seems just like an echo in PHP and responseText via Javascript. Can I return an array of items via PHP and convert it into Javascript or HTML?
It depends on the data format your PHP response is sending - it sounds like the examples you're seeing are just plain text. The best format in my opinion is JSON which can send an array of multiple results, and even a multi-dimensional array many levels deep.
See json_encode() in PHP and JSON examples on jquery.com.
You can use the JSON format to return multiple values in AJAX: http://www.php.net/manual/en/function.json-encode.php
You can then decode it in javascript. This function allows you to do it in jQuery: http://api.jquery.com/jQuery.getJSON/

reading json encoded php array using ajax request

I have a php array with key, value pairs. I have json encoded it. And using ajax.Request i called the php file in which that array is there. Now i have to access both key and value pairs. Could anyone let me know how to do that?
You need to parse the JSON.
You can use the JSON library.
You can use a library method like jQuery's $.parseJSON().
If the JSON is trusted, you can use eval().
Code in javascript "json.js" is required. you can download this.
var votedCommentString = getCookie("votedComment"); // get value of voted comment cookie
votedComment = JSON.parse(votedCommentString); // extract json object into array
votedComment[votedComment.length] = id; // add more data in array
var cookieData = JSON.stringify(votedComment); // convert array into json object
setCookie("votedComment", cookieData, 365); // and again set cookie
In PHP you can access this in following way
$cookieData = (array)json_decode($_COOKIE["votedComment"]); // extract json object into array
print_r($cookieData);
Use
json_encode($array_variable) // to convert array in to json
As you said the array is in php file which is called via ajax, you can simply decode the json encoded string and retrieve the array with keys and values respectively.
Simply use json_decode() function to retrieve the array.

Best way to pass JSON from Browser to PHP using Ajax.Request

Hi I have a JSON object that is a 2-dimentional array and I need to pass it to PHP using Ajax.Request (only way I know how). ...Right now I manually serialized my array using a js function...and get the data in this format: s[]=1&d[]=3&[]=4 etc. ....
my question is: Is there a way to pass the JSON object more directly/efficientely?..instead of serializing it myself?
Thanks for any suggestions,
Andrew
You can also use Prototype's function toJSON() to convert an array into a JSON object. After passing it to server via Ajax call, simply use PHP's function json_decode() to decode the object.
Pass the object as a JSON-string to PHP, and in PHP use the builtin json_decode to get a PHP-object from the string.
In Javascript, use a "stringify" function on your object to get it as a string, library available for example here: https://github.com/douglascrockford/JSON-js/blob/master/json2.js
In que Javascript side (with Prototye):
var myJSON= Object.toJSON(youArray);
In que Php side:
$myjson = $_POST['myjson'];
$arrayJSON= json_decode(stripslashes($myjson), true);
Check
http://www.openjs.com/scripts/data/ued_url_encoded_data/
to encode nested data directly correct, since Object.toQueryString() doesn't accept nested data...

Categories