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 your backend code(php), whether it can accept json
data ?
If not, configure the header as below:
PHP CODE:
/** * Send as JSON */ header("Content-Type: application/json", true);
Happy Coding :
I recently came across this issue but because of other reasons:
My reason - I had a url on the server registered as:
http://mywebsite.com/folder/path/to/service/
But my client was calling:
http://mywebsite.com/folder/path/to/service
The .htaccess on the server read this as a 301 GET redirect to the correct URL and deleted the POST data. The simple solution was to double check the url path.
@C.Ovidiu, @MarcB - Both of you guys saved me lots of hours in debugging!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With