0

I have a super simple JS code that POSTs to my local server. Both JS and PHP are on localhost so I'm not worrying about cross site issues at the moment. Here's my JS:

var ENDPOINT_BASE = '';
var ENDPOINT_USER_LOGIN    = { url: '/user/login',    method: 'POST'};
var ENDPOINT_USER_REGISTER = { url: '/user/register', method: 'POST'};

var toSend = {'credentials': { 'email':'1', 'password':'123'}};

$.ajax({
    method: ENDPOINT_USER_LOGIN.method,
    url: ENDPOINT_BASE + ENDPOINT_USER_LOGIN.url,
    contentType: "application/json",
    data: toSend
});

My PHP is simply:

<?php
print_r($_POST);

In the Chrome debugger I can see the network call be made, however the Response received in $_POST is always empty, ie it prints out Array().

If I add something like echo "abc"; in the PHP I can see it in the response, so it is hitting that URL correctly.

I'm using jQuery 2.1.4.

The JS console isn't printing out any error messages.

Any ideas what could be wrong? Thanks!

Sandy
  • 2,572
  • 7
  • 40
  • 61
  • does `print_r(file_get_contents('php://input'));` show anything? What happens if you comment out the `contentType` – Ronnie Jul 20 '15 at 23:21
  • Actually, both solutions fixed the problem of not receiving anything separately. I had no idea `php://input` existed. – Sandy Jul 20 '15 at 23:25
  • @Dagon yes, I'm explicitly setting the method to `POST`. – Sandy Jul 20 '15 at 23:26
  • yup failed to see that, sorry. i would remove the variables and hard code POST\url etc, and check that, always good for debugging –  Jul 20 '15 at 23:28
  • So just using `print_r($_POST);` works if I remove the `contentType` param, and using `print_r(file_get_contents('php://input'));` works with `contentType`. @Ronnie if you make an answer I'll accept it. – Sandy Jul 20 '15 at 23:29

1 Answers1

0

PHP is not populating $_POST as you expect because you are setting the header to JSON. I believe its default is url-form-encoded.

Either don't define the content type or if you wish to send actual JSON you could achieve that by doing something like:

$postdata    = file_get_contents('php://input');
$request     = json_decode($postdata);
$credentials = $request->credentials;
Ronnie
  • 11,138
  • 21
  • 78
  • 140
  • 1
    This is also useful regarding the use of `php://input` : http://stackoverflow.com/questions/8893574/php-php-input-vs-post – Sandy Jul 20 '15 at 23:51