I have a function newCount that I run on Ajax success and it is working OK, however, I want to also run the same function every time the window is reloaded but for some reason I'm unable to call the function with newCount();
my code:
.ajax
$( document ).ajaxComplete(function() {
newCount();
});
.js
function newCount() {
var sum = 0;
$('.myclass').each(function() {
sum += parseFloat($(this).text());
});
// update count in html
$('#myid').html(sum);
}; // end count function
newCount(); // ajax not working when this in place
when I add newCount(); after the function, it will run correctly on page load, but the ajax will no longer work and vice versa.
What am I missing? How can I call the same function from the ajax success and every time the page is loaded?
Hey I've created this Plunker to show you how you should call the functions.
Here is the Javascript code.
<script>
(function(){
function newCount(msg) {
alert("message from: " + msg);
}; // end count function
debugger;
newCount("Page load");
$.get( "data.json", function( data ) {
alert( "Load was performed." );
});
$(document).ajaxComplete(function() {
newCount("ajax complete");
});
})();
EDIT 1
I've changed the Plunker so you can see that also works inside the $.ajax success property.
$.ajax({
url: "data.json",
data: "",
success: function() {
newCount("ajax complete");
}
});
Related
I'm working on a magento site which uses ajax layered navigation. When the user clicks on a color link in the layered nav it loads a list of the relevent products. I want to fire a click event after the ajax has completed.
I thought I could use the jQuery when() function for this but I can't get it working.
jQuery( "a#red-hoi-swatch" ).click(function() {
jQuery.when( jQuery.ajax() ).then(function() {
jQuery("a[name*='chili-ireye']").click();
});
});
Basically, I want to run jQuery("a[name*='chili-ireye']").click(); after the ajax has finished when a user clicks the a#red-hoi-swatch.
UPDATE
I found the ajax responsible for this, it's from the Magento Blacknwhite theme we bought
/*DONOT EDIT THIS CODE*/
function sliderAjax(url) {
if (!active) {
active = true;
jQuery(function($) {
oldUrl = url;
$('#resultLoading .bg').height('100%');
$('#resultLoading').fadeIn(300);
try {
$('body').css('cursor', 'wait');
$.ajax({
url: url,
dataType: 'json',
type: 'post',
data: data,
success: function(data) {
callback();
if (data.viewpanel) {
if ($('.block-layered-nav')) {
$('.block-layered-nav').after('<div class="ajax-replace" />').remove();
$('.ajax-replace').after(data.viewpanel).remove();
}
}
if (data.productlist) {
$('.category-products').after('<div class="ajax-category-replace" />').remove();
$('.ajax-category-replace').after(data.productlist).remove();
}
var hist = url.split('?');
if(window.history && window.history.pushState){
window.history.pushState('GET', data.title, url);
}
$('body').find('.toolbar select').removeAttr('onchange');
$('#resultLoading .bg').height('100%');
$('#resultLoading').fadeOut(300);
$('body').css('cursor', 'default');
ajaxtoolbar.onReady();
jQuery('.block-layered-nav a').off('click.vs');
try{
ConfigurableSwatchesList.init();
}catch(err){}
}
})
} catch (e) {}
});
active = false
}
return false
}
function callback(){
}
I was able to achieve this with the ajaxComplete() function:
jQuery( "a#red-hoi-swatch" ).click(function() {
jQuery(document).ajaxComplete(function(){
jQuery("a[name*='chili-ireye']").click();
});
});
Not done jQuery for a while but do you really need the .when()?
Can you not just do
jQuery( "a#red-hoi-swatch" ).click(function() {
var url = 'http://my/api/url';
jQuery.ajax(url).then(function() {
jQuery("a[name*='chili-ireye']").click();
});
});
You can make any of the following 3
calling your click event on the success of your ajax call
you can make the asynch property of your ajax call to false;
callback the click event on success of your ajax call.
You can use handlers just after ajax queries or you can define a success callback for the ajax query.
From the jQuery API:
// Assign handlers immediately after making the request,
// and remember the jqXHR object for this request
var jqxhr = $.ajax( "example.php" )
.done(function() {
alert( "success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "complete" );
});
// Perform other work here ...
// Set another completion function for the request above
jqxhr.always(function() {
alert( "second complete" );
});
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.
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
I currently have the below function which updates the data in a div when the page is refreshed and this works fine however i want to edit the function to make it constantly update say every 2 seconds without having to refresh the page. How would i go about doing this?
<script>
$(document).ready(function ajaxLoop() {
//-----------------------------------------------------------------------
// Send a http request with AJAX Jquery
//-----------------------------------------------------------------------
$.ajax({
url: 'getOrderStatus.php', // Url of Php file to run sql
data: "",
dataType: 'json', //data format
success: function ajaxLoop(data) //on reciept of reply
{
var OrdersSubmitted = data[0].SUBMITTED; //get Orders Submitted Count
var OrdersFulfilled = data[0].FULFILLED; //get Orders Fulfilled count
//--------------------------------------------------------------------
// 3) Update html content
//--------------------------------------------------------------------
$('#OrdersSubmitted').html("SUBMITTED:" + OrdersSubmitted);
$('#OrdersFulfilled').html("FULFILLED:" + OrdersFulfilled); //Set output html divs
}
});
});
</script>
You can chain setTimeout calls to achieve this:
$(document).ready(function() {
function updateOrders() {
$.ajax({
url: 'getOrderStatus.php',
dataType: 'json',
success: function ajaxLoop(data) {
var OrdersSubmitted = data[0].SUBMITTED;
var OrdersFulfilled = data[0].FULFILLED;
$('#OrdersSubmitted').html("SUBMITTED:"+ OrdersSubmitted);
$('#OrdersFulfilled').html("FULFILLED:"+ OrdersFulfilled);
setTimeout(updateOrders, 2000);
}
});
});
The alternative is setInterval(), however if the requests slow down this can lead to calls being queued, which will eventually lead to memory issues.
You need to add a repeating event to call your updateOrders function. Like:
function startUpdateOrdersTimes() {
setInterval(function() {
updateOrders();
}, 2000);
//Call now (otherwise waits for first call)
updateOrders();
}
Using "window.setInterval" (https://developer.mozilla.org/en/docs/Web/API/window.setInterval) you can repeatedly execute a function at a specified time interval.
function SomeFunction()
{
$.ajax({...});
}
window.setInterval(SomeFunction,2000);
This would execute SomeFunction every 2 seconds
Hope this helps
timerupdateorders = setInterval(function() {
ajaxLoop();
}, 2000);
You may use
clearInterval(timerupdateorders);
to end the timer
I have a plugin raty (http://wbotelhos.com/raty) that is loaded to document.ready, the page content changes at the click of a button reloading a part of the DOM, and the document is not ready "recalculated" and I will not reload all javascript (there are other similar behavior) I tried this solution but without success
function star(){
alert("star");
...code plugin...
}
$(document).ready(function() {
star();
});
$.ajax({
..code..
done: function(creaStella) {
alert("D");
star();
},
complete:function(){
alert("C");
star();
},
});
After call ajax i have alert("star") but i haven't my div populated
Incorrect usage of $.ajax
$.ajax({
..code..
success: function(creaStella) {
//code to populate div goes here
alert("complete");
star();
}
}).done(function(){
//or here
alert("complete2");
});
use success/done as show (or both).
I resolve in this Way..(promise().done)
also form with jquery validate plugin before dosen't works
function star(){
//plugin star
}
$(document).ready(function() {
formJqueryValidate1();
formJqueryValidate2();
star();
});
function formJqueryValidate1() {
//my check
function formJqueryValidate2() {
//my check
}
$.ajax({
success: function(msg) {
$('#myid').html(msg.template).promise().done(function(){
formJqueryValidate1();
formJqueryValidate2();
star();
});
}
}
});