Example 1: jquery ajax get
$.ajax({
url: "www.site.com/page",
success: function(data){
$('#data').text(data);
},
error: function(){
alert("There was an error.");
}
});
Example 2: jquery get
$.get( "ajax/test.html", function( data ) {
$( ".result" ).html( data );
alert( "Load was performed." );
});
Example 3: ajax data post call in javascript
$.ajax({
url: 'ajaxfile.php',
type: 'post',
data: {name:'yogesh',salary: 35000,email: '[email protected]'},
success: function(response){
}
});
Example 4: jquery get request
jQuery get() Method
The jQuery get() method sends asynchronous http GET request to the server and retrieves the data.
Syntax:
$.get(url, [data],[callback]);
Parameters Description:
url: request url from which you want to retrieve the data
data: data to be sent to the server with the request as a query string
callback: function to be executed when request succeeds
The following example shows how to retrieve data from a text file.
Example: jQuery get() Method
$.get('/data.txt',
function (data, textStatus, jqXHR) {
alert('status: ' + textStatus + ', data:' + data);
});
In the above example, first parameter is a url from which we want to retrieve the data. Here, we want to retrieve data from a txt file located at mydomain.com/data.txt. Please note that you don't need to give base address.
Example 5: how to get the status of other urls in ajax
$('#main-menu a').on('click', function(event) {
event.preventDefault();
$.ajax(this.href, {
success: function(data) {
$('#main').html($(data).find('#main *'));
$('#notification-bar').text('The page has been successfully loaded');
},
error: function() {
$('#notification-bar').text('An error occurred');
}
});
});
Example 6: jquery ajax post
var request;
$("#foo").submit(function(event){
event.preventDefault();
if (request) {
request.abort();
}
var $form = $(this);
var $inputs = $form.find("input, select, button, textarea");
var serializedData = $form.serialize();
$inputs.prop("disabled", true);
request = $.ajax({
url: "/form.php",
type: "post",
data: serializedData
});
request.done(function (response, textStatus, jqXHR){
console.log("Hooray, it worked!");
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.error(
"The following error occurred: "+
textStatus, errorThrown
);
});
request.always(function () {
$inputs.prop("disabled", false);
});
});