Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Posting JSON with JQuery

Tags:

json

jquery

Trying to get JQuery to post JSON to a server:

$.ajax({  
  url: "/path/to/url",  
  type: "POST",  
  dataType: "json",  
  contentType: "json",  
  data: {"foo": "bar"},  
  success: function(){              
    alert("success :-)");  
  },  
  error: function(){  
    alert("fail :-(");  
  }  
});  

Problem is the data appears on the server as "foo=bar" rather than the desired "{\"foo\":\"bar\"}.

I thought specifying either the dataType or contentType params would do the trick, but no.

Anyone know the correct ajax configuration ? [or alternatively a way of serialising the 'data' parameter as JSON prior to posting ?]

Thanks!

like image 289
Justin Avatar asked Dec 21 '22 22:12

Justin


1 Answers

You could use json2.js:

data: JSON.stringify({"foo": "bar"})
like image 68
Darin Dimitrov Avatar answered Jan 05 '23 02:01

Darin Dimitrov