Reputation: 14154
I would like to send a data via jQuery ajax
function to the PHP script and receive a response - success or failure. The code I am using:
JavaScript:
$.ajax({
type: 'POST',
url: 'foo.php',
dataType: 'json',
data: {
foo: 'foo'
},
success: function (response) {
...
},
error: function (response) {
...
}
});
PHP:
<?php
header("Content-Type: text/json");
echo $_POST['foo']
?>
However this always return error, because of header("Content-Type: text/json");
.
What is done wrong here?
Upvotes: 0
Views: 77
Reputation: 454
This would handle the errors correctly server side.
<?php
if(isset($_POST['foo']){
header('Content-Type: application/json');
$foo = array(
"foo" => $_POST['foo'];
);
echo json_encode($foo);
} else {
header('HTTP/1.0 400 Bad Request');
}
?>
Upvotes: 1
Reputation: 143
As many in the comments have pointed out, the correct MIME type for JSON data is "application/json" – that's not your problem though. The problem is that you're not returning JSON, you're simply echoing out the contents of a variable. If the variable is only a value, it needs at least one key ({"key": "value"}) to be properly converted to a JSON object.
To convert, you echo json_encode($yourvar) after it is an object that represents valid JSON.
Upvotes: 1
Reputation: 611
if you use application/json
It should be
$.ajax({
url: '/foo.php',
method: 'post',
contentType: 'application/json',
data: JSON.stringify({ foo: 'foo' }),
success: function(data) {
}
})
or type : 'json'
$.ajax({
type: 'post'
url: '/foo.php',
data: { "foo": "foo" },
dataType: "json",
success: function(data) {
}
})
Upvotes: 1
Reputation: 34924
To get json response include key to make proper json
<?php
header("Content-Type: text/json");
$foo = isset($_POST['foo'] ) ? $_POST['foo'] : "";
echo json_encode(["foo"=>$foo ]) ;
?>
As you already define dataType as json in ajax you could remove above header.
Upvotes: 1