$.blockUI jQuery plugin blocks back button android / phonegap - javascript

I am using the blockUI jQuery plugin for an AJAX call:
//start the plugin
App.utilities.Loading();
$.ajax(url, {
type: "POST",
contentType: 'application/json',
data: JSON.stringify({
"textcontent": content
}),
success: function (data) {
$.mobile.navigate('discussion.html');
$.unblockUI();
}
});
Sometimes the loading takes more than three seconds and if the user is pressing the back button, the back event get triggered after calling $.unblockUI(); Is there a way to go back during the plugin is ON and cancel the Ajax call?
I can get the status of the block UI:
var isUIBlocked = $('.ui-widget-overlay:visible').length > 0;
any ideas?

you can try the following code
//start the plugin
App.utilities.Loading();
//assign the ajax call to a xhr object
var xhr = $.ajax(url, {
type: "POST",
contentType: 'application/json',
data: JSON.stringify({
"textcontent": content
}),
success: function (data) {
$.mobile.navigate('discussion.html');
$.unblockUI();
}
});
//when back button is being clicked
window.onbeforeunload = function (e) {
xhr.abort(); //abort the above ajax call
var isUIBlocked = $('.ui-widget-overlay:visible').length > 0;
if(isUIBlocked) {
$.unblockUI();
}
}
further reading for the jqXHR object of the jquery.ajax function : http://api.jquery.com/jQuery.ajax/#jqXHR

Related

JQuery form submit not calling success

After click on submit beforeSend: works but it does not call success: also there is no console error . The data also submit to database correctly ! Then why it not call the success: . Please Help
$(function() {
//hang on event of form with id=ticketForm
$("#ticketForm").submit(function(e) {
//prevent Default functionality
e.preventDefault();
//get the action-url of the form
var actionurl = e.currentTarget.action;
var form = $('#ticketForm');
var submit = $('#submite');
$.ajax({
url: actionurl,
type: "POST",
data: $("#ticketForm").serialize(),
dataType: "json",
contentType: 'application/json; charset=utf-8',
cache: false,
beforeSend: function(e) {
submit.html("Booking....");
},
success: function(e) {
submit.html("Booking Completed !");
//get the message from booking.php and show it.
$(".alert").removeClass("hide");
var msg = $.ajax({
type: "GET",
url: actionurl,
async: false
}).responseText;
document.getElementById("success-message").innerHTML = msg;
setTimeout(function() { // wait for 3 secs(2)
location.reload(); // then reload the page.(3)
}, 3000);
},
error: function(e) {
console.log(e)
}
});
});
});
Console Message
Object {readyState: 4, responseText: "<strong>Seat Booked Successfully</strong>", status: 200, statusText: "OK"}
In a Ajax call 'dataType' attributes means what data format can be expect from client(browser). As per error message server is returning 'string' instead 'json'.
But on the other hand, given ajax call is expecting json data to be returned by backend server. Either provide a
valid JSON in response or change datatype to html.
In your AJAX call settings you set dataType to json, but in return you provide a string.
dataType (default: Intelligent Guess (xml, json, script, or html)) The
type of data that you're expecting back from the server. If none is
specified, jQuery will try to infer it based on the MIME type of the
response
So, you have two solutions:
Provide a valid JSON in response
Do not ask for JSON by changing your dataType value (to html), or by removing it.
I had similar problem. As you are redirecting page in success you need to use
e.preventDefault(); // to prevent page refresh
after the ajax call or
return false; // to prevent page refresh
Something like this :
$(function() {
//hang on event of form with id=ticketForm
$("#ticketForm").submit(function(e) {
//prevent Default functionality
e.preventDefault();
//get the action-url of the form
var actionurl = e.currentTarget.action;
var form = $('#ticketForm');
var submit = $('#submite');
$.ajax({
url: actionurl,
type: "POST",
data: $("#ticketForm").serialize(),
dataType: "json",
contentType: 'application/json; charset=utf-8',
cache: false,
beforeSend: function(e) {
submit.html("Booking....");
},
success: function(e) {
submit.html("Booking Completed !");
//get the message from booking.php and show it.
$( ".alert" ).removeClass( "hide" );
var msg = $.ajax({type: "GET", url: actionurl, async: false}).responseText;
document.getElementById("success-message").innerHTML = msg;
setTimeout(function(){// wait for 3 secs(2)
location.reload(); // then reload the page.(3)
}, 3000);
},
error: function(e) {
console.log(e)
}
});
return false; e.preventDefault(); //any one of this options to prevent page refresh after ajax call
});
});

How to stop AJAX making multiple calls?

I'm using the jquery countdown timer plugin (http://keith-wood.name/countdown.html) to display the time. I'm calling a function to add more time on callback event 'onTick'. When the time countdowns to 00:00:00, the function will make an ajax call to add extra time. It's working fine but every time the timer equals 00, ajax is making multiple calls (>15). How can I make it to send just one call? I tried doing async: false but still it's making multiple calls. Thank you.
$(this).countdown({ until: time, format: 'HMS', onTick: addExtraTime });
function addExtraTime() {
if ($.countdown.periodsToSeconds(periods) === 00) {
var postValue = { ID: id }
if (!ajaxLoading) {
ajaxLoading = true;
$.ajax({
url: "#Url.Action("AddExtraTime", "Home")",
type: 'post',
dataType: 'json',
contentType: "application/json",
data: JSON.stringify(postValue),
success: function() {
// show success
},
error: function(data) {
// show error
}
});
ajaxLoading = false;
}
}
}
You have a variable, ajaxLoading, that you use to determine if an Ajax request is in flight but you set it to false immediately after calling $.ajax() instead of when you get a response. Set it to false inside your success and error handlers instead.
You're setting ajaxLoading = false; even when the ajax request is still being done, set it to false after the request is completed
if (!ajaxLoading) {
ajaxLoading = true;
$.ajax({
url: "#Url.Action("AddExtraTime", "Home")",
type: 'post',
dataType: 'json',
contentType: "application/json",
data: JSON.stringify(postValue),
success: function() {
// show success
},
error: function(data) {
// show error
}
complete: function(){
ajaxLoading = false;
}
});
//ajaxLoading = false;
}

trigger a javascript function before on any AJAX call

Here, I have a function which needs to be called before any AJAX call present in the .NET project.
Currently, I have to call checkConnection on every button click which is going to invoke AJAX method, if net connection is there, proceeds to actual AJAX call!
Anyhow, I want to avoid this way and the checkConnection function should be called automatically before any AJAX call on the form.
In short, I want to make function behave like an event which will be triggered before any AJAX call
Adding sample, which makes AJAX call on button click; Of course, after checking internet availability...
//check internet availability
function checkConnection() {
//stuff here to check internet then, set return value in the variable
return Retval;
}
//Ajax call
function SaveData() {
var YearData = {
"holiday_date": D.getElementById('txtYears').value
};
$.ajax({
type: "POST",
url: 'Service1.svc/SaveYears',
data: JSON.stringify(YearData),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (data, status, jqXHR) {
//fill page data from DB
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
And below is current way to call function:
<form onsubmit="return Save();">
<input type="text" id="txtYears" /><br />
<input type="submit" id="btnSave" onclick="return checkConnection();" value="Save" />
<script>
function Save() {
if (confirm('Are you sure?')) {
SaveData();
}
else {
return false;
}
}
</script>
</form>
You cannot implicitly call a function without actually writing a call even once(!) in JavaScript.
So, better to call it in actual AJAX and for that you can use beforeSend property of ajaxRequest like following, hence there will be no need to call checkConnection() seperately:
$.ajax({
type: "POST",
url: 'Service1.svc/SaveYears',
data: JSON.stringify(YearData),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
beforeSend: function() {
if(!checkConnection())
return false;
},
success: function (data, status, jqXHR) {
//fill page data from DB
},
error: function (xhr) {
alert(xhr.responseText);
}
});
It reduces the call that you have made onsubmit() of form tag!
UPDATE:
to register a global function before every AJAX request use:
$(document).ajaxSend(function() {
if(!checkConnection())
return false;
});
The best way is to use a publish-subsribe pattern to add any extra functions to be called on pre-determined times (either before or after ajax for example).
jQuery already supports custom publish-subsrcibe
For this specific example just do this:
//Ajax call
function SaveData(element) {
var doAjax = true;
var YearData = {
"holiday_date": D.getElementById('txtYears').value
};
if (element === myForm)
{
doAjax = checkConnection();
}
if ( doAjax )
{
$.ajax({
type: "POST",
url: 'Service1.svc/SaveYears',
data: JSON.stringify(YearData),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (data, status, jqXHR) {
//fill page data from DB
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
else
{
// display a message
}
}
Hope i understand correctly what you mean.
UPDATE:
in the if you can do an additional check if the function is called from the form or a field (for example add an argument SaveData(element))
If you use the saveData in html, do this: "saveData(this)", maybe you should post your html as well
You can use:
$(document)
.ajaxStart(function () {
alert("ajax start");
})
.ajaxComplete(function () {
alert("ajax complete");
})
That's it!!
use
beforeSend: function () {
},
ajax method

Stop Ajax Request And Call New Ajax

in this code, i take typing character from user and search it in database,but when user enter each character,running new ajax request with previous ajax,
i want when call search function, cancel previous ajax request and run new ajax request;
html code :
<input type="text" onkeyup="search()">
js code:
function search () {
var request=$.ajax({
type: "POST",
url: "php/h.php",
data: {k_word:k_word},
dataType: "json",
success: function (data) {
ghtml(data)
}
})
}
Also i tried with abrot() like this :
var request;
function search () {
request.abort();
request=$.ajax({
type: "POST",
url: "php/h.php",
data: {k_word:k_word},
dataType: "json",
success: function (data) {
ghtml(data)
}
})
}
but not working
That's generally not how it's done, instead throttling is used to only call the ajax function when the user stops typing for a given time
First of all, get rid of the inline javascript
<input type="text" id="myInput" />
then use an event handler
$('#myInput').on('keyup', function() {
clearTimeout( $(this).data('timer') );
$(this).data('timer',
setTimeout(function() {
$.ajax({
type : "POST",
url : "php/h.php",
data : {k_word:k_word},
dataType : "json",
success : function (data) {
ghtml(data)
}
});
}, 500)
);
});
This sets a timeout on the ajax call, and that timeout is cleared if a new key is pressed within half a second, so the ajax call is only made when the user stops typing for more than 500 milliseconds

passing callback function accross windows causing error with ie

I have a problem with IE causing two errors:
1. Object doesn't support this property or method
2. Call was rejected by callee.
My Intention:
To call window.opener.myObject method that is going to retrieve some data using ajax and pass in callback function
that live as nested function in popup window that initiated call that is going to handle response data and modify popup window html accordingly.
Here is a scenario:
I pull up popup window that handles some specific operation.
This popup window calling window.opener.myObject method that using ajax call.
I'm passing in popup window function that is going to handle response and it works with ff and safari but not with ie.
Here is code sample
//RELEVANT SCRIPT ON POPUP WINDOW
$('#myButton').live('click', function() {
var h = window.opener.myObject, p = { 'p1': 1 };
var responseHandler = function(responseObj) {
//in IE we never got here
if (!responseObj) {
alert('Unexpected error!! No response from server');
return false;
}
//..handle response
};
p.p1 = $('#control').val();
h.executeMethod(p, responseHandler);
});
//RELEVANT SCRIPT ON WINDOW OPENER MYOBJECT
try {
$.ajax({
type: 'POST',
async: true,
url: url,
data: postData,
dataType: "json",
contentType: 'application/x-www-form-urlencoded; charset=utf-8',
success: r, // r here is reference to my responseHandler popup window function
error: handleError
});
} catch (ex) {
alert(ex.message);
}
Any tips?
I have made it work, not sure if that is the right way or not but now it works.
I've modified window opener myobject code from :
//RELEVANT SCRIPT ON WINDOW OPENER MYOBJECT
try {
$.ajax({
type: 'POST',
async: true,
url: url,
data: postData,
dataType: "json",
contentType: 'application/x-www-form-urlencoded; charset=utf-8',
success: r, // r here is reference to my responseHandler popup window function**
error: handleError
});
} catch (ex) {
alert(ex.message);
}
to:
//RELEVANT SCRIPT ON WINDOW OPENER MYOBJECT
try {
$.ajax({
type: 'POST',
async: true,
url: url,
data: postData,
dataType: "json",
contentType: 'application/x-www-form-urlencoded; charset=utf-8',
success: function(myResponseObj) {
r.call(null, myResponseObj);
}
error: handleError
});
} catch (ex) {
alert(ex.message);
}
so success jquery ajax handler was modified to :
success: function(myResponseObj) {
r.call(null, myResponseObj);
}
and it works now :-) ...

Categories

Resources