html
<button id="btn2">show alert array</button>
<button id="btn"> go to php</button>
javascript
var test = new Array();
test.push("one");
test.push("two");
json = JSON.stringify(test);
$('#btn').click(function(){
$.ajax({
type: "POST",
url: "json.php",
data: {data:json}
});
});
$('#btn2').click(function(){
alert(json);
});
php file (json.php)
<?php
$data = json_decode($_POST['data']);
var_dump($data);
?>
id="btn2" is working. It displays an alert with the array on it, but when I click in the id="btn", it is not working at all. Can you tell me the problem of these codes?? I just want to send an array from javascript to php file.
how come you say it is not working at all, check your ajax function, you should have a success handler in it,
$('#btn').click(function(){
$.ajax({
type: "GET",
url: "json.php",
data: {data:json},
success:function(data){
alert(data);
}
});
});
otherwise how are you supposed to know whether the ajax happened ?
You do a GET request on the client side:
type: "GET",
But you are expecting POST data on the server side:
$_POST['data']
(This answer is not true anymore because the OP edited the question.)
This is not the correct way to send an array from JavaScript to PHP. There is no need for JSON here. You can just send the array in your AJAX call. It will be serialized correctly:
$('#btn').click(function(){
$.ajax({
type: "POST", // Make sure to read from the right array in PHP
url: "json.php",
data: {data: test} // test is your array, no JSON.stringify needed
});
});
You are reading $_POST['data']
in PHP, so you need to send the data as POST
This has the added benefit that in PHP your $_POST['data']
will be an array! No json_decode
needed.