Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery AJAX/POST not sending data to PHP

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

like image 611
C. Ovidiu Avatar asked Feb 28 '14 15:02

C. Ovidiu


2 Answers

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 :

like image 72
dreamweiver Avatar answered Sep 20 '22 17:09

dreamweiver


I recently came across this issue but because of other reasons:

  1. My POST data was redirected as 301
  2. My Server request was GET
  3. I did not get my POST data

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!

like image 43
Reshape Media Avatar answered Sep 18 '22 17:09

Reshape Media