I wonder why AJAX keeps making calls, this way its so hard to press a button and the site is not functional like this... : http://buycheapvaporizer.com/products.php
My JS file:
$(document).ready(function(){
product();
function product(){
$.ajax({
url : "productloader2.php",
method: "POST",
data : {getProduct:1},
success : function(data){
$("#get_product").html(data);
},
complete: function() {
setTimeout(product, 10000);
}
});
}
});
I checked productloader2.php which has main.js and same code you have posted here. This will create an infinite loop of product being called by every load of productloader2.php. You would better remove main.js in productloader2.php. You could use JSON to grab prodcuts.
product();
function product(){
$.ajax({
url : "productloader2.php",
method: "POST",
data : {getProduct:1},
success : function(data){
$("#get_product").html(data);
},
complete: function() {
setTimeout(product, 10000000000000);
}
});
}
Here's a flow chart of happens
products.php calls product() is for first time (and registers interval)
productloader2.php is loaded
product() is called from productloader2.php (first time and registers interval).
productloader2.php is loaded from productloader2.php of 2. and calls product() again and the loop continues.
Eventually, the page might crash.
When ajax request complete it executes setTimeout(product, 10000); which then call product function again after 10000ms.
$(document).ready(function(){
product();
function product(){
$.ajax({
url : "productloader2.php",
method: "POST",
data : {getProduct:1},
success : function(data){
$("#get_product").html(data);
}
});
}
});
Related
I am trying to get the response time of an ajax request and use it in a setTimeout() function, this function displays a loader that is suppose to keep loading until we get the response.
Here's my function :
$("#recalculer").click(function(){
ajax_call();
setTimeout(function()
{
$("#divgris").fadeTo(0,1);
$("#loadingdiv2").hide();
}, 5000);
});
And here's my ajax request :
function ajax_call()
{
var resultat;
var duree_souhaitee= $("#duree").val();
var apport_personnel= $("#apport").val().replace(/\s+/g, '');
var prix_achat_bien=$("#prix").val().replace(/\s+/g, '');
$.ajax({
type: "POST",
url: "/iframe/rest-assurance",
data : {
"duree_souhaitee" : duree_souhaitee,
"apport_personnel" : apport_personnel,
"prix_achat_bien" : prix_achat_bien
},
dataType: 'json',
xhrFields: {
withCredentials: true
},
async: true,
beforeSend: function(){
$("#actualiserAssurance").hide();
},
success: callback_assurance
});
}
For now i set a time of 5000 but i need to replace it with the ajax response time, how can I achieve that ?
I use always:
$("#loadingdiv2").show();
$.ajax(
...
).always(function(){ $("#loadingdiv2").hide(); });
If you want to separate it from the Ajax call I would use a custom event.
$("#recalculer").click(function(){
ajax_call();
});
$("body").bind('custom.ajaxStart', function(){ $("#loadingdiv2").show(); });
$("body").bind('custom.ajaxStop', function(){ $("#loadingdiv2").hide(); });
function ajax_call(){
$('body').trigger('custom.ajaxStart');
$.ajax(..).always(function(){ $('body').trigger('custom.ajaxStop'); });
}
The always callback is triggered even on a 404, relying on timing never works well for me.
Using an event gives you the flexibility of calling the loading deal, from anywhere.
Meaby the you can use:
console.time(label);
and
console.timeEnd(label);
more info can be found here.
Goodluck!
use
var afterfnc = ()=>{
$("#divgris").fadeTo(0,1);
$("#loadingdiv2").hide();
}
and then set
callback_assurance = afterfnc
in ajax call
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 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'm writing a javascript function that should change the view of a postcard depending on which case is selected.
My problem is that the old values of the object "m_case" is getting used. If I press the button with class "case-btn" twice I get the right case selected in my postcard view. But I want it to be triggered when I press the button once.
I guess I have to do something like a callback function in the m_case.setCase() function call, but I can't get it working,
$('.case-btn').on('click', function() {
remove_active_state_from_cases();
m_case.setCase($(this).data('case'));
// Changes the view of the postcard
m_postcard.changeBackground(m_case.getPhoto());
m_postcard.changeMessage(m_case.getMessageText());
m_postcard.changeFullName(m_case.getFullName());
m_postcard.changeCountry(m_case.getCountry());
$(this).toggleClass('active');
});
The setCase() function
this.setCase = function(id) {
// Set ID
this.setID(id);
var that = this;
$.ajax({
url: 'get_case_by_id.php',
type: 'get',
dataType: 'json',
data: {id: that.getID() },
success: function(data) {
if(data.success) {
that.setFirstName(data.first_name);
that.setFullName(data.full_name);
that.setAdress(data.adress);
that.setCountry(data.country);
that.setStamp(data.stamp);
that.setPhoto(data.photo);
that.setSummary(data.summary);
that.setStory(data.story);
that.setMessageText(data.message_text);
that.setDefaultMessageText(data.default_message_text);
that.setMessageImg(data.message_img);
} else {
console.log('failure');
}
}
EDIT The problem might be in my AJAX call, I have to wait till the ajax have been called. but how do I continue the first flow when my Ajax is done and not before?
SOLUTION
I made it working by adding a callback parameter and calling that function in the ajaxs complete function.
$('.case-btn').on('click', function() {
remove_active_state_from_cases();
var that = this;
m_case.setCase($(this).data('case'), function() {
m_postcard.changeBackground(m_case.getPhoto());
m_postcard.changeMessage(m_case.getMessageText());
m_postcard.changeFullName(m_case.getFullName());
m_postcard.changeCountry(m_case.getCountry());
$(that).toggleClass('active');
});
});
// Sets the whole case from an id.
this.setCase = function(id, callback) {
// Set ID
this.setID(id);
var that = this;
$.ajax({
url: 'get_case_by_id.php',
type: 'get',
dataType: 'json',
data: {id: that.getID() },
success: function(data) {
if(data.success) {
that.setFirstName(data.first_name);
that.setFullName(data.full_name);
that.setAdress(data.adress);
that.setCountry(data.country);
that.setStamp(data.stamp);
that.setPhoto(data.photo);
that.setSummary(data.summary);
that.setStory(data.story);
that.setMessageText(data.message_text);
that.setDefaultMessageText(data.default_message_text);
that.setMessageImg(data.message_img);
} else {
console.log('fail big time');
}
},
complete: function() {
callback();
}
});
}
Your m_postcard.changeBackground and other calls should be in the success callback, or in another function that is called from the success callback, as those values aren't set till the async ajax call is done.
With the way your code is now the m_postcard.changeBackground and other calls are called immediately after your setCase function is done executing. This means your methods are executed before the data has arrived from the server
While the ajax is processing you probably should show a loading message on the screen to let the user know they have to wait till the processing is done. Show the message before calling the .ajax call and hide it in the success/error callbacks.
Any changes to the site content should be done from the success callback, ie changing active states, changing content, etc.
I am having some trouble with the timing of javascript events. The problem I am having is that one part of the code seems to be executing before another part of the code completes. I need to ensure that the first code finishes before the latter code begins. Here is the initial code:
function(){
myLoop(); //this needs to complete before the call to myMethod below
$.ajax({
url: sURL + "myController/myMethod",
success: function() {
$.msg("My Success Message",{live:10000});
error: function(){
$.msg("My Error Message",{live:10000});
});
}
And here is the code that loops and inserts records into a db:
function myLoop(){
$('input[name=c_maybe].c_box').each(function(){
if( $(this).prop('checked') ){
var rn = $(this).prop('value');
$.ajax({
url: sURL + 'myController/myInsert',
type:"POST",
dataType: 'text',
data: {'rn': rn},
success: function(data) {
//not sure what to do on success.
}
});
}
});
}
The problem that seems to be happening is that the call to myController\myMethod is happening before myLoop completes inserting all the records into the database.
Can someone suggest a way for me to redesign this code so that I can ensure that myController\myMethod is not called until myLoop has completely finished?
Thanks.
function myLoop() {
var jqxhrs = [];
if( $(this).prop('checked') ){
var rn = $(this).prop('value');
jqxhrs.push($.ajax({...
}
return jqxhrs;
}
function () {
$.when.apply(undefined, myLoop()).done(function () {
$.ajax({
url: sURL + "myController/myMethod",
...
});
}
$.when.apply is used to call $.when on the array of ajax requests, so .done is not called until they are all complete.
You can use the $.when function that has been added to jQuery.
It goes something like this:
$.when(ajaxFunction1(), ajaxFunction1()).done(function(response1, response2){
// when the function calls are done this code here will be executed -> the response will be passed as parameters corresponding to the functions -> response1, response2
});
Or you can try to use "beforeSend" within the ajax function:
$.ajax({
beforeSend: function(){
alert("doing stuff before the ajax call ...");
},
success: function(){
alert("Whoa!");
}
});
You can make the ajax call synchronous. That way, the execution will be blocked till ajax call returns:
$.ajax({
url: sURL + 'myController/myInsert',
type:"POST",
dataType: 'text',
data: {'rn': rn},
async: false,
success: function(data) {
//not sure what to do on success.
}
});