ajax

callbacks

You can assign callbacks via jqXHR object or via the request settings.

var jqxhr = $.ajax( "example.php" )
  .done(function() {
    alert( "success" );
  })
  .fail(function() {
    alert( "error" );
  })
  .always(function() {
    alert( "complete" );
  });

$.ajax("example.php", {
  success: function(response) {
         alert( "success" );
    }
  statusCode: {
    404: function() {
      alert( "page not found" );
    }
  }
});

submit form

Sometimes it is preferable to use an ajax request, rather than a form submit button. For example, some data must be calculated and therefore cannot be stored in hidden elements.


var data = $("#myform").serializeArray(); // convert form data to array
data.push({name: "NonFormValue", value: NonFormValue});

$.ajax({
    type: 'POST',
    url: urlaction,
    data: $.param(data)
});

// or 

$.ajax({
    type: 'POST',
    url: urlaction,
    data: $("#myform").serialize()+"&NonFormValue="+encodeURIComponent(NonFormValue)
});

json rest api

$.ajax({
    url: "/myapi.com.action",
    type: 'POST', 
    contentType: "application/json",
    dataType: "json",
    data: JSON.stringify({ // collect data from different source like form elements
              id : $("#docid").text(),
              title : $("#docTitle").val(),
              lang : $("#docLang").val(),
              content: mc.getDoc().getValue()
        }),

    success: function(response) {
       // let response is json  like {data: {...}, error: "", code: "ok"}
         var data = response.data;
        
         if(data.code != "ok"){
            
         }
         ...
    },

    error: function (data) {
         alert("error: "+data);
    }
    });
}

download html

We load a HTML content and insert it to the #result element. If the request is successful, an alert will be shown.

$( "#result" ).load( "ajax/test.html", function() {
  alert( "Load was performed." );
});

download json

We load the elements as JSON data and then add them to the page.

$.getJSON( "ajax/test.json", function( data ) {
  var items = [];
  $.each( data, function( key, val ) {
    items.push( "<li id='" + key + "'>" + val + "</li>" );
  });
 
  $( "<ul/>", {
    "class": "my-new-list",
    html: items.join("")
  }).appendTo( "body" );
});