Sunil Jadhav
Sunil Jadhav

Reputation: 81

JSON.stringify is not serialiizing the object

i am trying to do ajax call by passing serialized json object and assigning it to data property of the ajax call. but some thing is not proper at assigning serialized object to data property control goes to jquery-2.0.3.min.js file

<script type="text/javascript">
    function AddEmployee() 
    {


        var Product = new Object();
        Product.Name = "kRISH";
        Product.Price = "23";
        Product.Category = "AS";

        $.ajax
        ({
            url: 'http://localhost:62310/api/products',
            type: 'POST',
            data: JSON.stringify(Product),
            contentType: "application/json;charset=utf-8",
            success: function (data){ WriteResponse(data);},
            error: function (x, y, z){ alert(x + '\n' + y + '\n' + z);}
        });
    }
</script>

Upvotes: 1

Views: 196

Answers (3)

Harsha Venkataramu
Harsha Venkataramu

Reputation: 2904

Just do

var json_text = JSON.stringify(Product, null, 2);

 $.ajax
        ({
            url: 'http://localhost:62310/api/products',
            type: 'POST',
            data: json_text ,
            contentType: "application/json;charset=utf-8",
            success: function (data){ WriteResponse(data);},
            error: function (x, y, z){ alert(x + '\n' + y + '\n' + z);}
        });

Upvotes: 0

Florian F.
Florian F.

Reputation: 4700

Product : Product is not an object.

You should replace it with an actual object :

$.ajax
    ({
        url: 'http://localhost:62310/api/products',
        type: 'POST',
        data: JSON.stringify({Product : Product}),
        contentType: "application/json;charset=utf-8",
        success: function (data){ WriteResponse(data);},
        error: function (x, y, z){ alert(x + '\n' + y + '\n' + z);}
    });

http://jsfiddle.net/floo51/x52GX/

Upvotes: 1

Sirko
Sirko

Reputation: 74036

Either you want to serialize an object with a property Product, then you need

data: JSON.stringify( {Product : Product} )

or you just want to serialize your Product, then you need

data: JSON.stringify(Product)

btw your object initialization could be rewritten as:

var Product = {
  Name : "kRISH",
  Price : "23",
  Category : "AS"
};

Upvotes: 1

Related Questions