I have following code to show a loading panel after e.g. clicking a button and making an Ajax call:
$(document).on("click", function (e) {
window.LoadingPanel.Show();
});
After the Ajax call following code makes sure the loading panel disappears again:
$(document).ajaxComplete(function() {
if (window.LoadingPanel != null) {
window.LoadingPanel.Hide();
}
});
But in some cases I redirect to another page depending on the result of the Ajax call by setting the window.location.href.
In this case I want the ajaxComplete function NOT to hide the loading panel too early until the redirect has been succeeded.
How can I check in the ajaxComplete function if the window.location.href has been changed and the page is about to redirect?
This might not be a good way to solve this problem but thats what i can think of now.
1. create a variable call isHide = true;
2. In your jax call Onsuccess function set isHide = false if hiding is not require.
3. in your ajaxComplete see following
$(document).ajaxComplete(function(e) {
if (window.LoadingPanel != null && isHide) {
window.LoadingPanel.Hide();
}
});
Related
I want to demonstrate my window in a full screen.
I have a working function, but I have a problem:
I'm sending an AJAX call after user's click on some button in UI, to get some data and prepare it, after this ajax call (on success I want to demonstrate my data in the full screen, but I can't do that, because it raises an error:
Failed to execute 'requestFullScreen' on 'Element': API can only be initiated by a user gesture.
As you understand, I had user action - click on button, but it's not enough, if I' trying to execute fullscreen function in ajax call.
I was trying to use global variable too, to have a state(do I need to show fullscreen or not(it depends on result of response parsing(after AJAX call)), but it doesn't work too.I was trying in this way:
ISFULLSCREEN = false;
function get_ajax() {
ajax_call ()
.success(response) {
if (response.fullscreen) {
ISFULLSCREEN = true;
}
}
}
function useFullscreen() {
if (ISFULLSCREEN) {
use_fullscreen();
}
}
and my button looks like:
<button onclick="get_ajax();useFullscreen()" value="click me" />
but function useFullscreen runs faster, than the value of ISFULLSCREEN changes to true
Do somebody have any idea how to resolve this issue?
Thanks a lot!
Perhaps in your ajax request, use async: false to make the fetch synchronous, therefore keeping all the execution within the same event (from the user click).
The downside to this is that it may hang the page if it takes a long time
You can use callback function, a callback function is a function passed into another function as an argument, so you can utilize it, and it will execute after your awaited ajax response comes, see below example:
ISFULLSCREEN = false;
function get_ajax(useFullscreenCallback) {
ajax_call ()
.success(response) {
if (response.fullscreen) {
ISFULLSCREEN = true;
useFullscreenCallback();
}
}
}
function useFullscreen() {
if (ISFULLSCREEN) {
use_fullscreen();
}
}
get_ajax(useFullscreen);
Reference: Callback Function Mozilla web docs
Does this help you?: Run a website in fullscreen mode
The answer basically says that you cannot force a fullscreen change without user interaction but there are some alternate suggestions
Add async : false to ajax call and call the function useFullscreen on ajax success and remove this from the button onclick event
I start to using jQuery BlockUI Plugin to block user activity for the page until complete a button process on C#/ASP.NET side.
So I wrote this;
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.io/min/jquery.blockUI.min.js" ></script>
<script type="text/javascript">
$(document).ready(function () {
$('#MyButtonID').click(function () {
$.blockUI({ message: '<h1>Please wait..</h1>' });
});
});
</script>
As you can see, this is a simple code that blocks UI when I click asp:button which ID is MyButtonID until it finish it's process. This works great.
Now I try to create some alert based on a condition while on this click process. If I understand clearly, now I need to unblock my page as a first, show the alert and keep it blocked again until complete button process.
That's why I wrote two function (maybe I can call these $.unblockUI and $.blockUI directly without them?) in my javascript side for that;
function UnblockUI() {
$.unblockUI();
}
function BlockUI() {
$.blockUI({ message: '<h1>Please wait..</h1>' });
}
As far as I search, most common way to call Javascript function on server side is using ClientScriptManager.RegisterStartupScript method in C#. So I tried to alert something on C# side as an example with;
if(condition)
{
string script = string.Format("alert('{0}');", "Some error message");
Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "alert", script, true);
}
and it worked. After that, I tried to unblock page with calling UnblockUI function in my javascript side but it didn't unblock it.
if(condition)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "unblock", "UnblockUI", true);
string script = string.Format("alert('{0}');", "Some error message");
Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "alert", script, true);
}
If I understand correctly, this UnblockUI parameter calls my UnblockUI javascript function which I defined above and this function calls $.unblockUI(); and unblock my page which is blocked but as expected, it didn't work.
What am I missing here? Or am I didn't even understand that This plugin lets you simulate synchronous behavior when using AJAX, without locking the browser sentence?
Try using the function call as follows:
function unblockUI() {
$(function() {
$.unblockUI();
});
}
function blockUI() {
$(function() {
$.blockUI({ message: '<h1>Please wait..</h1>' });
});
}
I hope I have helped...
Here is what i am using in my current project.
$(document).ready(function () {
// unblock when ajax activity stops when DOM gets updated, means Ajax is completed
$(document).ajaxStop($.unblockUI);
//Block when trying for Ajax Activity
$('ul#Appdropdown').click(function (ev) {
$.blockUI();
//Add ajax call to get data
}
});
Implement the same and it will do the block and unblock for you.
I had an issue when using the $ajax complete function to stop the animation, If the ajax call fails i was resubmitting the ajax call, and wanted to block UI on resubmitting. But when making the call $.unblockUI inside of complete it was not animating correctly. It would flicker and disapear and not continue to block. However using global call to stop did work, allowing for blocking to re occur with a updated message on blocked UI.
$(document).ajaxStop($.unblockUI); // this works
instead of inside of the complete function of ajax
$.ajax({
complete: function(jqXHR, textStatus) {
$.unblockUI();// this did not always work
}
});
If you block user interface on this way :
BlockUI.Component(".page-content");
Then this is a working solution:
BlockUI.UnblockComponent(".page-content");
What I'm Trying To Accomplish
I need to trigger 1 to 3 different $.post() requests, and whether it's 1 call, 2 consecutive calls, or 3 consecutive calls is decided by some basic user selection. Each call must only start after the previous is completely finished.
I am dealing with 3 simple behavior cases -- the user, being presented with "Checkbox 1," "Checkbox 2," and a "Continue" button," opts to
Select nothing and then press "Continue" button, which makes an XHR call to '/remote.php',
The user opts to only select "Checkbox 1" or "Checkbox 2," and then presses "Continue" button, which calls $.post() Function 1 that is bound to Checkbox 1, or $.post() Function 2 that is bound to Checkbox 2, and then makes an XHR call to '/remote.php',
Or the user selects both Checkbox 1 + 2 and then presses Continue, which calls $.post() Function 1, then calls $.post() Function 2, and then makes an XHR call to '/remote.php'.
I need to make sure that the Continue-button $.post() function does not fire until the Checkbox-bound $.post() functions fire and complete.
The Problem
The problem is that if Checkbox 1 is selected and Checkbox 2 is selected, and then the Continue button is pressed, as I understand it, the loading order should be:
Checkbox 1 bound $.post() request fires and completes, then
Checkbox 2 bound $.post() request fires and completes, then
Continue button bound $.post() fires, and pages is changed via AJAX at the end of the function tied to "Continue" button bound function.
So, where the result should look like:
XHR finished loading: POST "/cart.php?action=add&product_id=1280".
XHR finished loading: POST "/cart.php?action=add&product_id=1284".
XHR finished loading: POST "/remote.php".
It instead often comes out like this:
XHR finished loading: POST "/cart.php?action=add&product_id=1280".
XHR finished loading: POST "/remote.php".
XHR finished loading: POST "/cart.php?action=add&product_id=1284".
So when the page changes due to the AJAX at the end of the "last"/"Continue-button function, either neither of the Checkbox 1 or Checkbox 2 actions have taken place, or one of the two or both do register in the backend (ie, added to cart) but do not reflect in the AJAXified DOM as they should as the final AJAX fires and completes before the previous $.post() calls have completed.
My Code
The HTML
The HTML is basic:
<form method="post" action="#" onsubmit="newChooseShippingProvider(); return false;">
<label for="delSigCheck" class="del-sig-text"><input id="delSigCheck" type="checkbox" onchange="addDelSigToCart();" title="Add Delivery Signature"></label>
<label for="addInsCheck" class="ins-add-calc"><input id="addInsCheck" type="checkbox" onchange="addInsToCart();" title="Add Delivery Signature" data-ins-id="1284"></label>
<input type="submit" value="Continue" class="btn Small">
</form>
The Javascript/jQuery
This is my latest--4th or 5th--attempt, and still does not work:
function addDelSigToCart() {
$('#delSigCheck').toggleClass('checked');
}
function addInsToCart() {
$('#addInsCheck').toggleClass('checked');
}
function newChooseShippingProvider() {
var originalCheckout = ExpressCheckout.ChooseShippingProvider();
if ($('.ShippingProviderList .radio span').hasClass('checked')) {
var addInsCheck = $('#addInsCheck').hasClass('checked');
var delSigCheck = $('#delSigCheck').hasClass('checked');
var insId = $('#addInsCheck').attr('data-ins-id');
var addDelSigUrl = '/cart.php?action=add&product_id=1280';
var addInsUrl = '/cart.php?action=add&product_id=' + insId;
if (delSigCheck && addInsCheck) {
$.post(addDelSigUrl, function() {
$.post(addInsUrl, function() {
originalCheckout;
});
});
} else if (!delSigCheck && !addInsCheck) {
originalCheckout;
} else if (delSigCheck && !addInsCheck) {
$.post(addDelSigUrl, function() {
originalCheckout;
});
} else if (!delSigCheck && addInsCheck) {
$.post(addInsUrl, function() {
originalCheckout;
});
}
} else {
originalCheckout;
}
What I've Tried
I've gone through several version of chaining the $.post() calls, but nothing seems to work consistently.
What I am using now and what seems to work the best for me with extensive testing is using setTimeout to chain the function with some delay, like this:
...
if (delSigCheck && addInsCheck) {
$.post(addDelSigUrl);
setTimeout(function() {
$.post(addInsUrl);
setTimeout(function() {
ExpressCheckout.ChooseShippingProvider();
}, 1300);
}, 1300);
} else if ...
And this version above is what I'm using now, as it seems to give the most consistent results, seeing the scripts load typically as 1,2,3, followed by a DOM AJAXified with appropriate changes based on function 1 and 2. However, I don't think the setTimeout is working as even when I increase it to 5000 or 10000, the action is performed "instantaneously" and no delay takes place (at least certainly nothing close to 5-10 seconds).
I've also tried putting the functions inside $.post()'s success callback:
...
if (delSigCheck && addInsCheck) {
$.post(addDelSigUrl, function() {
setTimeout(function() {
$.post(addInsUrl, function() {
setTimeout(function() {
originalCheckout;
}, 1300);
});
}, 1300);
});
} else if ...
And finally I've also tried:
$.when($.post(addDelSigUrl)).then(originalCheckout);
as well as .done and success: but none of it works, and the $.posts()'s load in an unexpected order, failing.
The Question
What am I doing wrong?
How can I make it so 1 loads fully, then 2 loads fully, and only then 3 fires and loads?
UPDATE 1:
I just tried jfriend00's answer:
$.post(addDelSigUrl, { cache: false }).then(function(data1) {
//CONSOLE.LOGing HERE
console.log(data1);
return $.post(addInsUrl, { cache: false });
}).then(function(data2) {
//CONSOLE.LOGing HERE
console.log(data2);
return originalCheckout;
});
But it still resulted in:
XHR finished loading: POST "/cart.php?action=add&product_id=1280".
XHR finished loading: POST "/remote.php".
XHR finished loading: POST "/cart.php?action=add&product_id=1284".
and both console.logs fire immediately after the first "XHR ...", THEN /remote.php fires (though it should fire last as part of originalCheckout), THEN the 3rd XHR fires.
UPDATE 2
Now that we got the XHRs firing and loading in the correct order via .then(), the second part of the problem I am having is that the 3rd XHR to /remote.php updates the DOM via AJAX with data from the backend. Part of that data is the 1st and 2nd $.posts.
I think the 3rd AJAX call is firing and completing milliseconds before some action is taken on the backend via server-side PHP, and because of this more than 50% of the time, the DOM update via the 3rd AJAX call is missing the data from the 1st and/or 2nd call (most often the DOM changes include Checkbox 1/AJAX call 1, but not 2).
How can I fix this? I've tried setTimeout but it doesn't seem to work as even when I set it to like 30000, the 3rd AJAX fires as soon as the 1st/2nd complete.
Latest front-end code:
function newChooseShippingProvider() {
if ($('.ShippingProviderList .radio span').hasClass('checked')) {
var addInsCheck = $('#addInsCheck').hasClass('checked');
var delSigCheck = $('#delSigCheck').hasClass('checked');
var insId = $('#addInsCheck').attr('data-ins-id');
var addDelSigUrl = '/cart.php?action=add&product_id=1280';
var addInsUrl = '/cart.php?action=add&product_id=' + insId;
if (delSigCheck && addInsCheck) {
$.post(addDelSigUrl).then(function(data1) {
return $.post(addInsUrl);
}).then(function(data2) {
return ExpressCheckout.ChooseShippingProvider();
});
} else if (!delSigCheck && !addInsCheck) {
ExpressCheckout.ChooseShippingProvider();
} else if (delSigCheck && !addInsCheck) {
$.post(addDelSigUrl).then(function(data1) {
return ExpressCheckout.ChooseShippingProvider();
});
} else if (!delSigCheck && addInsCheck) {
$.post(addInsUrl).then(function(data1) {
return ExpressCheckout.ChooseShippingProvider();
});
}
} else {
ExpressCheckout.ChooseShippingProvider();
}
}
The simplest way to sequence jQuery ajax operations is to use the built-in promises:
$.post(...).then(function(data1) {
return $.post(...);
}).then(function(data2) {
return $.post(...);
}).then(function(data3) {
// everything done here
});
Working demo that shows you the precise sequencing: http://jsfiddle.net/jfriend00/zcfr2xy0/
OK, it appears that the problem is that you're doing this:
var originalCheckout = ExpressCheckout.ChooseShippingProvider();
And, then you think that sometime later, you can just do:
originalCheckout;
and that will somehow execute the former. That's not the case. Your ExpressCheckout.ChooseShippingProvider() function is executed immediately and the return result from executing that function is assigned to originalCheckout.
You simply can't do it that way. When you have () after a function name, that means to execute it NOW. I would suggest that you just replace all instances of originalCheckout; with ExpressCheckout.ChooseShippingProvider();.
If you "chain" AJAX post operations (meaning that you do your process once receiving the data from the previous call) then nothing strange should happen.
From the symptom I'd think more to some cache-related problem. Adding an extra random value to the query is a quick'n dirty way to get rid of whoever is caching the result and responding instead of who should. Also using a POST request instead of a GET (if possible) may help on this issue and better conveys the idea that the operation is a mutation that should not be skipped or done out of order.
Note that a stale response problem could be at several levels: browser, proxy, web server, cms plugin...
I have write the following code into AJAX to change the tab.
$("a").click(function(event){
if ($.browser.msie != true && $.browser.version != 8.0){
event.preventDefault();
if ($(this).parent().hasClass("current") == false){
$.ajax({
url: '/getvideofeed',
success: function(data) {
$('.flow').html(data);
cf._init();
},
data: {'playlistid': $(this).attr("pid")}
});
$(".current").removeClass("current");
console.log($(this).parent().addClass("current"));
}}
});
when i changed the TAB. the cf._init(); function getting called more than one time... means when i clicked 1st tab it will be called twice. when i clicked to next tab again cf._init() function will be called thrice and so on.
so my problem is how to reset cf._init() function after ajax called has been finished ? or how to called cf._init() function only once each time when i clicked any of the tab .
The function cf._init() should be executed on Ajax success
if cf._init() called more than once, than probably the Ajax is being performed more than once.
For start I suggest putting async property as follows:
async: false
so Ajax call will wait until it is finished.
This way will enable you to debug how come Ajax call is made more than once.
First make sure cf._init() is not calling ajax again ... 2nd why not call init when ajax is done or complete :
var request = $.ajax({"url":url});
request.done( function(data){ } );
I'm uploading a file in an iframe (with name and id=upload_target) to some server. As a response it creates a callback json style :
'result':'true'
So I'm trying the following. On onload action of my IFrame I've added an event listener, which should run function grabbing data :
function fileUploadFunction(){
(...)
$("#upload_target").onload = uploadDone;
(...)
};
function uploadDone() {
alert("uploadDone");
var ret = frames['upload_target'].document.getElementsByTagName("body")[0].innerHTML;
var data = eval("("+ret+")");
if(data.result == 'true') {
alert("GREAT SUCCESS !!");
}
else {
alert("GREAT FAILURE :(");
}
}
But as a result I'm not getting anything at all. Should I return callback status in different form, or can it be solved differently ? Because even the first alert from uploadDone is not shown problem probably lies somewhere else.
Probably the reason nothing is happening is because of the funky way you have to detect an iFrame is loaded. Check the post jQuery .ready in a dynamically inserted iframe. I am assuming you are using jQuery.