Reputation: 32321
I am trying to insert to MongoDB from directly from javascript as shown below .
The below works fine .
$.ajax( {
type: "POST" ,
url: "http://fff:28017/test/stocks/" ,
contentType: "application/json; charset=utf-8",
data:'{test:123}',
dataType: "json"
} );
But where as if i am trying to construct JSON Object dynamically as shown below its failing saying 400 Bad request
var json = "{ 'symbol': '" + symbol +"','lastprice:' '" + lastprice +"' }";
$.ajax( {
type: "POST" ,
url: "http://fff:28017/test/stocks/" ,
contentType: "application/json; charset=utf-8",
data:json',
dataType: "json"
} );
Upvotes: 0
Views: 26
Reputation: 27012
Don't create json strings via concatenation. Create a javascript object and pass it to JSON.stringify()
:
var data = { symbol: symbol, lastprice: lastprice };
...
data: JSON.stringify(data),
Upvotes: 2