Web API With AJAX: Understanding POST Request in Web API

This article provides a basic understanding of the Web API and concepts of AJAX in web applications.

This is the first presentation of the "Web API with AJAX" article series. This article provides a basic understanding of the Web API and concepts of AJAX in web applications. We can say that the Web API is the latest communication technology of the Microsoft platform. If we look back at Microsoft's communication technology we will find that communication started by holding the hand of remoting techniques. Then the concept of Web Services was introduced that began the use SOAP messages to send messages back and forth. It has a few limitations, such as only being able to be consumed by HTTP and able to host on IIS. Then WCF took entry with useful features. The limitation of IIS has gone and people started to host their application in various environments. Then new problems began. It's a programmer's nightmare to configure endpoints and consume them through a proper endpoint (If you are a good developer then you may ignore the line that you have read just now) .Then Microsoft introduced the concept of the Web API in MVC platforms on top of the traditional ASP.NET.
 
We can describe the Web API as a Swiss knife with many features and capabilities. It has simplified the concept of communication. And supports true RESTful features. The most beautiful advantage of the Web API is , it can be consumed by (almost) any type of client. It does not matter whether your client is built using C# or JavaScript or by some other language running on various platforms and devices. We will not continue our explanation much more because this is not core to a Web API article. So, let's start our coding session by assuming that you have a basic understanding of POST, GET , PUT and DELETE verbs of HTTP to talk about Web API applications.
 
As per the title, we will understand how to consume the Web API service using a POST method. If you are very new in this environment (read Web API and RESTful service) and still want to read , then the following paragraph is for you.
 
When we talk about RESTful services we need to think of each and every object as being a resource. Say for example we want to read the employee information whose id is 5, so the information is nothing but a resource. If I want to get the picture of whose name is "flower" then I think of the picture as nothing but a resource that can be consumed by a few HTTP verbs. In a broad sense, consume implies save, retrieve, update and delete. Now, our beloved CRUD operation can match with the HTTP verb. Here is the mapping sequence:
  • POST: Create
  • GET: Read
  • PUT: Update
  • DELETE: delete
So, the idea is that when we perform a create operation we well use the POST verb with respect to the RESTful service and in this article we will use the jQuery ajax() function for the post operation.
 
As per the concept of any service application, we need to implement both a client and a server. Here we will implement the client using JavaScript and JQuey. So, let's start to write the code.
 
Implement client code to consume Web API
 
This is the client-side implementation to consume the Web API service. We are loading jQuery from the local server and using the ajax() function.
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="APICall.aspx.cs" Inherits="WebApplication1.APICall" %>  
  2. <!DOCTYPE html>  
  3. <html xmlns="http://www.w3.org/1999/xhtml">  
  4. <head runat="server">  
  5.     <title></title>  
  6.     <script src="jquery-1.7.1.js" type="text/javascript"></script>  
  7.      <script>  
  8.          $(document).ready(function () {  
  9.              $("#Save").click(function () {  
  10.                  var person = new Object();  
  11.                  person.name = $('#name').val();  
  12.                  person.surname = $('#surname').val();  
  13.                  $.ajax({  
  14.                      url: 'http://localhost:3413/api/person',  
  15.                      type: 'POST',  
  16.                      dataType: 'json',  
  17.                      data: person,  
  18.                      success: function (data, textStatus, xhr) {  
  19.                          console.log(data);  
  20.                      },  
  21.                      error: function (xhr, textStatus, errorThrown) {  
  22.                          console.log('Error in Operation');  
  23.                      }  
  24.                  });  
  25.              });  
  26.          });  
  27.     </script>  
  28. </head>  
  29. <body>  
  30.     <form id="form1">  
  31.         Name :- <input type="text" name="name" id="name" />  
  32.         Surname:- <input type="text" name="surname" id="surname" />  
  33.         <input type="button" id="Save" value="Save Data" />  
  34.     </form>  
  35. </body>  
  36. </html>  
Please note the formation of the data that we are collecting from the HTML form. Since we have configured the ajax() method to communicate with the JSON data, we need to form the data in object format. So, this is the implementation of the client-side code.
 
Create Web API to serve RESTful service
 
In this section we will create the Web API application. We are skipping the basic Web API creation part hoping you know that. Here is the implementation of Web API .
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Web.Http;  
  7. namespace WebApplication1.WebAPI  
  8. {  
  9.     public class person  
  10.     {  
  11.         public string name { getset; }  
  12.         public string surname { getset; }  
  13.     }  
  14.     public class personController : ApiController  
  15.     {  
  16.         [HttpPost]  
  17.         public string Post( person obj)  
  18.         {  
  19.             return obj.name + obj.surname;  
  20.         }  
  21.    }  
  22. }  
At first we created a model class (person) that is very similar to the client object that we will send from the client application. The person controller contains the Posr() method that is specified with the HttpPost attribute. This implies that this action/method can be consumed by the POST verb. We are halting the execution flow and checking the form data to the Web API.
 
 
 
In the Web API we are getting the value that we have sent from the client end.
 
 
 
In the successful callback function we are just printing this value to the console. Here is sample output.
 
 
 
Use post() function of jQuery library
 
Here is another way to perform the POST operation. We can use the post() function to perform the post operation. Basically the post() function is nothing but a shorthand implementation of the ajax() function.
 
Have a look at the following code.
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="APICall.aspx.cs" Inherits="WebApplication1.APICall" %>  
  2. <head runat="server">  
  3.     <script src="jquery-1.7.1.js" type="text/javascript"></script>  
  4.      <script>  
  5.          $(document).ready(function () {  
  6.              $("#Save").click(function () {  
  7.                  var person = new Object();  
  8.                  person.name = $('#name').val();  
  9.                  person.surname = $('#surname').val();  
  10.                  $.post('http://localhost:3413/api/person', person, function (data) {  
  11.                      console.log(data);  
  12.                  });  
  13.              });  
  14.          });  
  15.     </script>  
  16. </head>  
  17. <body>  
  18.     <form id="form1">  
  19.         Name :- <input type="text" name="name" id="name" />  
  20.         Surname:- <input type="text" name="surname" id="surname" />  
  21.         <input type="button" id="Save" value="Save Data" />  
  22.     </form>  
  23. </body>  
  24. </html>  
Here is the output of the post() method.
 
 
 
Conclusion
 
This is the first lap of our Web API Ajax journey. Today we have learned the POST method and the practical implementation of that. In a future article we will learn all types of HTTP verbs and a few concepts of the Web API. Happy learning.