jQuery AJAX / POST does not send data to PHP

advertisements

So I have this problem for a while now, and I know there are countless questions on this topic, believe me I tried every solution possible but still does not work.

This is the simplest of examples which in my case is not working

jQuery:

$.ajax({
    url: "ajax/add-user.php",
    type: "POST",
    data: {name: 'John'},
    success: function(data){
        console.log(data);
    }
});

PHP

echo json_encode($_POST);

That's it. I always get back an empty array as a response. I tried with serialize() for the data: but the response is always empty. I get no errors whatsoever, just an empty array when I should get the posted values.

If, for example, in php I try to echo some hard-coded variables I get them, but the $_POST and $_GET don't work.

Any solution or methods of how I can identify the problem ?

Thank you.

EDIT/SOLUTION

Ok, so it seems the problem was with .htaccess which rewrites the url and removes the extension. In the network tab indeed the request was moved permanently. Removing the .php extension from the ajax url: solved it. Thank you and sorry for wasting time. Cheers


you need to set the data type as json in ajax call

JQUERY CODE:

$.ajax({
  url: "ajax/add-user.php",
  type: "POST",
  dataType:'json',
  data: {name: 'John'},
  success: function(data){
      console.log(data);
  }
});

at the same time verify at your script whether header is updated to accept json data.

PHP CODE:

/** * Send as JSON */ header("Content-Type: application/json", true);

Happy Coding :