Skip to content

Instantly share code, notes, and snippets.

@gibson042
Last active November 23, 2021 19:11
Show Gist options
  • Save gibson042/a30c4aaed9df054e2ae1 to your computer and use it in GitHub Desktop.
Save gibson042/a30c4aaed9df054e2ae1 to your computer and use it in GitHub Desktop.
jQuery.xhr

AJAX Examples

jQuery.xhr will be an asynchronous HTTP request API returning standards-compliant thenables. We have identified two possible approaches:

  • Autosend: control by options parameter; advanced functionality via beforeSend (similar to jQuery.ajax)
  • Chainable: control by options and/or chainable setters; advanced functionality via send: false and a chainable send method

This gist compares the approaches by imagining their use for current jQuery.ajax examples. To better highlight differences, chaining methods will be used instead of options more heavily than is likely in actual practice (assuming that options is available in the "Chainable" solution).

$.ajaxSetup({
cache: false,
timeout: 15000,
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content'),
Authorization: "token " + token
}
});
// TODO: autosend/chainable
// http://api.jquery.com/jquery.ajax/#entry-examples
// Plausible real-world scenarios and their analogs
// xhrFields
$.ajax({
url: a_cross_domain_url,
xhrFields: {
withCredentials: true
}
});
// autosend
$.xhr( a_cross_domain_url, {
beforeSend: function( req ) {
req.getNativeRequest().withCredentials = true;
}
});
// chainable
var req = $.xhr( a_cross_domain_url, { send: false } ).setNative({ withCredentials: true }).send();
// overrideMimeType/converters
$.ajax({
url: "http://fiddle.jshell.net/favicon.png",
beforeSend: function( xhr ) {
xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
}
}).done(function( data ) {
console.log( "Sample of data:", data.slice( 0, 100 ) );
});
// autosend/chainable
$.xhr( "http://fiddle.jshell.net/favicon.png" ).then( $.xhr.responseData ).then( String ).then(function( data ) {
console.log( "Sample of data:", data.slice( 0, 100 ) );
});
// POST
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
// autosend
$.xhr( "some.php", {
method: "POST",
body: { name: "John", location: "Boston" }
}).then(function( response ) {
alert( "Data Saved: " + response.data );
});
// chainable
$.xhr( "some.php", {
method: "POST",
send: false
}).send({
name: "John", location: "Boston"
}).then(function( response ) {
alert( "Data Saved: " + response.data );
});
// raw POST
$.ajax({
url: "page.php",
processData: false,
data: xmlDocument
}).done( handleResponse );
// autosend
$.xhr( "page.php", {
processData: false,
body: xmlDocument
}).then( $.xhr.responseData ).then( handleResponse );
// chainable
$.xhr( "page.php", {
method: "POST",
send: false
}).sendRaw( xmlDocument ).then( $.xhr.responseData ).then( handleResponse );
// dataType: script
$.ajax({
url: "test.js",
dataType: "script"
});
// autosend/chainable
$.xhr( "test.js" ).then( $.xhr.responseData ).then( $.globalEval );
// http://api.jquery.com/jquery.ajax/#entry-examples
// Implausible calls
// context
$.ajax({
url: "test.html",
context: document.body
}).done(function() {
$( this ).addClass( "done" );
});
// autosend/chainable
$.xhr( url ).then(
$.proxy(
function() {
$( this ).addClass( "done" );
},
document.body
)
)
// All handlers
var jqxhr = $.ajax( "example.php" )
.done(function() {
alert( "success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "complete" );
});
jqxhr.always(function() {
alert( "second complete" );
});
// autosend/chainable
var req = $.xhr( "example.php" );
req.then(
function() {
alert( "success" );
}, function() {
alert( "error" );
});
(function(fn) {
req.then( fn, fn );
})(function() {
alert( "complete" );
});
(function(fn) {
req.then( fn, fn );
})(function() {
alert( "second complete" );
});
// http://www.jquery4u.com/function-demos/index.php?function=ajax#code
$.ajax({
url: filename,
dataType: 'html',
beforeSend: function() {
$('#'+id+' .contentarea').html('<img src="/function-demos/functions/ajax/images/loading.gif" />');
},
success: function(data, textStatus, xhr) {
if (filename == '/function-demos/functions/ajax/data/content3.html') {
setTimeout( function() {
$('#'+id+' .contentarea').html(data);
}, 2000);
} else {
$('#'+id+' .contentarea').html(data);
}
},
error: function(xhr, textStatus, errorThrown) {
$('#'+id+' .contentarea').html(textStatus);
}
});
// autosend
$.xhr( filename, {
beforeSend: function() {
$('#'+id+' .contentarea').html('<img src="/function-demos/functions/ajax/images/loading.gif" />');
}
}).then(
function( response ) {
if (filename == '/function-demos/functions/ajax/data/content3.html') {
setTimeout( function() {
$('#'+id+' .contentarea').html( response.data );
}, 2000);
} else {
$('#'+id+' .contentarea').html( response.data );
}
}, function( exception ) {
$('#'+id+' .contentarea').html( exception.textStatus );
}
);
// chainable
var req = $.xhr( filename );
$('#'+id+' .contentarea').html('<img src="/function-demos/functions/ajax/images/loading.gif" />');
req.then(
function( response ) {
if (filename == '/function-demos/functions/ajax/data/content3.html') {
setTimeout( function() {
$('#'+id+' .contentarea').html( response.data );
}, 2000);
} else {
$('#'+id+' .contentarea').html( response.data );
}
}, function( exception ) {
$('#'+id+' .contentarea').html( exception.textStatus );
}
);
// http://www.php4every1.com/tutorials/jquery-ajax-tutorial/
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'json',
data: {
email : $('#email').val()
},
success : function(data){
$('#waiting').hide(500);
$('#message').removeClass().addClass((data.error === true) ? 'error' : 'success')
.text(data.msg).show(500);
if (data.error === true)
$('#demoForm').show(500);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#waiting').hide(500);
$('#message').removeClass().addClass('error')
.text('There was an error.').show(500);
$('#demoForm').show(500);
}
});
// autosend
$.xhr( 'post.php', {
method : 'POST',
body: {
email : $('#email').val()
}
}).then( $.xhr.responseData ).then( $.parseJSON ).then(
function(data){
$('#waiting').hide(500);
$('#message').removeClass().addClass((data.error === true) ? 'error' : 'success')
.text(data.msg).show(500);
if (data.error === true)
$('#demoForm').show(500);
}, function(exception) {
$('#waiting').hide(500);
$('#message').removeClass().addClass('error')
.text('There was an error.').show(500);
$('#demoForm').show(500);
}
);
// chainable
$.xhr( 'post.php', {
method : 'POST',
send: false
}).send({
email : $('#email').val()
}).then( $.xhr.responseData ).then( $.parseJSON ).then(
function(data){
$('#waiting').hide(500);
$('#message').removeClass().addClass((data.error === true) ? 'error' : 'success')
.text(data.msg).show(500);
if (data.error === true)
$('#demoForm').show(500);
}, function(exception) {
$('#waiting').hide(500);
$('#message').removeClass().addClass('error')
.text('There was an error.').show(500);
$('#demoForm').show(500);
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment