jamesplease
jamesplease

Reputation: 12869

Jquery Ajax Request Not Sending Post Data

I'm successfully making an AJAX call with the Jquery $.ajax method, in that the file it's POSTing to is getting called and executing. However, no POST data is being sent. All I want to do is send the data and have it received by the file; I don't care about returning data.

I've tried changing it to GET, which didn't yield results. I passed GET data in the URL which was received (obviously, I guess). I've also tried changing the data type that I'm sending...none of this has given me any ideas as to what I'm doing wrong. I've also browsed the numerous questions here with similar titles, but nothing seemed to fix this issue. Though I'm sure it's something simple.

Other variables that may be relevant: I'm using Knockout JS. I'm using .htaccess redirects to create a single point of entry in a /public folder.

And without further ado, here's the code:

page.html

<button data-bind="click: save">Save</button>

If you're unfamiliar with KOJS, it basically just calls the function save when you click it. I'm pretty sure this is working properly.

models.js

self.save = function() {
    var jsonData = ko.toJSON(self.tasks);
    $.ajax("http://test.local.com/js/post.php", {
        data: jsonData,
        type: "post", contentType: "application/json",
        success: function(result) { alert(jsonData) }
    });
};

That alert is giving me a nicely formatted JSON object, like

[{"title": "Clean up the dog"},{"title": "Warm up the old pasta"}]

It's the post file, I think, where my error is? The $_POST array is empty. And if I change it to send as GET, that's also empty. I put comments in the code explaining things.

post.php

if (isset($_POST)) {
  //It does get inside this if. That's good at least, right?

  $my_file = 'file.txt';
  $handle = fopen($my_file, 'w') or die('Cannot open file:  '.$my_file);
  //It will make this file.

  fwrite($handle, print_r($_POST));
  //Prints "1" without the quotes


  foreach ($_POST as $key => $value) {
    fwrite($handle, 'your data: '.$value.'; ');
  }
  //Prints nothing
}

Any thoughts as to why this won't send any POST data? I'm sure it's something silly. Thanks!

Upvotes: 2

Views: 7669

Answers (1)

subhaze
subhaze

Reputation: 8855

Your issue is that you're setting data as a JSON string. Per the docs jQuery won't process string data, only objects http://api.jquery.com/jQuery.ajax/

Instead use ko.toJS to get a clean JS object and that should get you going in the right path.

[edit]

I just noticed you were setting the contentType as well... For that to work you won't be able to use the $_POST var. Instead you'll need to grab the data from file_get_contents("php://input") that "should" give you the raw JSON string. From there you should be able to use PHP's json_decode to turn it into a true PHP object.

Upvotes: 4

Related Questions