jQuery Mobile Ajax Navigation timeout - javascript

In jQuery Mobile, if user clicks on a button, a loading icon appears and then it loads the new webpage via Ajax.
But, The server may be not respond in my case. Isn't there any way to put a timeout (e.g. 10 seconds) for ajax navigation feature? (If time limit exceeds, stop trying to navigate and show an error message)

To set a timeout i think you should not do it in a static way ( using "data-transition" )
you can make a listener to the link ('onclick') and within the listener make an ajax call to load your page. Use $.mobile.changePage() to do that.
The $.mobile.changePage() function is used in a number of places in jQuery Mobile. For example, when a link is clicked, its href attribute is normalized and then $.mobile.changePage() handles the rest.
so your code could seem like this :
$('#link_id').click(function() {
$.ajax({
url: "page_served_from_server",
error: function(jqXHR, strError){
if(strError == 'timeout')
{
//do something. Try again perhaps?
}
},
success: function(){
//charge your page :
// $.mobile.changePage('yourPageAdress',"turn",false,true);
},
// here you can specify your timeout in milliseconds
timeout:3000
});
});

Related

jQuery stop load() if another load() is initiated on the same container

I have a dynamic website with a lot of AJAX and jQuery loading in different modules to different containers.
For the purpose of my question, consider that I have 3 buttons and one container. Clicking button A loads a.php into the container using jQuery
$('.container').load('a.php');
Now consider that module b.php is a module that takes about 3-4 seconds to load because it's grabbing content from another website and parsing it.
When I click button B to load module b.php, but then quickly click button A again to load module a.php, my problem occurs: module a.php quickly loads in the container, but the loading of module b.php was still in progress, therefore, after another second or 2-3, module b.php loads into the container, even though the user last clicked button A.
So here's my question: how can I stop the loading of module b.php if a user clicks another button.
Note: as a work-around I've thought of disabling the buttons until the loading of each module has completed. It does prevent the issue, but it's not the desired end result.
EDIT: So I've seen this: Aborting jQuery().load() and yes, I can get it working using AJAX. Thanks to everyone who suggested this. I'm hoping to find an answer that actually works with load() but haven't found one that works yet.
By using beforeSend, You can abort first ajax request before sending next ajax request , see example
<button onclick="onClickBtnA()">A</button>
<button onclick="onClickBtnB()">B</button>
In your jQuery
var currentRequest = null;
function onClickBtnA(){
currentRequest = $.ajax({
url: 'AJAX_URL_1',
beforeSend : function() {
if(currentRequest != null) {
currentRequest.abort();
}
},
success: function(data) {
//do something
}
});
}
function onClickBtnB(){
currentRequest = $.ajax({
url: 'AJAX_URL_2',
beforeSend : function() {
if(currentRequest != null) {
currentRequest.abort();
}
},
success: function(data) {
//do something
}
});
}
Make a global variable and abort it every time you load data
<button>Get External Content</button>
var xhrPrevoius; // use this global var and assign it for your previously
// loaded ajax when you making ajax request
var xhrThis;
$("button").click(function(){
$("#div1").load("demo_test.txt", function(responseTxt, statusTxt,
xhrThis){
if(statusTxt == "success")
// do you work here
xhrPrevoius.abort(); // abort here the previously loaded ajax
if(statusTxt == "error")
alert("Error: " + xhr.status + ": " + xhr.statusText);
});
});
If you want to stick with using load, rather than doing an ajax request as has been suggested, you could load into a hidden div, then use load's callback option to decide whether or not to copy from the hidden div into a visible component.

AJAX stop working on loading same site different PHP id

So i have a website that I'm doing for a school project. It's supposed to be like PasteBin. So on the right theres a different div (Uued koodid) that shows newest pastes. On click, they are supposed to show what they include using AJAX to refresh the left div. This only works for 4 times and then stops, but URL is still changing. After refresh it changes again and works again for 4 more times.
In main.js i have
...
$.ajaxSetup({ cache: false });
...
$(".uuedKoodid").click(function () {
$(".left-content").load(document.location.hash.substr(1));
});
...
EDIT:
Also other AJAX functions work. If I log in, I can switch between settings and profile perfectly but still cannot watch new codes
When you replace right menu with new code (from ajax call) you don't attach click event again on .uuedKoodid items so they don't do anything. You need to attach event again or attach it like this:
$(document).on('click', '.uuedKoodid', function () {
$(".left-content").load(document.location.hash.substr(1));
});
Edit:
As you noticed this will cause small problem. onclick event run before browser run standard link action. First you load ajax and then browser changes address. This way you are 1 action behind. Better solution than reading with delay (setTimeout) i think would be to read address directly from link:
$(document).on('click', '.uuedKoodid', function () {
var url = $(this).attr('href');
$(".left-content").load(url.substring(url.indexOf("#")+1));
});

Duplicate javascripts are getting loaded ajax

I'm developing a web based document management for my final year project. The user interacts with only one page and the respective pages will be called using AJAX when the user click the respective tabs (Used tabs for navigation).
Due to multiple user levels (admin, managers, etc.) I've put the javascripts into the correspondent web pages.
When user requests the user request everythings work perfectly except some situations where some functions are triggered multiple times. I found the problem. It is each time the user clicks a tab it loads same scripts as new instance and both of them will be triggered when I call a function.
to load the content I tired
.load and $.ajax(); non of them address the issue.
I tried to put all into the main page at that time my jQueryUI does not work. I tired
$(document).load('click', $('#tab_root li'), function(){});
Same issue remain.
Can anyone help me out this issue?
--Edit--
$(function){
$(document).on('click','#tabs',function(e){
getAjax($(this))
});
}
//method to load via AJAX
function getAjax(lst){
var cont = $(lst).text();
$.ajax({
url:'../MainPageAjaxSupport',
data: {
"cont":cont
},
error: function(request, status, error){
if(status==404){
$('#ajax_body').html("The requested page is not found. Please try again shortly");
}
},
success: function(data){
$('#ajax_body').html(data);
},
});
}
You can't undo JavaScript after it has been executed by simply unloading the file or removing the script element.
The best solution would probably be to set a variable in each JavaScript file you include in your ajax data and include them from an online inline JavaScript inside the ajax data along with a conditional like such:
<script>
if(!tab1Var) $.getScript("filename");
<script>
Older Solutions
You can manually unbind each event before setting them with off.
$(function){
$('#tabs').off('click');
$('#tabs').on('click',function(e){
getAjax($(this));
});
}
Alternatively you can initialize a global variable (eventsBound1=false) for each tab in the main html:
$(function){
if(!eventsBound1){
$('#tabs').on('click', function(e){
getAjax($(this));
});
eventsBound1 = true;
}
}
The tabs click event is only an example you have to do this for each time you bind an event in the scripts that are being reloaded.
if all the events are bound to things inside ajax_body, a final thing you can try is:
success: function(data){
$('#ajax_body').empty();
$('#ajax_body').html(data);
},
You have bind an event click on 'document' so getAjax() only replace the '#ajax_body' not the 'document'.
This means old event is still attached to the 'document' all you need is to unbind event by using $(document).off('click'); or change 'document' to other elements.

Is there any way to disable the beforeSend event for a single ajax call?

I have an ajax loader much like this one:
$('#loadingDiv')
.hide() // hide it initially
.ajaxStart(function() {
if(showSpinner == true){
$(this).show();
}
else{
showSpinner = true;
}
})
.ajaxStop(function() {
$(this).hide();
})
;
from: How to show loading spinner in jQuery?
edited after updates
I initialize showSpinner = true, and set it to false immediately before my recurring ajax call. It works most of the time but sometimes the spinner won't show up when its supposed to. I've polled the value of showSpinner and it looks like it remains false for too long between when its set and when it's set back to true.
It works wonderfully, but I also have a recurring ajax call that is executed every 15 seconds, and I don't want the ajax loader to appear for that one. I've tried this:
showSpinner = false;
// make ajax call to the database to check for new photos
$.ajax('/url', {
type:"post",
data: data,
success: function(response){
}
});
and it will prevent the spinner from appearing, but sometimes it disables the spinner for the other ajax calls too (other times it works fine). I've tried moving the re-enabling of the spinner to beforeSend but it didn't help. When the setInterval call that executes the code above is removed, it fixes the problem.
My other option is to include the spinner every place an ajax call occurs, but I'd prefer the more generic solution. Does anyone know how to get around this?
Thanks.
This sounds very similar, if not identical, to my own question about disabling certain ajax event handlers. This answer may be useful to you.

How do people achieve the loading effect with jQuery modal windows?

I'm going to be dynamically loading certain information in a modal window via ajax.
I've noticed on other sites that a small circular loading animation will appear in a modal window prior to loading the content. Does anyone know how this effect is achieved and possibly where to find the loading animation?
Thanks
The jQuery $.ajax() method provides for this by allowing you to specify a method to call upon ajax invoke and another method to call upon ajax response. The logical extension of this functionality is displaying a div containing an animated gif in the first call and clearing it in the second call. Here's an example. I do this in my $.ajaxSetup call when setting my ajax call defaults so that all of my ajax calls have the same behavior, but you can implement this at the $.ajax level to have potentially a different type of start/stop behavior depending on situation.
beforeSend: function() {
$('div#ajaxProcessingMessageDiv').show();
},
complete: function() {
$('div#ajaxProcessingMessageDiv').hide();
}
Happy coding,
Maybe consider using this jquery plugin
BlockUI
// unblock when ajax activity stops
$(document).ajaxStop($.unblockUI);
function test() {
$.ajax({ url: 'wait.php', cache: false });
}
$(document).ready(function() {
$('#pageDemo2').click(function() {
$.blockUI({ message: '<h1><img src="busy.gif" /> Just a moment...</h1>' });
test();
});
});
A Google search for "ajax loader", "ajax load", "loading animation", etc. brings up http://ajaxload.info/.
Some times it usefull to inform users by notificator jGrowl.

Categories