user1167253
user1167253

Reputation: 833

Can not send a POST-JSON-Request with JavaScript

i try to send a POST-JSON-Request with jQuery 1.9.

I always get the following error in Console.

TypeError: this.products is undefined. this.products.push(oneProduct);

here is my code

<script src="http://code.jquery.com/jquery-latest.js"></script>
<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: p
        });

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

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

and 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 = [];

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

What am I doing wrong?

Upvotes: 1

Views: 1015

Answers (1)

Kenneth
Kenneth

Reputation: 28737

You should alter your product.js The problem is that you're losing the reference to this.

This should do the trick:

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;
    };
  }

EDIT: When you call the method addOneProduct, the this-reference is correctly resolved. The problem is when actually try to call the service and set p as the data. Upon serializing the object, JS actually calls into the method and at that point the reference is incorrect. What you need to do is stringify the object before assigning it to the data:

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

Upvotes: 4

Related Questions