Web API With AJAX: Understanding POST Request in Web API

Web API with AJAX: Understand POST request in Web API

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.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="APICall.aspx.cs" Inherits="WebApplication1.APICall" %>

 

<!DOCTYPE html>

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

    <script src="jquery-1.7.1.js" type="text/javascript"></script>

     <script>

         $(document).ready(function () {

             $("#Save").click(function () {

                

                 var person = new Object();

                 person.name = $('#name').val();

                 person.surname = $('#surname').val();

 

                 $.ajax({

                     url: 'http://localhost:3413/api/person',

                     type: 'POST',

                     dataType: 'json',

                     data: person,

                     success: function (data, textStatus, xhr) {

                         console.log(data);

                     },

                     error: function (xhr, textStatus, errorThrown) {

                         console.log('Error in Operation');

                     }

                 });

 

 

             });

         });

    </script>

</head>

<body>

 

    <form id="form1">

        Name :- <input type="text" name="name" id="name" />

        Surname:- <input type="text" name="surname" id="surname" />

        <input type="button" id="Save" value="Save Data" />

    </form>

</body>

</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 .
 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Net.Http;

using System.Web.Http;

 

namespace WebApplication1.WebAPI

{

    public class person

    {

        public string name { get; set; }

        public string surname { get; set; }

    }

 

    public class personController : ApiController

    {

        [HttpPost]

        public string Post( person obj)

        {

            return obj.name + obj.surname;

        }

   }

}

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.

Web-API1

In the Web API we are getting the value that we have sent from the client end.

Web-API2

In the successful callback function we are just printing this value to the console. Here is sample output.

Web-API3

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.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="APICall.aspx.cs" Inherits="WebApplication1.APICall" %>

<head runat="server">

    <script src="jquery-1.7.1.js" type="text/javascript"></script>

     <script>

         $(document).ready(function () {

             $("#Save").click(function () {

                 var person = new Object();

                 person.name = $('#name').val();

                 person.surname = $('#surname').val();

 

                 $.post('http://localhost:3413/api/person', person, function (data) {

                     console.log(data);

                 });

             });

         });

    </script>

</head>

<body>

 

    <form id="form1">

        Name :- <input type="text" name="name" id="name" />

        Surname:- <input type="text" name="surname" id="surname" />

        <input type="button" id="Save" value="Save Data" />

    </form>

</body>

</html>

Here is the output of the post() method.

Web-API4

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.

Up Next
    Ebook Download
    View all
    Learn
    View all