When using phonegap serve
to test out my Angular based app, GET requests work just fine, but POST requests are failing.
I'm using WordPress as my backend, and all of my AJAX requests are directed to wp-admin/admin-ajax.php, and then I use action hooks to run the appropriate function for each request. GET requests work just fine this way and will return expected results. POST requests, however, are returning 0 no matter what I do. If I use Weinre to inspect the app, the request is sent successfully and gets a 200 response from WordPress, but the response body simply contains "0" instead of my specified response.
In Weinre, my request appears to be sending correctly with all required variables, but it's still not working. Here is a screenshot of the request in Weinre:
The only thought that I had is that the request payload object seems to have quotes around the keys, and I'm not sure if this is throwing WP off. Has anybody experienced this or know why I might be experiencing this?
Found the answer to my question. Turns out that the way Angular handles POST data prevents users from using $_POST
to access data and instead requires users to use file_get_contents("php://input");
In order to get WP ajax to work, data had to be accessible using the $_POST
super global. In order to make Angular work correctly, I included jQuery in my app and ran the postData object that I was sending through jQuery's $.param()
method. This "stringified" my data before passing it to the server, enabling WordPress ajax to work correctly. More info on this here:
http://angulartricks.com/how-to-do-http-post-with-angularjs-in-php/