Mike Oram
Mike Oram

Reputation: 765

Ajax post returning empty $_POST

Okay I think I am going mad because I have done this a million times before and now I can't make it work. I am doing an ajax post to a PHP script with some simple JSON and then returning the JSON from my PHP, however it is currently showing $_POST as an empty array.

Here is my js:

$.ajax({
  type: "POST",
  url: "/account/book-promo.php",
  data: '{"firstName":"Peter" , "lastName":"Jones"}',
  success: function(response) {
    console.log(response);
  }
});

And my PHP:

<?php
var_dump($_POST);
exit;

Firebug shows that my request is using POST as it is supposed to and my data is being sent as JSON yet I am getting a response of:

array(0) {
}

The only thing I can think is that there is some kind of server settings that are preventing this from working, however I cant think why there would be. Maybe I have missed a bracket or something, it is driving me mad!

Any and all suggestions welcome!

Upvotes: 0

Views: 266

Answers (2)

Jai
Jai

Reputation: 74738

You have to do this:

$.ajax({
  type: "POST",
  dataType: "json", // <---------------its required if response is json
  url: "/account/book-promo.php",
  data: {"firstName":"Peter" , "lastName":"Jones"}, //<---instead of string send the object this way
  success: function(response) {
    console.log(response);
  }
});

You said in your post retuning the JSON from my PHP:

so you need to use dataType:"json" and the data you are sending to your php should be sent as object (which is usually to be pair of key and values separated by : like {key:value}) as of your code you are sending a string.

Upvotes: 0

zzlalani
zzlalani

Reputation: 24354

send it like if you want to send it as json.

data: { data : '{"firstName":"Peter" , "lastName":"Jones"}' },

and if you want to send it as POST just remove quotes '

data: {"firstName":"Peter" , "lastName":"Jones"},

Upvotes: 2

Related Questions