Request ajax with setInterval - javascript

I want to call ajax function at specified intervals after enterkey being pressed.
However, the code doesn't work.
I want to get some advice.
Thank you!
function regist(){
$.ajax({
url: '/getlabel',
method: 'GET'
}).done(function(r){
// console.log(r);
$('#label').text(r)
console.log("ajax-success")
}).fail(function(){
console.log("ajax fail")
});
}
function keyPress(e) {
if (e.keyCode == 13) {
setInterval( regist() , 3000);
return false;
}
}

Related

Execute jquery functions in order

function fn_one() {
$('#search-city-form').trigger('click');
}
function fn_two() {
$("form input[name='tariffId']").val("137");
$('#search-city-form').trigger('click');
}
function fn_three() {
$("form input[name='tariffId']").val("138");
$('#search-city-form').trigger('click');
}
function fn_four() {
$("form input[name='tariffId']").val("139");
$('#search-city-form').trigger('click');
}
$(document).on('click','.ui-menu li',function(){
fn_one();
fn_two();
fn_three();
fn_four();
});
I have this js code. I need to execute the functions in on(click) in order, i.e. fn_one() goes first, fn_two() second and etc.
Please give simple example of how can I achieve this.
Edit: OK, I used the next function to be executed in the previous one but still I was getting erraneous data. So I think I realized why this is happening. I will explain what $('#search-city-form').trigger('click'); does. It triggers a form submit which makes an Ajax call and other function are not waiting till ajax request is complete. So how do I make it to wait for ajax request to complete?
EDIT 2:
Event handler for $('#search-city-form'):
$('#cdek').submit(function() {
var formData = form2js('cdek', '.', true, function(node) {
if(node.id && node.id.match(/callbackTest/)) {
return {
name : node.id,
value : node.innerHTML
};
}
});
var formDataJson = JSON.stringify(formData);
// console.log(JSON.stringify(formData));
document.getElementById('testArea').innerHTML = 'Отправляемые данные: <br />' + JSON.stringify(formData, null, '\t');
$.ajax({
url : 'http://api.cdek.ru/calculator/calculate_price_by_jsonp.php',
jsonp : 'callback',
data : {
"json" : formDataJson
},
type : 'GET',
dataType : "jsonp",
success : function(data) {
console.log(data.result.price);
} else {
for(var key in data["error"]) {
console.log(data["error"][key]);
}
}
}
});
return false;
});
I'll do this. If you need validate when the function has triggered, maybe you need to work with promises.
function fn_one() {
$('#search-city-form').trigger('click');
fn_two()
}
function fn_two() {
$("form input[name='tariffId']").val("137");
$('#search-city-form').trigger('click');
fn_three()
}
function fn_three() {
$("form input[name='tariffId']").val("138");
$('#search-city-form').trigger('click');
fn_four()
}
function fn_four() {
$("form input[name='tariffId']").val("139");
$('#search-city-form').trigger('click');
}
$(document).on('click','.ui-menu li',function(){
fn_one();
});

AJAX sending multiple requests after button click

I just want one click to equal one submit in my jQuery code.
I've read quite a few posts on this same topic but I think mine is different. I do have a mouseleave and focusout event that I'm using to find errors in user input. Those functions feed down into the function that is submitting multiple times. The more times I hit mouseleave and focusout the more times my Ajax request is submitted. But I need mouseleave and focusout to continue to work and check the users input, that's why I'm not using one. Please see my code below, the function that I think is submitting multiple times is handleButtonClicksAfterError
function getCreditAmountToSend(modal){
console.log("getCreditAmountToSend");
var checkBox = $(modal).contents().find("#fresh-credit-checkbox");
checkBox.change(function(){
if($(checkBox).is(":checked")) {
var creditAmount = +(sessionStorage.getItem("creditAmount"));
sessionStorage.setItem('amountToSend', creditAmount);
}
});
var pendingCreditAmount = $(modal).contents().find("#pending_credit_amount");
pendingCreditAmount.on({
mouseleave: function(){
if(pendingCreditAmount.val() != ""){
adminForGetPendingCredit(modal);
}
},
focusout: function(){
if(pendingCreditAmount.val() != ""){
adminForGetPendingCredit(modal);
}
}
});
}
function adminForGetPendingCredit(modal){
console.log("adminForGetPendingCredit");
var checkBox = $(modal).contents().find("#fresh-credit-checkbox");
if(!$(checkBox).is(":checked")) {
var enteredAmount = +($(modal).contents().find("#pending_credit_amount").val());
var creditAmount = +(sessionStorage.getItem("creditAmount"));
sessionStorage.setItem('enteredAmount', enteredAmount);
doWeDisplayError(modal,creditAmount, enteredAmount);
}
}
function doWeDisplayError(modal,creditAmount, enteredAmount){
console.log("doWeDisplayError");
$(modal).contents().find("#fresh-credit-continue-shopping").prop("disabled", false);
$(modal).contents().find("#fresh-credit-checkout").prop("disabled", false);
if(creditAmount < enteredAmount){
$(modal).contents().find("#pending_credit_amount").val("");
$(modal).contents().find("#fresh-credit-continue-shopping").prop("disabled", true);
$(modal).contents().find("#fresh-credit-checkout").prop("disabled", true);
displayError();
}
else{
handleButtonClicksAfterError(modal, enteredAmount);
}
}
function handleButtonClicksAfterError(modal, enteredAmount){
// this is the problem!!!!!!!!!!!!!
console.log("handleButtonClicksAfterError");
sessionStorage.setItem('amountToSend', enteredAmount);
var continueButton = $(modal).contents().find("#fresh-credit-continue-shopping");
continueButton.click(function() {
modal.hide();
});
var checkoutButton = $(modal).contents().find("#fresh-credit-checkout");
checkoutButton.click(function() {
console.log("handleButtonClicksAfterError");
sendData();
});
}
function displayError(){
console.log("displayError");
$(function(){
$("#fresh-credit-iframe").contents().find("#pending_credit_amount").attr("placeholder", "Whoops, that was too much");
$("#fresh-credit-iframe").contents().find("#pending_credit_amount").attr({
class: "form-control form-control-red"
});
sessionStorage.removeItem('enteredAmount');
});
}
This is the function that actually POSTs the data
function sendData(){
var amountToSend = sessionStorage.getItem("amountToSend");
var products = $.parseJSON(sessionStorage.getItem("products"));
console.log("sendData");
console.log("This is the amount to send " + amountToSend);
$.ajax({
url: "/apps/proxy/return_draft_order",
data: {amountToSend, products},
type: "POST",
dataType: "json",
complete: function(data) {
window.location.href = data.responseText;
console.log("This is the URL from poll " + data.responseText );
return false;
},
});
}
It ended up being super simple.. I just needed the jQuery off method.. I attached it to the button before click and everything is peachy.. Looks like this:
checkoutButton.off().click(function(){});
off clears all the previous event handlers and then just proceeds with Click
Pretty cool, to read more check it out here
use async:false to prevent multiple request
$(document).off('click').on('click', function(){
$.ajax({
type:'POST',
url: ,
async:false,
cache: false,
data:{}
,
success: function(data){
},
error:function(data){
}
});
});

Run the function after the effects is done

How can I run the function after the effect is done like delaying running the specified function after a certain time? I tried set timeout and it didn't work for me.
Here my Code
<script>
$("#findtext").keyup(function (e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13)
{
explodeEffect();
}
$.ajax({
url: 'resultFindFriend.php',
type: 'post',
async: false,
data: { dataFriend: $(this).val() },
success: function (data) {
$('.outputfindfriend').html(data);
}
},setTimeout(150));
});
function explodeEffect() {
$("#explodesearchresult").toggle("explode");
setTimeout(1000);
window.location("http://localhost/index.html");
};
$("#buttonfriend").click(function () {
explodeEffect();
return false;
});
</script>
This is doable with jQuery's .toggle(), just add a function as the second argument.
Try this:
function explodeEffect() {
$("#explodesearchresult").toggle(400, function() {
setTimeout(function() {
window.location.href = "http://localhost/index.html";
}, 1000);
});
}
This will redirect the page 1 second after the explode effect has finished.

How can I stop this setTimeout function from running?

I use the function below to check on the status of a JSON file. It runs every 8 seconds (using setTimeout) to check if the file has changed. Once the JSON's status becomes 'success' I no longer want to keep calling the function. Can someone please show me how to do this? I suspect it involves the use of clearTimeout, but I'm unsure how to implement this.
Cheers!
$(function() {
var checkBookStatus = function() {
var job_id = "#{#job.job_id}";
var msg = $('.msg');
var msgBuilding = $('#msg-building');
var msgQueuing = $('#msg-in-queue');
var msgSuccessful = $('#msg-successful-build');
var msgError = $('#msg-error');
$.ajax({
url: '/jobs/'+job_id+'/status.json',
datatype: 'JSON',
success:function(data){
if (data.status == "failure") {
msg.hide();
msgError.show();
}
else if (data.status == "#{Job.queue}") {
msg.hide();
msgQueuing.show();
}
else if (data.status == "#{Job.building}") {
msg.hide();
msgBuilding.show();
}
else if (data.status == "#{Job.failure}") {
msg.hide();
msgError.show();
}
else if (data.status == "#{Job.success}") {
msg.hide();
msgSuccessful.show();
}
},
}).always(function () {
setTimeout(checkBookStatus, 8000);
});
};
checkBookStatus();
});
t = setTimeout(checkBookStatus, 8000); when you decide to stop the timeout use this clearTimeout(t);.
use clearTimeout
e.g. you defined :
id = setTimeout(checkBookStatus, 8000);
then you can remove this function by :
clearTimeout(id)
Before your call of checkBookStatus() at the end, put another call: var interval = setInterval(checkBookStatus, 8000);. Then on success you can clearInterval(interval).
Do not use setTimeout for iteration.
A lot of answers are suggesting just to use clearTimeout() however, you are checking the status after the timeout has expired, there is no timeout to clear. You need to not call setTimeout() in your always() function rather than to clear anything. So you could re-inspect the status inside your always() function I suppose, but your data object isn't in scope there. It would be preferable to just use setInterval() outside of your checkBookStatus() function.
$(function() {
var checkBookStatus = function() {
var job_id = "#{#job.job_id}";
var msg = $('.msg');
var msgBuilding = $('#msg-building');
var msgQueuing = $('#msg-in-queue');
var msgSuccessful = $('#msg-successful-build');
var msgError = $('#msg-error');
$.ajax({
url: '/jobs/'+job_id+'/status.json',
datatype: 'JSON',
success:function(data){
if (data.status == "failure") {
msg.hide();
msgError.show();
}
else if (data.status == "#{Job.queue}") {
msg.hide();
msgQueuing.show();
}
else if (data.status == "#{Job.building}") {
msg.hide();
msgBuilding.show();
}
else if (data.status == "#{Job.failure}") {
msg.hide();
msgError.show();
}
else if (data.status == "#{Job.success}") {
msg.hide();
msgSuccessful.show();
clearInterval(interval);
}
}
});
};
var interval = setInterval(checkBookStatus, 8000);
checkBookStatus();
});
Call clearTimeout with the value previously returned by setTimeout. This would give you something like:
$(function() {
var timeoutID;
var checkBookStatus = function () {
[…]
else if (data.status == "#{Job.success}") {
clearTimeout(timeoutID);
[…]
}).always(function () {
timeoutID = setTimeout(checkBookStatus, 8000);
[…]
When you use setTimeout, use like this:
var myTime = setTimeout(checkBookStatus, 8000);
to clear it just:
clearTimeout(myTime);
the following should work...
the setTimeout function return an instance of the setTimeout function. Keep this value in a variable and pass it to the function clearTimeout when you want to prevent the event from firing again.
i.e.
var t = setTimeout(1000, someFunction);
...
//after you no longer need the timeout to fire, call
clearTimeout(t);

Why does this JavaScript freeze IE6?

When you click, "Add to Bag" on this page, it freezes IE6 every time. How can I figure out why it is freezing? Does anyone have a more direct answer?
totallytrollbeads {dot} com {slash} Safety0.html
function update() {
$.ajax({
dataType: 'json',
type: 'POST',
url: '/cgi-bin/ajax_cart_count.cgi',
timeout: 2000,
success: function (data) {
// If bag is empty, it's see through.
if (data.cart_count == 0) {
$(".shopping_bag").css("opacity", ".2");
}
// If bag is not empty, it's not see through.
else {
$(".shopping_bag").css("opacity", "1");
}
$("#bag_total").html(data.grand_total);
$("#bag_count").html(data.cart_count);
window.setTimeout(update, 15000);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$("#bag_total").html('Timeout contacting server..');
window.setTimeout(update, 60000);
}
})
}
$(document).ready(update);
// preparethe form when the DOM is ready
$(document).ready(function () {
// bind form using ajaxForm
$('.add_to_cart_form').ajaxForm({
beforeSubmit: loading,
success: myBox
});
});
// preparethe form when the DOM is ready
$(document).ready(function () {
// bind form using ajaxForm
$('.add_to_cart_form').ajaxForm({
beforeSubmit: loading,
success: myBox
});
});
// $(".add_to_cart_form").click(function () {
// $('.bypass_add_to_cart_form').ajaxForm({ success: myBox });
// });
function loading() {
$("#loadingContent").show();
}
function myBox(resptext, statustext) {
$("#loadingContent").hide();
Boxy.ask(resptext, ["View Bag", "Continue Shopping"], function (val) {
if (val == "View Bag") {
document.location.href = "/cgi-bin/store.cgi?action=view_cart";
}
if (val == "Continue Shopping" && product_detail == 1) {
history.go(-1);
}
}, {
title: "Add to Bag"
});
$('.bypass_add_to_cart_form').ajaxForm({
beforeSubmit: loading,
success: myBox
});
update();
return false;
}
/*
This tells the ajax-style add to cart that
it's on a product detail page so if the
user clicks "Continue Shopping" it takes
them back on step in their history.
*/
$('.search_view').click(function () {
product_detail = 0;
});
$('.product_view').click(function () {
product_detail = 1;
});
It's not easy to debug a thing that freezes immediately from the outside. But it's always a good idea to cleanup the whole, remove things that are not essential, check the functionality and then do the next step.
For example this:
// preparethe form when the DOM is ready
$(document).ready(function () {
// bind form using ajaxForm
$('.add_to_cart_form').ajaxForm({
beforeSubmit: loading,
success: myBox
});
});
// preparethe form when the DOM is ready
$(document).ready(function () {
// bind form using ajaxForm
$('.add_to_cart_form').ajaxForm({
beforeSubmit: loading,
success: myBox
});
});
It's not hard to see that have this part twice there.
Put a little more accuracy into your application instead of copy&paste.

Categories

Resources