0

I have an AJAX call that is not sending information over to the server from the data parameter. I confirmed it's being recognized as a POST request with my PHP code below. You will notice my var_dump($_POST) does not contain the 'myData' data. I'm not sure where to go from here.

JavaScript

$.ajax({
    method : 'POST',
    contentType: 'application/json; charset=utf-8',
    url : myURL,    
    data : {
        'myData' : 'myData'
    },  
    async : true,
    success: function (results) {
    console.log('here are the results: ' + results);
},
error: function (req, msg, obj) {
  console.log('An error occured while executing a request');
  console.log('Error: ' + msg);
}
});

PHP

if ($_SERVER["REQUEST_METHOD"] == "POST") { 
echo var_dump($_POST);
}

Console.log

here are the results: array(1) { ["phpURI"]=> unicode(33) "php/main.php?
function=myFunction" } 

Thanks!

Caconde
  • 4,177
  • 7
  • 35
  • 32
  • 3
    `$_POST` is auto-filled only if the content-type request header indicates a "multipart/form-data" or "application/x-www-form-urlencoded" request. For any other content-type you need to parse the raw input data yourself. – rickdenhaan Feb 27 '18 at 21:32

1 Answers1

-1

Your AJAX request is posting JSON data due to the Content-Type: application/json; charset=utf-8 header.

If you just delete that line, $.ajax defaults to application/x-www-form-urlencoded; charset=UTF-8, which should cause PHP to put it into $_POST as key-value pairs.

amphetamachine
  • 27,620
  • 12
  • 60
  • 72