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;
}
Related
$.ajax({
url: vars.url,
type: "post",
data: r,
async: true,
processData: vars.process,
contentType: vars.contenttype,
beforeSend: function(){
if(vars.loadbar == 'true'){
setInterval(function () {
$.getJSON(domain + '/core/files/results.json', function (data) {
console.log(data);
})
}, 1000);
}
},
complete: function(){
clearInterval();
},
succes: function(data){
..................
}
})
So I am trying to end the infinite loop my code is spawning as soon as my ajax call is being done. It now phones pretty much every second to my file to get results, which i want to stop as soon as my ajax call is completed.
I am not sure how to approach this, since if i assign a variable to the setInterval (being it in the function of the beforeSend itself, or outside of the AJAX call), it either wont see the variable, or my variable is empty. I think I am approaching this wrong. Can I check within the beforeSend if the AJAX call is complete to end the loop?
you can store your interval as a global variable and clear it when you need it. like so:
let interval;
$.ajax({
url: vars.url,
type: "post",
data: r,
async: true,
processData: vars.process,
contentType: vars.contenttype,
beforeSend: function(){
if(vars.loadbar == 'true'){
interval = setInterval(function () {
$.getJSON(domain + '/core/files/results.json', function (data) {
console.log(data);
})
}, 1000);
}
},
complete: function(){
clearInterval(interval);
},
succes: function(data){
..................
}
}
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
});
});
I have a difficulty to know when all Ajax requests are completed because I need this information to call another function.
Difficulty are to know when my 4/5 function with requests are completed. I use native function of ajax and none is working for me.
I used Chrome, and async requests.
Someone Helps me
I use this(not work):
$(document).ajaxStop(function() {
alert("Completed");
});
and this (not Work):
$(document).ajaxComplete(function() { alert("Completed"); });
Both ways I try use in another function thal calls all requests:
Example:
function Init()
{ Search("123"); Search2("1234"); Search3("12345");
... }
Extract one (of 5 requests,others are very similar ) of my request:
function Search(user) {
$.ajax({
url: 'www.example.com/' + user,
type: 'GET',
async: true,
dataType: 'JSONP',
success: function(response, textStatus, jqXHR) {
try {
if (response != null) {
alert("Have Data");
} else {
alert("are empty");
}
} catch (err) {
alert("error");
}
},
error: function() {
alert("error");
}
}); }
have you tried putting it in a done function? something like...
$.ajax({
url: 'www.example.com/' + user,
type: 'GET',
async: true,
dataType: 'JSONP'
}).done(function (data) {
code to execute when request is finished;
}).fail(function () {
code to do in event of failure
});
bouncing off what Michael Seltenreich said, his solution, if i understand where you guys are going with this...might look something like:
var count = 0;
function checkCount(){
if(count == 5 ){
//do this, or fire some other function
}
}
#request one
$.ajax({
url: 'www.example.com/' + user,
type: 'GET',
async: true,
dataType: 'JSONP',
}).done( function(data){
count += 1
checkCount()
})
#request two
$.ajax({
url: 'www.example.com/' + user,
type: 'GET',
async: true,
dataType: 'JSONP',
}).done( function(data){
count += 1
checkCount()
})
and do it with your five requests. If that works out for you please make sure to mark his question as the answer;)
You can create a custom trigger
$(document).trigger('ajaxDone')
and call it when ever you finished your ajax requests.
Then you can listen for it
$(document).on('ajaxDone', function () {
//Do something
})
If you want to keep track of multiple ajax calls you can set a function that counts how many "done" values were passed to it, and once all are finished, you can fire the event.
Place the call for this function in each of the 'success' and 'error' events of the ajax calls.
Update:
You can create a function like so
var completedRequests= 0
function countAjax() {
completedRequests+=1
if(completedRequests==whatEverNumberOfRequestsYouNeed) {
$(document).trigger('ajaxDone');
}
}
Call this function on every success and error events.
Then, ajaxDone event will be triggered only after a certain number of requests.
If you wanna track specific ajax requests you can add a variable to countAjax that checks which ajax completed.
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
I have a problem with multiple ajax functions where the beforeSend of the second ajax post is executed before the complete function of the first ajax.
The loading class I am adding to the placeholder before sending is working for the first ajax call. However soon after the first ajax request completes the class is removed and never appends again on the second and further calls (remember recursive calls).
While debugging it shows that the beforeSend function of the second ajax call is called first and the complete function of the first ajax call is called later. Which is obvious, because the return data inserted in the page from the first ajax call starts the second call.
In short it's mixed up. Is there any way this can be sorted out?
The function code is as follows
function AjaxSendForm(url, placeholder, form, append) {
var data = $(form).serialize();
append = (append === undefined ? false : true); // whatever, it will evaluate to true or false only
$.ajax({
type: 'POST',
url: url,
data: data,
beforeSend: function() {
// setting a timeout
$(placeholder).addClass('loading');
},
success: function(data) {
if (append) {
$(placeholder).append(data);
} else {
$(placeholder).html(data);
}
},
error: function(xhr) { // if error occured
alert("Error occured.please try again");
$(placeholder).append(xhr.statusText + xhr.responseText);
$(placeholder).removeClass('loading');
},
complete: function() {
$(placeholder).removeClass('loading');
},
dataType: 'html'
});
}
And the data contains the following snippet of javascript/jquery which checks and starts another ajax request.
<script type="text/javascript">//<!--
$(document).ready(function() {
$('#restart').val(-1)
$('#ajaxSubmit').click();
});
//--></script>
Maybe you can try the following :
var i = 0;
function AjaxSendForm(url, placeholder, form, append) {
var data = $(form).serialize();
append = (append === undefined ? false : true); // whatever, it will evaluate to true or false only
$.ajax({
type: 'POST',
url: url,
data: data,
beforeSend: function() {
// setting a timeout
$(placeholder).addClass('loading');
i++;
},
success: function(data) {
if (append) {
$(placeholder).append(data);
} else {
$(placeholder).html(data);
}
},
error: function(xhr) { // if error occured
alert("Error occured.please try again");
$(placeholder).append(xhr.statusText + xhr.responseText);
$(placeholder).removeClass('loading');
},
complete: function() {
i--;
if (i <= 0) {
$(placeholder).removeClass('loading');
}
},
dataType: 'html'
});
}
This way, if the beforeSend statement is called before the complete statement i will be greater than 0 so it will not remove the class. Then only the last call will be able to remove it.
I cannot test it, let me know if it works or not.
It's actually much easier with jQuery's promise API:
$.ajax(
type: "GET",
url: requestURL,
).then((success) =>
console.dir(success)
).failure((failureResponse) =>
console.dir(failureResponse)
)
Alternatively, you can pass in of bind functions to each result callback; the order of parameters is: (success, failure). So long as you specify a function with at least 1 parameter, you get access to the response. So, for example, if you wanted to check the response text, you could simply do:
$.ajax(
type: "GET",
url: #get("url") + "logout",
beforeSend: (xhr) -> xhr.setRequestHeader("token", currentToken)
).failure((response) -> console.log "Request was unauthorized" if response.status is 401