AJAX error handling with jQuery
HTML
<h1>AJAX error handling with jQuery</h1>
<div>
<button id="myBtnAjax">AJAX communication with error</button>
</div>
<div id="result">
</div>
JavaScript
$(document).ready(function() {
$('#myBtnAjax').click(function(event) {
/**
* http://api.jquery.com/jQuery.ajax/
*/
event.preventDefault();
$.ajax({
url: 'https://formsubmit.co/[email protected]',
type: "POST",
crossDomain: true,
dataType: "jsonp",
data: {
name: "John",
location: "Boston"
},
/**
* A function to be called if the request fails.
*/
error: function(jqXHR, textStatus, errorThrown) {
alert('An error occurred... Look at the console (F12 or Ctrl+Shift+I, Console tab) for more information!');
$('#result').html('<p>status code: ' + jqXHR.status + '</p><p>errorThrown: ' + errorThrown + '</p><p>jqXHR.responseText:</p><div>' + jqXHR.responseText + '</div>');
console.log('jqXHR:');
console.log(jqXHR);
console.log('textStatus:');
console.log(textStatus);
console.log('errorThrown:');
console.log(errorThrown);
},
/**
* A function to be called if the request succeeds.
*/
success: function(data, textStatus, jqXHR) {
$('#result').html(data);
alert('Load was performed. Look at the console (F12 or Ctrl+Shift+I, Console tab) for more information! ');
console.log('jqXHR:');
console.log(jqXHR);
console.log('textStatus:');
console.log(textStatus);
console.log('data:');
console.log(data);
}
});
});
});
///////////////////////////////////////////////////////////