0

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

1 Answer 1

2

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),
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.