How to send HTTP Request in jQuery.

Using jQuery is pretty easy. There is many way you can send HTTP request. There are 3 main method that you can use to send Ajax Request in jQuery.

$.get(“”,{},function(){});

$.post(“”,{},function(){});

$.ajax({
url: “blahblah”,
type: ‘GET’,
dataType: ‘json’, // added data type
success: function(res) {
console.log(res);
alert(res);
}
});

The first 2 method are common and easier way to send HTTP request. First parameter was path, second is body and third is callback. If you are new to callback concept, you can learn it on my blog here What is callback

How to test-

Open chrome dev tool and go to console and start playing with it.

$.ajax give some power to developer as it have some more callback like Error and Success

jQuery.ajax({
type: “POST”,
url: “saveuser.do”,
dataType: “html”,
data: “userId=” + encodeURIComponent(trim(document.forms[0].userId.value)),
success: function (response) {
alert(“Details saved successfully!!!”);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});

 

This code handle both Success and Error. In case you want to handle error you can use $.ajax.

 

Leave a Reply

Your email address will not be published. Required fields are marked *