HTTP POST Request With jQuery AJAX

This post shows how to call Server ASP.NET method using jQuery Ajax making HTTP POST request with headers.

One of the most common scenarios is making client side HTTP calls to URLs to external or internal domains using jQuery Ajax. In this demo, I'll show how to call Page static method of an ASP.NET method written for an ASPX page using C#. The requirement is to use headers that need to be passed along with POST data.

  1. var dataSent = "{firstName : '" + firstName + "', lastName: '" + lastName + "', pID: '" + pID + "'}";  

I used the following JavaScript method to generate Guid which is RFC4122 version 4 compliant solution.

  1. var Guid = createGuid();  
  2.   
  3. function createGuid() {  
  4.     return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {  
  5.         var r = Math.random() * 16 | 0,  
  6.             v = c === 'x' ? r : (r & 0x3 | 0x8);  
  7.         return v.toString(16);  
  8.     });  
  9. }  

Below is the jQuery Ajax POST request calling the Page static method DemoMethod in the DemoPage.aspx.cs file with the following signature:

Server-side public static method
  1. [WebMethod]  
  2. public static string DemoMethod(string firstName, string lastName, string pID) {  
  3.     return "demo";  
Client-side jQuery Ajax call,
  1. $.ajax({  
  2.     type: 'POST',  
  3.     url: "DemoPage.aspx/DemoMethod",  
  4.     contentType: "application/json; charset=utf-8",  
  5.     dataType: 'json',  
  6.     headers: {  
  7.         'Accept''application/json',  
  8.         'Content-Type''application/json',  
  9.         'firstName': firstName,  
  10.         'lastName': lastName,  
  11.         'x-requestKey': Guid  
  12.     },  
  13.     data: dataSent,  
  14.     async: false,  
  15.     success: function(response) {  
  16.         alert(response);  
  17.         if (response != null && response.d != null) {  
  18.             alert(response.d);  
  19.         }  
  20.     },  
  21.     error: function(XMLHttpRequest, textStatus, errorThrown) {  
  22.         alert('error');  
  23.     }  
  24. });  

The response in the success part will be received by the object "response" and can be accessed using the response.d property.