Nick Schrock Nick Schrock - 7 months ago 19
Javascript Question

jQuery AJAX function called multiple times but data is only pulled on first call

I have a jQuery function for pulling data from an XML file on a flask server. I start out my ready function with calling this function and all of my variables update with no issues. However, when I call the function a second time from a click action my variables do not update. I know that the AJAX function is being called successfully because I get my alerts. It seems as thought the XML document is not being re-loaded after the first call. How can I get my variables to update on every call to the function.

Global Variables

//Variables representing Sensor Data
var bspeed=0;
var set_temp=0;
var f_temp=0;
var fuel_level=0;
var s_temp=0;
var humidity=0;
var bspeed_data=0;
var set_temp=0;
var mode = "mod";
var mod_mode = "blower";


Data-Pull function

//AJAX XML file parsing
function pull_data(){

//Gather Data from main.xml and store into variables
$.ajax({
type: "GET",
url: "static/main.xml",
async: false,
success: function(xml){
$(xml).find('item').each(function(){
var id = $(this).find('id').text();
switch(id){
case "ftemp_data":
f_temp = $(this).find('value').text();
break;
case "stemp_data":
s_temp = $(this).find('value').text();
break;
case "fuel_level_data":
fuel_level = $(this).find('value').text();
break;
case "humidity_data":
humidity = $(this).find('value').text();
break;
case "blower_speed":
alert("Changing bspeed");
bspeed_data = $(this).find('value').text();
}
});
alert("Pull Success "+ bspeed_data);
},
error: function(data){
alert("AJAX failed: "+ data.status + ' ' + data.statusText);
}
});

//Populate HTML with variables
$("#ftemp_data").text(f_temp+("\u00B0"));
$("#stemp_data").text(s_temp+("\u00B0"));
$("#fuel_level_data").text(fuel_level+"%");
$("#humidity_data").text(humidity+"%");
$("#bspeed_data").text(bspeed_data);
}


Ready Function (Simplified)

$(document).ready(function(){
pull_data();
//Click Refresh Button
$("#refresh_btn").click(function(){
pull_data();
});
}


I'm fairly new to web development so feel free to point out structural issues with what I'm doing.

Answer

Probably you need to force to refresh the cache, in order to do this, add a property cache: false in the ajax code:

$.ajax({
    type: "GET",
    url: "static/main.xml",
    async: false,
    cache: false,...

You can check in Jquery Ajax documentation

Comments