Http POST request with jQuery ajax

One of the most common scenarios is making client side Http calls to URLs to external or internal domain 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.

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

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

var Guid = createGuid();

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

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:

[WebMethod]

public static string DemoMethod(string firstName, string lastName, string pID) {return "demo";}

Client-side jquery ajax call:

$.ajax({
type: ‘POST’,
url: “DemoPage.aspx/DemoMethod”,

contentType: “application/json; charset=utf-8”,
dataType: ‘json’,
headers: {
‘Accept’: ‘application/json’,
‘Content-Type’: ‘application/json’,
‘firstName’: firstName,
‘lastName’: lastName,
‘x-requestKey’: Guid
},
data: dataSent,
async: false,
success: function (response) {
alert(response);
if (response != null && response.d != null) {
alert(response.d);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(‘error’);
}
});

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

Advertisements

One thought on “Http POST request with jQuery ajax

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.