简体   繁体   中英

Ajax POST-request doesn't come through to PHP

I'm firing an HTTP POST request with Ajax to my php file, but I don't get the desired result. $_POST and $_GET are both empty. I think I'm overlooking something, but I have no clue what.

Here's my code for firing the request:

this.save = function() {

    alert(ko.toJSON([this.name, this.description, this.pages]));
    $.ajax("x", {
        data: ko.toJSON([this.name, this.description, this.pages]),
        type: "post", contentType: "application/json",
        success: function(result) { alert(result) },
        error : function(jqXHR, textStatus, errorThrown) { alert(textStatus + errorThrown)}
    });
};

Note that I alert the JSON on line 3. That JSON is correct, so the input on line 5 is valid.

My test method in PHP:

header('Content-type: application/json; charset=utf-8');
echo json_encode(array_merge($_POST, $_GET));
exit;

The response I'm getting is an empty array.

  • I tested the input (see above);
  • I know the Ajax call itself succeeds, if I replace that second line in my PHP example with json_encode(array('success' => true)); I get that back in my page - so the URL is correct.
  • I tested it with both GET and POST, with similar negative results.

You are sending a JSON request, that's why both $_POST and $_GET are empty. Try sending the data like this:

$.ajax("x", {
    data: { data: [this.name, this.description, this.pages] },
    type: "post", 
    success: function(result) { alert(result) },
    error : function(jqXHR, textStatus, errorThrown) { alert(textStatus + errorThrown)}
});

Now look inside $_POST["data"] .

or if you need to use a JSON request then you need to deserialize it back in your PHP file:

$.ajax("x", {
    data: { data: ko.toJSON([this.name, this.description, this.pages]) },
    type: "post", 
    success: function(result) { alert(result) },
    error : function(jqXHR, textStatus, errorThrown) { alert(textStatus + errorThrown)}
});

and then decode:

$json = $_POST['json'];
$data = json_decode($json);

and if you want to send pure JSON request in the POST body:

$.ajax("x", {
    data: ko.toJSON([this.name, this.description, this.pages]),
    type: "post", 
    contentType: 'application/json',
    success: function(result) { alert(result) },
    error : function(jqXHR, textStatus, errorThrown) { alert(textStatus + errorThrown)}
});

and then:

$data = json_decode(file_get_contents("php://input"));

Notice that php://input is a read-only stream that allows you to read raw data from the request body.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM