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

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.

Related

JQuery not opening the already opened window when clicked twice

I am relatively new to JQuery. I have an anchor tag in JSP which when clicked calls a function and it in turn calls an action class. If the result is success, it has to open a window. It works fine for the first time. But when i click on the anchored url for the 2nd time, control goes to action class but it doesnt pop up the already opened window. It doesnt even open a new window. Please suggest how to resolve it ?I need to pop up the already opened window.. I am sure it is due to jquery ajax call because the functionality works fine with out using ajax jquery. But i need to use it in my scenario
Sample code:
Open W3Schools
function func1() {
$.ajax({
url: "abc.do",
success: function(response){
window.open("https://www.w3schools.com","MyWindow","left=10,top=20,width=1200,height=700,scrollbars=1,resizable=1, status=1, modal=yes");
},
error: function(e){
alert('Error: ' , e);
}
}); }
Probably your browser detects a pop-up and blocks it without telling your program. How are you calling your function? Usually repeated window.open calls will only work in an event listener like
button.addEventListener("click", ()=>{
func1();
});
So if you have it in a loop or a similar thing, there's not much you can do about pop-up protection.
Try passing an empty name to your window instead of MyWindow, like this:
function func1() {
$.ajax({
url: "abc.do",
success: function(response){ window.open("https://www.w3schools.com","","left=10,top=20,width=1200,height=700,scrollbars=1,resizable=1, status=1, modal=yes");
},
error: function(e){
alert('Error: ' , e);
}
}); }

Program does not recognize .modal("show") function after appending HTML to page

I am writing a program where a click event handler fires an ajax request to my node server, which then renders info inside of a handlebars partial and sends it back to the client (res.render("partials/scraped-article", data);). The client-side javascript appends this html to the document and shows a modal using the bootstrap .modal("show") function. The program shows the modal the first time the click event handler gets fired, but does not recognize the .modal("show") function afterwards. Is there a way to fix this?
Client-Side Javascript:
$(document).on("click", "#scrape-options li", function(){
var choice = $(this).text();
var request;
if(choice === "website1")
request = "/scrape/website1";
else
request = "/scrape/website2";
$.ajax({
type: "GET",
url: request
}).then(function(response){
$(".news-article").remove();
$("footer").append(response);
$('.news-article-img').each(function(i, element){
$(this).css({'height': ($(this).next().height() + 'px')});
});
$("footer h1").addClass("display-none");
$("#articles-added").text($(".news-article").length);
$(".modal").modal("show");
});
});
It turns out that even if you are rendering a partial, the response sent from the server will be embedded in the default template (i.e. it will be a full HTML document). If you simply add this to the DOM, you will be inserting the script for Bootstrap a second time, which will do weird things like disable the $(...).modal function. Instead, you should use the array.split method to extract the body HTML and then append this to the DOM.

Jquery spinner overlay loading

I am currently working with jQuery/Ajax. I wanted to add a spinner when an ajax request is made. My scenario is: There are two tabs in the UI, one is Home and other is Activities. So, when the user click the Activities tab, it will make ajax request to the backend. At this point I wanted to add a loading spinner overlay to the whole page. I am currently using jQuery block UI. I doesn't seem to work with this. I have my code like this:
beforeSend: function (xhr) {
$.blockUI({message: $("#spinner")});
//show the loading spinner.
},
success: function (data) {
//get the data.
},
error: function (error) {
//get the error response.
},
complete: function (jqXHR, textStatus) {
$.unblockUI();
//hide the loading spinner
}
I have my spinner element like this:
<div id="spinner" style="background:url('assets/img/spinner.gif')"></div>
Is there something I am missing here....
Update: (Solved)
The reason was due to the ajax synchronous nature. It locks the browser until the response is received. So, I changed by call to be async. You may want to look here for more discussion. view
According to jQuery BlockUI Plugin's documentation, the message parameter expects an HTML string.
So, you must change that part of your code to:
$.blockUI({ message: $("#spinner").html() });

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.

jQuery Mobile Ajax Navigation timeout

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
});
});

Categories