Thanks to StackOverflow, I managed to get the following code working perfectly, but I have a follow up question.
$.get('http://example.com/page/2/', function(data){
$(data).find('#reviews .card').appendTo('#reviews');
});
This code above enabled my site to fetch a second page of articles with a Load More button in WordPress. However when the site runs out of pages/results, I'm running into a small issue. The load more button remains in place. It will keep trying to fetch data even if no pages are remaining.
How can I tweak this command so that I can show a visual response if the .get
request fails or is a (404) not found page for instance?
If someone could help me out with a simple example of even an alert("woops!");
that would be awesome!
Thanks!
This question is related to
jquery
If you want a generic error you can setup all $.ajax()
(which $.get()
uses underneath) requests jQuery makes to display an error using $.ajaxSetup()
, for example:
$.ajaxSetup({
error: function(xhr, status, error) {
alert("An AJAX error occured: " + status + "\nError: " + error);
}
});
Just run this once before making any AJAX calls (no changes to your current code, just stick this before somewhere). This sets the error
option to default to the handler/function above, if you made a full $.ajax()
call and specified the error
handler then what you had would override the above.
You can chain .fail()
callback for error response.
$.get('http://example.com/page/2/', function(data){
$(data).find('#reviews .card').appendTo('#reviews');
})
.fail(function() {
//Error logic
})
You can get detail error by using responseText property.
$.ajaxSetup({
error: function(xhr, status, error) {
alert("An AJAX error occured: " + status + "\nError: " + error + "\nError detail: " + xhr.responseText);
}
});
Source: Stackoverflow.com