19

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?

Daniel Chen
  • 1,933
  • 5
  • 24
  • 33
  • possible duplicate of [Send JSON to the server using jQuery](http://stackoverflow.com/questions/4118226/send-json-to-the-server-using-jquery) – Chris Moschini Sep 02 '13 at 22:20

7 Answers7

23
 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);
        }
    }
 });
ShiftyThomas
  • 476
  • 5
  • 18
  • Does this post a response? Or perhaps a better question, is there a way to post without dealing with a response; like kind of like a stream with just one packet – shanehoban May 27 '14 at 15:51
  • 1
    This does not handle any returned response from the server. – ShiftyThomas May 28 '14 at 20:15
  • Thanks, and would $.post be better then, if all I want to do is send a request with some data; and not care about the return? – shanehoban May 29 '14 at 06:55
  • $.post is just a shortened version of $.ajax (http://api.jquery.com/jquery.post/) so neither is 'better' $.post has a callback function for return of data too. I like to use $.ajax just because I always have. – ShiftyThomas Jun 01 '14 at 12:53
4

I've had the same problem. You can't send an object as "data", you need to stringify the object. Try this instead, with your object stringified:

$.ajax({
       url: url,
       type: 'POST',
       contentType:'application/json',
       data: '{
          name:"test",
          key:"foo",
          key2:"bar"
       }',
       dataType:'json'
});
Jonas
  • 121,568
  • 97
  • 310
  • 388
  • I've seen this too, but I've seen examples that show it like this: data: {name: 'test', key: 'foo', key2: 'bar'}. It fails every time when I try to code it like that – Yatrix Nov 11 '12 at 01:00
2

Try this: http://www.abeautifulsite.net/blog/2008/05/postjson-for-jquery/

Its a lot shorter:

$.post(url, data, function(response) {
    // Do something with the response
}, 'json');
Jānis Gruzis
  • 905
  • 1
  • 10
  • 25
  • I love this way. $.ajax is more for low level. – CStff May 02 '17 at 18:34
  • 1
    Link is dead, but the current version of jQuery provides an equivalent in any case, with some error handling niceness: see [the API documentation](http://api.jquery.com/jQuery.post/) – Ian Gibbs Oct 14 '17 at 05:18
0

Also, is necesary can create a parameter and assign the value with JSON.stringify

....
data: "jsonString="+JSON.stringify(data),
...
cmg_george
  • 309
  • 1
  • 2
  • 9
0

I agree the data must be converted into a JSON string, not only to agree with the dataType and contentType setup but more importantly, to satisfy the server.

data: JSON.stringify(data),
dataType:'json'
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
0

There are many ways to send JSON data to the server

1. Using Ajax

var data = <?php echo json_encode($data) ?>;
var url  = '<?php echo $url ?>';
jQuery.ajax({
    type: "POST",
    url: url,
    data: JSON.stringify(data),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(data){
        var jsonObj = jQuery.parseJSON(data);
        alert(jsonObj.encPassword);
    },
    failure: function(errorMsg) {
        alert(errorMsg);
    }
});

2. Using Curl

<?php
$content = json_encode($data);

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
        array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); //curl error SSL certificate problem, verify that the CA cert is OK

$result     = curl_exec($curl);
$response   = json_decode($result);
var_dump($response);
curl_close($curl);
?>

3. Using Streams

<?php
$options = array(
    'http' => array(
        'method'  => 'POST',
        'content' => json_encode( $data ),
        'header'=>  "Content-Type: application/json\r\n" .
                    "Accept: application/json\r\n"
      )
);

$context     = stream_context_create($options);
$result      = file_get_contents($url, false, $context);
$response    = json_decode($result);
var_dump($response);

4. Raw HTTP Post

Using Zend Framework’s HTTP client: http://framework.zend.com/manual/en/zend.http.client.advanced.html#zend.http.client.raw_post_data

$json = json_encode($data);
$client = new Zend_Http_Client($url);
$client->setRawData($json, 'application/json')->request('POST');
var_dump($client->request()->getBody());

SOURCE:- https://blog.magepsycho.com/sending-json-data-remote-server/

MagePsycho
  • 1,944
  • 2
  • 29
  • 60
-3
dataType: 'json',
Bruce Dou
  • 4,673
  • 10
  • 37
  • 56
  • To be more clear, this answer means that you have incorrectly capitalized your `dataType` value. String comparisons are case-sensitive, and jQuery only tests for `"json"`, not `"JSON"`. – Phrogz Dec 03 '10 at 06:24
  • 2
    `dataType` is used for the data that is returned by the response and not for the posting. – Jonas Jun 06 '11 at 16:39