user1167253
user1167253

Reputation: 833

PHP read JSON-POST-Request and send them back

I tried with PHP to read JSON-POST-Request, but I get the following error.

Request failed: parsererror

Here is my code

    <script type="text/javascript" charset="utf-8" src="resources/js/model/Product.js"></script>
<script>
    function getdetails(){

        var p = new Product(15,11.5,"Pizza Test","P");
        var z = new Product(68,1.5,"Zutate Test","Z");

        p.addOneProduct(z);

        var request = $.ajax({
            type: "POST",
            url: "yb_test_post.php",
            dataType: "json",
            data: JSON.stringify(p)
        });

        request.done(function(msg) {
            $("#msg").html( " Post parameter are: <br/>"+msg );
        });

        request.fail(function(jqXHR, textStatus) {
            alert( "Request failed: " + textStatus );
        });
    }
</script>

and my PHP-Code, I try to read the POST request and immediately print

    <table>
<?php


    foreach ($_POST as $key => $value) {
        echo "<tr>";
        echo "<td>";
        echo $key;
        echo "</td>";
        echo "<td>";
        echo $value;
        echo "</td>";
        echo "</tr>";
    }


?>
</table>

What do i wrong?

Product.js

function Product(id, price, name, type){
    this.id = id;
    this.price = +price;
    this.totalPrice = +price;
    this.name = name;
    this.type = type;
    this.products = [];
    var self = this;

    this.addOneProduct = function(oneProduct){
        self.products.push(oneProduct);
        self.totalPrice= self.totalPrice+oneProduct.price;
    };
}

Upvotes: 0

Views: 1251

Answers (1)

gen_Eric
gen_Eric

Reputation: 227310

You are doing data: JSON.stringify(p). This is sending a JSON string as the post body. You don't want this. PHP will not automatically parse this for you. You want to send PHP a query string, this will make PHP automagically parse it into the $_POST array.

Lose the JSON.stringify, and just try this: data: p.

Also, dataType: "json" is the Content-type of the response, not the request. Your PHP is sending back HTML, so you want: dataType: "html".

var request = $.ajax({
    type: "POST",
    url: "yb_test_post.php",
    dataType: "html",
    data: p
});

Upvotes: 1

Related Questions