jQuery All in one examples


Example

Ajax Get:

Solution 1:

$.get('url.html', function(data){
    $('#update-box').html(data);
});

Solution 2:

 $.ajax({
     type: 'GET',
     url: 'url.php',  
 }).done(function(data){
     $('#update-box').html(data);
 }).fail(function(jqXHR, textStatus){
     alert('Error occured: ' + textStatus);
 });

Ajax Load: Another ajax get method created for simplcity

$('#update-box').load('url.html');

.load can also be called with additional data. The data part can be provided as string or object.

$('#update-box').load('url.php', {data: "something"});
$('#update-box').load('url.php', "data=something");

If .load is called with a callback method, the request to the server will be a post

$('#update-box').load('url.php', {data: "something"}, function(resolve){
    //do something
});

Ajax Post:

Solution 1:

$.post('url.php', 
    {date1Name: data1Value, date2Name: data2Value},  //data to be posted
    function(data){
        $('#update-box').html(data);
    }
);

Solution 2:

$.ajax({
    type: 'Post',
    url: 'url.php',  
    data: {date1Name: data1Value, date2Name: data2Value}  //data to be posted
}).done(function(data){
    $('#update-box').html(data);
}).fail(function(jqXHR, textStatus){
    alert('Error occured: ' + textStatus);
});

Ajax Post JSON:

var postData = {
    Name: name,
    Address: address,
    Phone: phone
};

$.ajax({
     type: "POST",
     url: "url.php",
     dataType: "json",
     data: JSON.stringfy(postData),
     success: function (data) {
         //here variable data is in JSON format
     }
 });

Ajax Get JSON:

Solution 1:

$.getJSON('url.php', function(data){
    //here variable data is in JSON format
});

Solution 2:

 $.ajax({
      type: "Get",
      url: "url.php",
      dataType: "json",
      data: JSON.stringfy(postData),
      success: function (data) {
          //here variable data is in JSON format
      },    
      error: function(jqXHR, textStatus){
          alert('Error occured: ' + textStatus);
      }
  });