vamsiampolu vamsiampolu - 3 months ago 14
Ajax Question

jQuery not sending JSON on AJAX POST request

I am a little confused here,I am trying to post data to my node js server using the following code:

$.ajax({type:'POST',
url:'/map',
data:'type=line&geometry='+str,
success:function(msg)
{
console.log(msg);
},
datatype:'json'
});


This is the result here:

{ type: 'line', geometry: 'b~cqCge{b[mv|q@xnyC' }


This is not JSON.I had previously tried to use
contentType
and do this like this:

$.ajax({type:'POST',
url:'/map',
data:{type:'line',geometry:str},
success:function(msg)
{
console.log(msg);
},
datatype:'json',
contentType:"application/json"
});


Even this sent the data without any change.I have also tried the above method using the data string from the first one.I have also tried setting
processData
to
false
along with the methods in the code blocks.

It is important to me that the data be in
JSON
and use
AJAX
because I am trying to insert into mongodb from node js using mongojs and it fails

Answer

Actually dataType has nothing to do with the input but rather the output.

Instead what you want is to stringify your input data and then send that down as a single variable to your backend which can then decode it:

$.ajax({type:'POST',
    url:'/map',
    data: {data: JSON.stringify({type: 'line', geometry: str})},
    success:function(msg)
    {
       console.log(msg);
    },
    dataType:'json'     
});

That way in your backend you just decode data and it should be now a fully functioning object from JSON.

Note you will need the JSON class for this, JQuery does not include this ability by default: https://github.com/douglascrockford/JSON-js

Comments