Set timeout on AJAX without $.ajax() - javascript

I want to set timeout after 2 seconds loading data. I am new in ajax so please clarify through my code...because i have already see many (set time out on ajax) answer but every one do through $.ajax().
how I can do through .load() ? It is possible or not ?
My AJAX code 1:
// Start of our new ajax code
if (!url) {
url = jQuery('#product_addtocart_form').attr('action');
}
url = url.replace("checkout/cart","ajax/index"); // New Code
var data = jQuery('#product_addtocart_form').serialize();
data += '&isAjax=1';
jQuery('#ajax_loader').show();
try {
jQuery.ajax( {
url : url,
dataType : 'json',
type : 'post',
data : data,
success : function(data) {
jQuery('#ajax_loader').hide();
parent.setAjaxData(data,true);
}
});
jQuery("#productOptions").modal('hide');
} catch (e) {
//alert(e);
}
// End of our new ajax code
2:
// AJAX product options modal
$('.optionsTrigger').on('click', function() {
var target, url;
target = $(this).attr('data-target');
url = $(this).attr('href');
$(target).load(url, function(){
$(target).modal({
show: true
});
});
});
$('#productOptions').on('hidden', function() {
$('#productOptions').html('<img src="<?php echo $this->getSkinUrl("img/loading.gif"); ?>" id="optionsLoading" />');
window.setTimeout("Tick()", 2000);
function Tick()
{
}
});

jQuery has the ajaxSetup() method available. You can set all options to the normal ajax() method there, including the timeout option. The settings set there should also be available when you call your AJAX request via load().

First, wrap your head around the fact that Ajax is asynchronous (like setTimeout) - the callbacks are called somewhen in the future.
How to timeout? You could use
var request = jQuery.ajax(…);
setTimeout(function() {
request.abort();
}, 2000);
request.done(function callback(){ … });
But it's much simpler than that, jQuery already has a timeout parameter for it's ajax() option object.
However, this is not possible using load - here not the jqXHR object is returned, but the current jQuery DOM-selection. Either, you have to globally configure ajax, or you don't use load and build the method yourself - it's not that hard, see source

Related

How to call this function automatically

Im using the following function to call an ajax request, and fill certain corresponding divs with the response:
$( function() {
$(document).ready(function() {
var postData = "";
$.ajax( {
url : \'functions/ajax_api.php?\',
type : \'post\',
data : postData,
success : function( resp ) {
$(\'#id1\').html($(\'#id1\' , resp).html());
$(\'#id2\').html($(\'#id2\' , resp).html());
}
});
return false;
});
});
The function works fine. My question is how can I call it automatically every few seconds?
I tried using window.setTimeout(function, 3000) but I couldnt set it up correctly.
use setInterval(); instead of .setTimeout()
Let me help you a little bit with that
var interval , setItinterval; // just a variables you can change names
interval = function(){
// ajax code here
}
to run it .. use:
setItinterval = setInterval(interval , 3000);
to stop it .. use
clearInterval(setItinterval);
Make sure to read setInterval for more information.
For Complete answer and Last thing I want to say when using setInterval(); Its better to use visibilitychange to avoid server error , server load or something like that
document.addEventListener('visibilitychange',function(){
if(document.visibilityState == 'visible'){
// user view the page
}else{
// user not see the page
}
});
You can use setTimeout() or setInterval, but setInterval may result in multiple simultaneous ajax calls if those calls take too long to respond. That isn't a problem if you call setTimeout() in the ajax success callback.
To use setTimeout(), first wrap your ajax call in a function. You can then add a call to setTimeout() to the ajax success callback. You also need to call the function once to start of the looping.
$(function() {
function postData() {
var postData = "";
$.ajax({
url: 'functions/ajax_api.php?',
type: 'post',
data: postData,
success: function(resp) {
$('#id1').html($('#id1', resp).html());
$('#id2').html($('#id2', resp).html());
// Call postData again after 5 seconds.
setTimeout(function() { postData(); }, 5000);
}
});
}
// Call postDate the first time to start it off.
postData();
});
Note: With the call to setTimeout in the success callback, the cycle will break if an ajax call fails. You may want that, but if you want it to act more like setInterval, you can place the call to setTimeout in the complete callback.
Here's some example code that will do it (note that it runs the function when the document loads, and then starts the interval). You can always use clearInterval(refresh_interval) if you need to stop it.
var refresh_interval;
function update_content() {
$.ajax({
url : \'functions/ajax_api.php?\',
type : \'post\',
data : postData,
success : function( resp ) {
$(\'#id1\').html($(\'#id1\' , resp).html());
$(\'#id2\').html($(\'#id2\' , resp).html());
}
});
}
$(document).ready(function() {
update_content();
setInterval(update_content, 3000);
}
The relevant documentation for using intervals is here: https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval
Though you may want to look into Server Sent Events, it's probably a better solution for what you want.

Ajax wont call when output from another ajax

I have comment system using live ajax php, and also include for vote system on that comment
Logic: when i post new comment, system will call ajax function with method post, and display response in above of textarea for comment, that response is include vote system (a class="with_unique_id"), but when i click that vote, it wont calling ajax function (nothing happend in browser console), whereas in current comment that displaying in above of new comment, it working fine.
This is my ajax code for vote
jQuery(document).ready(function($){
$(".voteMe").click(function() {
var voteId = this.id;
var upOrDown = voteId.split('_');
$.ajax({
type: "post",
url: "<?php echo base_url('blog/likepost');?>/"+upOrDown[0],
cache: false,
data:'voteId='+upOrDown[0] + '&upOrDown=' +upOrDown[1],
success: function(response){
try{
if(response=='true'){
var newValue = parseInt($("#"+voteId+'_result').text()) + 1;
$("#"+voteId+'_result').html(newValue);
document.getElementById('likeStatus_'+upOrDown[0]).innerHTML = 'Success';
$("#likeStatus_"+upOrDown[0]).show();
setTimeout(function() { $("#likeStatus_"+upOrDown[0]).hide(); }, 5000);
}else{
$("#likeStatus_"+upOrDown[0]).show();
document.getElementById('likeStatus_'+upOrDown[0]).innerHTML = 'Liked';
setTimeout(function() { $("#likeStatus_"+upOrDown[0]).hide(); }, 5000);
}
}catch(err) {
alert(err.message);
}
},
error: function(){
alert('Error while request..');
}
});
});
});
It took me a while to read your code, but I guess this is the root cause:
if(response=='true'){
var newValue = parseInt($("#"+voteId+'_result').text()) + 1;
$("#"+voteId+'_result').html(newValue);
document.getElementById('likeStatus_'+upOrDown[0]).innerHTML = 'Success';
$("#likeStatus_"+upOrDown[0]).show();
setTimeout(function() { $("#likeStatus_"+upOrDown[0]).hide(); }, 5000);
}
This line here:
$("#"+voteId+'_result').html(newValue);
That become the link you want to click again. Right?
If that is so, then you need to re-assign the event handler.
By replacing the DOM element, you have also removed the assigned event handler
PS: You code is very hard to read. It will be nightmare for you to maintain it.
i have fixed my code with adding same ajax code function in response of current ajax with different id.
thankyou

Ajax callback appending desired url to existing url

I am trying to make a ajax call back to a Drupal 7. The problem I am encountering is that the url I want to use to make the callback is appended to the current page the user is viewing. I am not sure why this is happening and am wondering if some can point out my error for me. Here is the javascript code I am using to make the call:
(function($) {
function todaysHours(context) {
var callbackFunction = window.location.host +'/' + Drupal.settings.library_hours.callbackFunction,
content = $("#todays-hours").find(".block");
nIntervId = setInterval(checkTime, 300000);
function checkTime() {
request = $.ajax({
url: callbackFunction,
dataType: "json",
type: "GET"
});
request.done(function( result ) {
content.text(result[0].data);
})
}
}
Drupal.behaviors.library_hours = {
attach: function(context) {
todaysHours(context);
}
}
})(jQuery);
The url I expect to use is http://mydomain.com/ajax/get-time but what is actually being used in the ajax call is http://mydomain.com/current-page/mydomain.com/ajax/get-time even though the callbackfunction variable is set to mydomain.com/ajax/get-time.
Why is this happening and how do I fix it? Thanks.
Problem:
Protocol is not defined in the url
Solution:
update the following part in the code
(function($) {
function todaysHours(context) {
var callbackFunction = '//'+window.location.host +'/' + Drupal.settings.library_hours.callbackFunction,
// rest code
})(jQuery);

jQuery $.get returns white error page when handling errors

The following code gives me an error like this when I request a page and it comes back 404. Instead it should bring up an alert. What is strange is it only does this on links that have been ajaxed in, on links that don't update/change it works fine.
('.page-wrap').append('<img src="img/graphics/ajax-loader.gif" class="ajax-loader" />');
var target = $('section.content'),
siteURL = 'http://' + top.location.host.toString(),
internalLinks = $("a[href^='"+siteURL+"'], a[href^='/'], a[href^='./'], a[href^='../'], a[href^='#']"),
links = $('a'),
URL,
el,
mainContent,
headContent,
headClasses,
pageName,
ajaxSpinner = $('.ajax-loader');
internalLinks.click(function(e) {
el = $(this);
URL = el.attr('href');
$('.current_page_item').removeClass('current_page_item');
el.addClass("current_link").parent().addClass("current_page_item");
ajaxLoader(URL, false);
e.preventDefault();
});
function ajaxLoader(location, isHistory) {
$("html, body").animate({ scrollTop: "0px" });
ajaxSpinner.show();
$('.page-wrap').css('opacity', '0.5}');
// Load New Page
$.get(location, function(data) {
mainContent = $('section.content', data).html();
headContent = $('.feature-content', data).html();
pageName = $('.page-name', data).html();
headClasses = $('header', data).attr('class');
$('section.content').html(mainContent);
$('.page-name').html(pageName);
$('.feature-content').html(headContent);
if (headClasses) {
$('header').attr('class', headClasses);
} else {
$('header').removeClass();
}
if (!isHistory) {
history.pushState(location, '', location);
}
$(resizeHeader);
ajaxSpinner.fadeOut();
}).error(function() {
alert('woops'); // or whatever
});
}
w.bind('popstate', function(event) {
if (event.originalEvent.state !== null ) {
ajaxLoader(event.originalEvent.state, true);
}
});
First thoughts
Is it perhaps the case that something in your success handler code is causing an error of some kind? Like maybe the injection of whatever html that comes back the first successful time is causing the script to fail a second time?
What do you see playing out in your your Fiddler/Firebug/F12 developer tool of choice - you are using one of these, right? :) Keep an eye on any console errors...
Second thought
What jQuery version are you using?
I have tested this with jq 1.8.2 and the error handler works just fine for me, but if this is a JSONP request it won't trigger the error() function. I took the gist of your code:
$.get(
"404MeBaby.html", function (data) {
$(".result").html(data);
console.log(data);
}
).error(
function (x) {
console.log("well that didn't go so well...");
});
From the API:
As of jQuery 1.5, the success callback function is also passed a
"jqXHR" object (in jQuery 1.4, it was passed the XMLHttpRequest
object). However, since JSONP and cross-domain GET requests do not use
XHR, in those cases the jqXHR and textStatus parameters passed to the
success callback are undefined.
You could try using $.ajax instead as it gives a lot more control. Or, you can set the jQuery global ajax options as shown here that will affect all $.get calls, but remember the curse of JSONP, if relevant!

Abort all jQuery AJAX requests globally

Is there a way to abort all Ajax requests globally without a handle on the request object?
The reason I ask is that we have quite a complex application where we are running a number of different Ajax requests in the background by using setTimeOut(). If the user clicks a certain button we need to halt all ongoing requests.
You need to call abort() method:
var request = $.ajax({
type: 'POST',
url: 'someurl',
success: function(result){..........}
});
After that you can abort the request:
request.abort();
This way you need to create a variable for your ajax request and then you can use the abort method on that to abort the request any time.
Also have a look at:
Aborting Ajax
You cannot abort all active Ajax requests if you are not tracking the handles to them.
But if you are tracking it, then yes you can do it, by looping through your handlers and calling .abort() on each one.
You can use this script:
// $.xhrPool and $.ajaxSetup are the solution
$.xhrPool = [];
$.xhrPool.abortAll = function() {
$(this).each(function(idx, jqXHR) {
jqXHR.abort();
});
$.xhrPool = [];
};
$.ajaxSetup({
beforeSend: function(jqXHR) {
$.xhrPool.push(jqXHR);
},
complete: function(jqXHR) {
var index = $.xhrPool.indexOf(jqXHR);
if (index > -1) {
$.xhrPool.splice(index, 1);
}
}
});
Check the result at http://jsfiddle.net/s4pbn/3/.
This answer to a related question is what worked for me:
https://stackoverflow.com/a/10701856/5114
Note the first line where the #grr says: "Using ajaxSetup is not correct"
You can adapt his answer to add your own function to window if you want to call it yourself rather than use window.onbeforeunload as they do.
// Most of this is copied from #grr verbatim:
(function($) {
var xhrPool = [];
$(document).ajaxSend(function(e, jqXHR, options){
xhrPool.push(jqXHR);
});
$(document).ajaxComplete(function(e, jqXHR, options) {
xhrPool = $.grep(xhrPool, function(x){return x!=jqXHR});
});
// I changed the name of the abort function here:
window.abortAllMyAjaxRequests = function() {
$.each(xhrPool, function(idx, jqXHR) {
jqXHR.abort();
});
};
})(jQuery);
Then you can call window.abortAllMyAjaxRequests(); to abort them all. Make sure you add a .fail(jqXHRFailCallback) to your ajax requests. The callback will get 'abort' as textStatus so you know what happened:
function jqXHRFailCallback(jqXHR, textStatus){
// textStatus === 'abort'
}

Categories

Resources