I am having trouble sending $_POST
data via jQuery Ajax. I have read over everything I can find regarding the matter and still I am getting nowhere. I have even gone back to very basic data and still nothing, the JSON data has been validated using the JSON validate site. For the life of me I cannot echo
/print_r
/var_dump
or get access to any data.
My JavaScript:
$('#updateJSON').click(function(){
var content = [{
"id": 21,
"children": [{
"id": 196
}, {
"id": 195
}, {
"id": 49
}, {
"id": 194
}]
}];
var someText = "someText";
$.ajax({
type: 'POST',
url: 'test.php',
data: {data: content},
cache: false,
success: function(){
alert("success");
console.log(content);
window.location = "test.php";
},
error:function(){
alert('ajax failed');
}
});
});
My PHP:
<?php
if(isset($_POST['data'])) {
$json = stripslashes($_POST['data']);
var_dump(json_decode($json, true));
} else {
echo "No Data";
}
?>
So I do get the alert("success")
, and then get redirected to test.php
once at test.php
I get the echo "No Data".
Thanks in advance for any help with this issue.
The reason is you are using window.location
to redirect to the PHP file (without any post data) instead of posting the form on test.php
.
You should either post the form without ajax
on test.php
.
Or use the response from test.php
in your success
function.
$('#updateJSON').click(function(){
var content = [{
"id": 21,
"children": [{
"id": 196
}, {
"id": 195
}, {
"id": 49
}, {
"id": 194
}]
}];
var someText = "someText";
$.ajax({
type: 'POST',
url: 'test.php',
data: {data: content},
cache: false,
success: function(response){
alert("success");
console.log(response);
//window.location = "test.php";
},
error:function(){
alert('ajax failed');
}
});
You are passing data as a string to ajax file. Please use JSON.stringify(conten) to pass data as a json format in ajax file.
use
data: {data: JSON.stringify(content)}
in place of
data: {data: content}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With