How to unblock a blocked page with jquery-blockui? - javascript

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

Related

jQuery AJAX call initiates without command when .done function added

I'm rewriting a series of jQuery AJAX requests and have been having trouble with .done code blocks. I'm attempting to send an AJAX request and wait for the response before processing the data. As a guide, I have been using the following page:
http://michaelsoriano.com/working-with-jquerys-ajax-promises-and-deferred-objects/
I've also looked at countless stack questions to try and troubleshoot my issues, but haven't found anything which has helped. For reference, some of the questions I've looked at are below:
jQuery Ajax call not processing .done
jquery ajax done function not firing
Confused on jquery .ajax .done() function
I've noticed that when I create code blocks which are similar to the guide above, the functions run on page load, rather than when they are triggered in code. To isolate the fault, I created a simple example, as below:
<!DOCTYPE html>
<html lang="en">
<body>
<button type="button" onclick="getData()">Click me</button>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
//Commented out due comment below
/*function getData() {
console.log('enter getData');
return $.ajax({url:'./testajax.html',type:"POST"});
}
getData().done(function(data){
console.log('enter done');
alert(data);
});*/
function getData() {
console.log('enter getData');
$.ajax({ url: './testajax.html', type: "POST" })
.done(function (data) {
console.log('enter done');
alert(data);
});
alert('after');
}
</script>
</html>
I was expecting that when my example page loaded, nothing would happen, as there was no trigger to execute the getData() function unless the button was clicked. However, when I load the page, my console logs 'enter getData' and then 'enter done', and I get an alert with the contents of my ./testajax.html page (just a single string). Further, when I then click the button, it enters getData() but doesn't trigger the getData().done function, so no alert is received.
Is anyone able to guide me on the right track here and help me prevent the getData() function from executing on page load, and instead make the button click execute the AJAX request, wait for the result, then execute the code in the .done block?
The getData() expression you have immediately calls the function on pageload. Then you attach a .done handler to it.
It sounds like you want a function that calls $.ajax and attaches .done to it, like:
function getData() {
console.log('enter getData');
$.ajax({ url: './testajax.html', type: "POST" })
.done(function (data) {
console.log('enter done');
alert(data);
});
}
Then attach getData as an event handler somewhere.
Don't use inline handlers. Use .addEventListener or jQuery's .on('click' instead.

JavaScript: Check if window.location.href has been changed

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

How to execute JS function after successfull ajax call?

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

Ajax not working? Using jQuery to grab a link, send via AJAX

I can add a product to my cart with this link:
<div id="add"><a id="add-link" href="http://example.com/cart/?add-to-cart=1127">Add to Cart</a>
I have tried to use both GET or POST when it reaches line 7 but I am not getting an alert that the product was added even though it retrieves the correct url in line 6. Can someone tell me what is wrong? Help would be great!
<script type="text/javascript">
$(document).ready(function(){
$('a#add-link').click(function(event) {
event.preventDefault();
var url = $(this).attr("href");
alert("Now I want to call this page: " + url);
$.post(url, function () {
alert("Product added to cart");
});
});
});
</script>
You didn't make it clear from your post where the request was being directed -- that is, whether you're requesting a resource on your domain or outside of your domain -- but this is a common symptom of a Cross Origin Resource Sharing (CORS) restriction.
If you're URL variable references a domain other than your own, you can bet this is the direction to pursue. You could test it by putting in a link that references a local resource, and giving that a try (it should work)
So, in your script block, you can declare the handlers and the functions:
$(document).ready(myMethod);
$(myButton).click(otherMethod);
function myMethod()
{
//do some work
//you can trigger another event in here
$(myButton).click()
}
function otherMethod()
{
//more work
}
Now, when the document signals that it is ready, it will run myMethod(), which fakes a click on the myButton element, which has an event handler called otherMethod(). So, just by the document saying "Ready!" it will kick off both events and it will do it more quickly than having the functions declared inline. Inline, JS has to recompile the function every time the event is hit. Separating the functions out causes them to only be compiled once, when the JS is loaded.
This will fire an event any time your "Add to Product" link is clicked:
$('#add-link').click(addToCart);
function addToCart() //you can optionally get an event parameter in here as well
{
event.preventDefault();
var url = $(this).attr("href");
alert("Now I want to call this page: " + url);
$.post(url, function ()
{
alert("Product added to cart");
//I'm not 100% on this, I don't use the jQuery .post method
});
}

WCF Service methods + Synchronous calls from javascript

I have written a WCF service and am trying to call the service methods in a script in my ASPX page.
Eg:
<script language="javascript" type="text/javascript">
<!--
function Test() {
**// The following call is an Async call.
tempuri.org.IService.GetData(1,OnRequestComplete, OnError, "");**
}
function OnRequestComplete(result, state) {
var textBox = $get("txtInput");
textBox.value = result;
}
function OnError(result) {
var textBox = $get("txtInput");
textBox.value = result;
}
//-->
</script>
What I want is to be able to call the service method "synchronously"
eg: var result = tempuri.org.IService.GetData(1);
Is this possible?
I believe there's no ability to do synchronous calls in Javascript - the AJAX libraries will always return while waiting for a remote response.
Can you explain why you want to do this?
Edit:
In answer, you should use this method:
In the onclick event handler for your form submit button: Make the webservice validation call, and immediately return false (so the form does not submit). It would be a good idea to display to the user a 'Validating' type message, so they know what is happening here.
If you get a valid response, then use document.form.submit(); to submit the form to the server.
If you get an invalid response, or a server error, then display to the user a message to that effect.
If you use regular AJAX you can make your call synchronous.
See: http://www.w3schools.com/Ajax/ajax_xmlhttprequest_send.asp
and scroll down to the part "Asynchronous - True or False?"
Here I use AJAX but sometimes it hangs
www.DomainGuarder.com

Categories

Resources