I need to make an Ajax call for every x seconds, to read the data from xml and use xml data as variable to call the same function after x seconds
here is the code:
<script type="text/javascript">
function fetchAjaxContent(msg,time) {
setTimeout(function(){
$.ajax({
type: "GET",
url: "ajax.php?msg="+msg+"&p="+Math.random(),
dataType: "xml",
success: function(xml) {
$(xml).find('msgs').each(function(){
var content = $(this).find('content').text();
var ftime = $(this).find('time').text();
$("#page-wrap").html(content);
});
}
});
msg=msg+1;
if(msg=4)
msg=1;
ftime=parseInt(ftime)*1000;
fetchAjaxContent(msg,ftime);
},time);
}
fetchAjaxContent(1,0);
its working on first iteration, 2nd fails.
Functions starts with msg id =1 and time =0 to start the first loop on pageload. in 2nd loop, settimeout to call after x seconds.
What am i doing wrong, please help
you define
ftimein succes function, so that means it’s not available outside succes function,Define
ftimein main function that should solve your problem.UPDATE:
And there is one more problem in your code,
jQuery.ajax()performs an asynchronous HTTP (Ajax) request. Softimewill not set immediately andfetchAjaxContentwill call continuously with sameftime, you should take all code into ajax success function.