0

so I have this code:

 $('input.myinput').each(function(){
    var id = $(this).val();
    var myajax = function(){
      $.ajax({
        url: ajax_url,
        type: "GET",
        data: ({
          code: id
        }),
        beforeSend: function() {  },
        error: function(request){ },
        success: function(data) { alert(data); }
      });
      setTimeout('myajax()', 10000);
    }
    myajax();
 });

I wanted the ajax() request above to run 10 seconds after the page was loaded, so I used setTimeout, but it doesn't work :( the ajax thingy runs right after the page loads, not 10 secs after...

what am I doing wrong?

2 Answers 2

3
$('input.myinput').each(function(){

    var id = $(this).val();

    var myajax = function() {
      $.ajax({
        url: ajax_url,
        type: "GET",
        data: ({
          code: id
        }),
        beforeSend: function() {  },
        error: function(request){ },
        success: function(data) { alert(data); }
      });

      //if you need to run again every 10 seconds
      //setTimeout(myajax, 10000);

    };

    setTimeout(myajax, 10000);
 });
Sign up to request clarification or add additional context in comments.

Comments

1

I'd do a few things differently..

function myajax(id) {
  $.ajax({
    url: ajax_url,
    type: "GET",
    data: ({
      code: id
    }),
    error: function(request){ },
    success: function(data) { alert(data); }
  });
  setTimeout('myajax(id)', 10000);  // you really want it to run AGAIN in another 10 seconds?
}

...

$(document).ready(function() {
   $('input.myinput').each(function(){
      var id = $(this).val();
      setTimeout('myajax(' + id + ')',10000);
   });
});

There's no reason to redeclare myajax as a new function for every input, when you can declare it once and pass in a new ID variable each call.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.