Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I send JSON data to server

Well, here is the story:

I have some data need to send to server, but they should turned into JSON dataType first.

I made such ajax call:

    $.ajax({
       url: url, // the url I want to post to.
       type: 'POST',
       contenttype:'application/json; charset=utf-8',
       beforeSend: //some HTTP basic auth stuff
       data: {
          name:'test',
          key:'foo',
          key2:'bar'
       },
       dataType:'JSON'
});

basically I'm expecting the data I send to server was:

[name:test,key:foo,key2:bar]

but what I've got was:

name=test&key=foo&key2=bar

What did I missing? How can I get those data into JSON?

like image 275
Daniel Chen Avatar asked Dec 03 '10 06:12

Daniel Chen


People also ask

How does REST API send JSON data?

To post JSON to a REST API endpoint, you must send an HTTP POST request to the REST API server and provide JSON data in the body of the POST message. You also need to specify the data type in the body of the POST message using the Content-Type: application/json request header.

Can we send JSON data in GET request?

To answer your question, yes you may pass JSON in the URI as part of a GET request (provided you URL-encode).


1 Answers

 var data = {'bob':'foo','paul':'dog'};
 $.ajax({
   url: url,
   type: 'POST',
   contentType:'application/json',
   data: JSON.stringify(data),
   dataType:'json'
 });

/** Added **/

The above does not do anything with the response from the server if you need to do something then a callback will be called when the server has responded.

 var data = {'bob':'foo','paul':'dog'};
 $.ajax({
   url: url,
   type: 'POST',
   contentType:'application/json',
   data: JSON.stringify(data),
   dataType:'json',
   success: function(data){
     //On ajax success do this
     alert(data);
      },
   error: function(xhr, ajaxOptions, thrownError) {
      //On error do this
        if (xhr.status == 200) {

            alert(ajaxOptions);
        }
        else {
            alert(xhr.status);
            alert(thrownError);
        }
    }
 });
like image 148
ShiftyThomas Avatar answered Sep 20 '22 07:09

ShiftyThomas