Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - How to PUT JSON via Ajax?

Tags:

json

jquery

ajax

I am trying to put some JSON formatted data via Ajax with jQuery to a server. My code looks like this:

$.ajax({     type: "PUT",     url: myURL,     contentType: "application/json",     data: {"data": "mydata"} }); 

But on the server-side, I receive a data=mydata string, instead of the expected JSON. Firebug tells me the same.

Where is the error?

like image 720
Juri Glass Avatar asked Nov 17 '09 14:11

Juri Glass


People also ask

Can you use JSON with AJAX?

According to the AJAX model, web applications can send and retrieve data from a server asynchronously without interfering with the display and the behavior of the existing page. Many developers use JSON to pass AJAX updates between the client and the server.

How pass JSON data to AJAX to controller?

Create target "JSON object Mapper" object class file according to the business requirements. Create a "Controllers\HomeController. cs" file with default Index method and GetData(...) method with string type input query parameters for Ajax call with following lines of code i.e.


1 Answers

I think the data needs to be a String. Objects are converted to query strings which is what you are seeing here.

You can use the JSON.stringify(obj) method to convert your Object to a String. The code for the JSON object is available from: https://github.com/douglascrockford/JSON-js/blob/master/json2.js.

Alternately, just pass the code you are using to create the object as a literal String, but I imagine this is just an example and you'll want to encode some object you've already created.

like image 110
Andy Avatar answered Sep 23 '22 08:09

Andy