Reputation: 61
I am trying to send using Ajax a POST request to php.
If I use GET it works fine, but with POST the data I receive in php is empty. I'm sending data as a json.
This is what the js code looks like:
$.ajax(
{
type: 'POST',
url: 'php/GiveItBack.php',
contentType: "json",
data: {
word: 'abc'
},
success: function (json) {
alert(json);
},
error: function (jqXHR, textStatus, errorThrown) { alert('ERROR: ' + errorThrown); }
});
This is the php/GiveItBack.php file
<?php
$x = $_GET['word'];
echo 'Get: ' . $x;
$x = $_POST['word'];
echo '; Post: ' . $x;
$x = $_REQUEST['word'];
echo '; Request: ' . $x . ';';
?>
With this code, the message in the alert window looks like this:
Get: ; Post: ; Request: ;
If I replace type: 'POST' in the js file with type: 'GET' this is the result I get in the alert window (as I was expecting to see):
Get: abc; Post: ; Request: abc;
I can't see what I'm missing here. Is something wrong in the code or is any special setting I need to do for this to work.
By the way I am using: jquery-2.2.4.min and php v5.6 and XAMPP v3.2.2.
Thank you.
Upvotes: 2
Views: 966
Reputation: 1
Ajax Data
Remove the contentType: json
:
$.ajax(
{
type: 'POST',
url: 'php/GiveItBack.php',
data: {
word: 'abc'
},
success: function (json) {
alert(json);
},
error: function (jqXHR, textStatus, errorThrown) { alert('ERROR: ' + errorThrown); }
});
Upvotes: 0
Reputation: 5131
Remove contentType: json
and you should be able to use the $_POST
superblogal array. If you use contentType: json
the object containing the parameters is converted into a string and sent over to the server. To get the string you will need to use
file_get_contents('php://input');
This happens because $_POST
only contains data sent along with the following headers:
When you set contentType: json
, jQuery adds the application/json
header to the request which is not supported by $_POST
so the JSON string is treated as raw input and therefore you need to use the php://input
stream to retrieve it
Upvotes: 0
Reputation: 8101
The content type was not correct, need to use contentType: "application/x-www-form-urlencoded"
OR 'Content-Type': 'application/json'
$.ajax(
{
type: 'POST',
url: 'php/GiveItBack.php',
contentType: "application/x-www-form-urlencoded",
data: {
word: 'abc'
},
success: function (json) {
alert(json);
},
error: function (jqXHR, textStatus, errorThrown) { alert('ERROR: ' + errorThrown); }
});
Upvotes: 4
Reputation: 1063
$.ajax(
{
method: 'POST',
url: 'php/GiveItBack.php',
data: {
word: 'abc'
},
success: function (json) {
alert(json);
},
error: function (jqXHR, textStatus, errorThrown) { alert('ERROR: ' + errorThrown); }
});
Upvotes: 0
Reputation: 4980
contentType: "json",
You content type is wrong here. If you want to receive it the way you are trying, you should use application/x-www-form-urlencoded
.
If you still want to stick within JSON, you will have to json_decode
your PHP input:
$json = file_get_contents('php://input');
$obj = json_decode($json, TRUE);
Upvotes: 1