Horatiu Horatiu - 5 months ago 25
Javascript Question

Ajax POST method not working in PHP, but GET is working

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.

Answer

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); }
    });
Comments