views:

21

answers:

2

Hi

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?

+1  A: 
$('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);
 });
andres descalzo
thanks, works :D
Alex
ok, you can accept the answer :).
andres descalzo
+1  A: 

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.

Fosco
you're right, thank you :)
Alex