How to send a JSON object with jQuery

Here is an example on how you can send a JSON object to a server with jQuery:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
  var data = {
    "name": "Neugebauer",
    "prename": "Benny",
    "age": 24,	
    "likes": [],        
    "device": "Laptop"
  };
 
  jQuery(document).ready(function($){
    $.ajax({
      type: "POST",
      url: "https://www.bennyn.de/rest-service/something",
      data: typeof data == "string" ? data : JSON.stringify(data || {}),
      dataType: "json",
      contentType: "application/json; charset=utf-8",
      success: function(data, textStatus, jqXHR){
        console.log('OK:' + data);
      },
      error: function(data, textStatus, jqXHR){ 
        console.log('ERROR:' + data);
      }
    });
  });      
</script>

How to parse JSON with jQuery

With jQuery you could easily parse a JSON (which is an object in JavaScript Object Notation). The method parseJSON of jQuery translates the JSON even into the corresponding JavaScript data types. As an example I have chosen the following JSON:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
{
        "firstName": "Joe",
        "lastName" : "Black",
        "age"      : 28,
        "address"  :
        {
          "streetAddress": "1st Street",
          "city"         : "New York",
          "state"        : "NY",
          "postalCode"   : "10021"
        },
        "phoneNumber":
        [
          {
            "type"  : "home",
            "number": "212555-1234"
          },
          {
            "type"  : "fax",
            "number": "646555-4567"
          }
        ],
        "married" : true,
        "developer" : true	
}

This JSON contains nested objects like address, an array like phoneNumber and key-value pairs of different types like firstName (string), age (number) and married (boolean).

Here it is shown how it is parsed:
How to parse JSON with jQuery weiterlesen