Question

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"
 } );
Was it helpful?

Solution

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),
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top