Render API Using AJAX Call

Introduction 

 
In this article, we will discuss how to invoke API using the AJAX call. We use the AJAX call because it allows the user to update a web page without reloading the page, request data from a server after the page has loaded, receive data from a server after the page has loaded, and send the data to a server in the background.
 
The below HTTP verb is used to call a particular Web API call. Here is the mapping sequence.
  • POST - Create
  • GET - Read
  • PUT - Update
  • DELETE - delete
  1. var person = new Object();    
  2. person.name = $('#name').val();    
  3. person.surname = $('#surname').val();    
  4. $.ajax({    
  5.     url: 'http://localhost:3413/api/person',    
  6.     type: 'POST',    
  7.     dataType: 'json',    
  8.     data: person,    
  9.     success: function (data, textStatus, xhr) {    
  10.         console.log(data);    
  11.     },    
  12.     error: function (xhr, textStatus, errorThrown) {    
  13.         console.log('Error in Operation');    
  14.     }    
  15. });  
In the above code, we pass the person data to the API using the Post method.
 
You can call the API using the above code for different uses, like Delete record, Update record, and Get records using Get, Put, and Delete type keywords.