jQuery AJAX Support

ajax method

$.ajax method is used to invoke the server web methods with request object and gets response object.

We can use ajax call when need to update only part of the content in the page using server method without postback of entire page.

Simple jQuery AJAX Call Example

Calls a method on the server /api/getTime with the input parameter country='USA' and replace the element with id 'country-time' html with the returned time.

here url parameter is used to mention the API method to request, data parameter is the request parameters and mentioned as JSON format.

success parameter is used to mention the call back function once request is successfully completed. Mostly used to update the section of page content using response object (result).

$.ajax({
  url: "/api/getTime",
  data: {
    country: 'USA'
  },
  success: function( result ) {
    $( "#country-time" ).html( "" + result + "" );
  }
});

AJAX JSON Request and Response

type parameter is used to mention Rest API type whether GET, POST, PUT or DELETE.

dataType parameter is used to mention the request and response data type format.

success parameter is used to mention call back function when AJAX call is successfully completed. here creates table format for response object and binds to html element having id as employees-info.

error parameter is used to mention call back function when AJAX call is failed. here alert message is displayed as "Error". err object can be used to trace the error reason.

$.ajax({
  url: "/api/getEmployees",
  type: "GET",
  dataType: "json",
  data: {
    DepartmentID: 20
  },
  success: function( result ) {
    if(result.employees.length > 0) {
      output = '<table><tr><th style="width: 30%;">ID</th><th style="width: 70%;">Name</th></tr>';
      for(i=0; i< result.employees.length; i++){
         output += '<tr><td>'+ result.employees[i].ID + '</td><td>' + result.employees[i].Name + '</td></tr>';
      }
      output += '</table>';
      $('#employees-info').html(output);
    } 
    
  },
  error: function(err) {
    alert("Error");
  }
});



Privacy Policy  |  Copyrightcopyright symbol2020 - All Rights Reserved.  |  Contact us   |  Report website issues in Github   |  Facebook page   |  Google+ page

Email Facebook Google LinkedIn Twitter
^