Possible Duplicate:
send arrays of data from php to javascript
I know there are many questions like this but I find that none of them are that clear.
I have an Ajax request like so:
$.ajax({
type: "POST",
url: "parse_array.php",
data: "array=" + array,
dataType: "json",
success: function(data) {
alert(data.reply);
}
});
How would I send a JavaScript array to a php file and what would be the php that parses it into a php array look like?
I am using JSON.
asked Mar 10, 2011 at 4:39
FraserK
2921 gold badge3 silver badges18 bronze badges
3 Answers 3
Step 1
$.ajax({
type: "POST",
url: "parse_array.php",
data:{ array : JSON.stringify(array) },
dataType: "json",
success: function(data) {
alert(data.reply);
}
});
Step 2
You php file looks like this:
<?php
$array = json_decode($_POST['array']);
print_r($array); //for debugging purposes only
$response = array();
if(isset($array[$blah]))
$response['reply']="Success";
else
$response['reply']="Failure";
echo json_encode($response);
Step 3
The success function
success: function(data) {
console.log(data.reply);
alert(data.reply);
}
answered Mar 10, 2011 at 4:43
Jason
15.4k15 gold badges71 silver badges106 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
FraserK
Thanks alot for prompt answer :)
cHao
You'd want to URL-encode the result from
JSON.stringify, i'd think, so a stray & in one of your object's strings wouldn't cut your string off prematurely and break your JSON.Jason
@cHao Agreed, I've changed it slightly to use the object notation, which will force jQuery to handle the URLencoding so that you can ignore
You can just pass a javascript object.
JS:
var array = [1,2,3];
$.ajax({
type: "POST",
url: "parse_array.php",
data: {"myarray": array, 'anotherarray': array2},
dataType: "json",
success: function(data) {
alert(data.reply); // displays '1' with PHP from below
}
});
On the php side you need to print JSON code:
PHP:
$array = $_POST['myarray'];
print '{"reply": 1}';
answered Mar 10, 2011 at 4:48
coldfix
7,2523 gold badges42 silver badges53 bronze badges
Comments
HI,
use json_encode() on parse_array.php
and retrive data with json_decode()
answered Mar 10, 2011 at 4:41
xkeshav
54.2k47 gold badges183 silver badges256 bronze badges
default