I have what I assume is a simple problem. But I am completely knew to AJAX and have been searching around and havent found anything I can find applicable.
I am fetching data from a route in my Flask app/webserver when I click a button. I am trying to return the data in its respective #id element on the page, but even though I specify their id's the data is sent to only the first #id. In addition, the data is sent in a random order. I am clearly on the wrong track in terms of dealing with the JSON data I retrieve from flask.
Furthermore, I dont understand the purpose of function(result), function(data)((not shown)),function() ((not shown ))in the ajax/jquery language. If anyone can elobarate that would be great, I've given it google searches and cant find anything helpful as well. Anybody have any suggestions? Thank you
JQUERY/AJAX
$(document).ready(function() {
$('#data_refresh').click(function() {
$.getJSON($SCRIPT_ROOT + '/data_refresh', function(result) {
$.each(result, function(i, field){
$('#ph').text(data.ph);
$('#distance').text(data.distance);
$('#air_temp').text(data.air_temp);
$('#humidity').text(data.humidity);
$('#heat_index').text(data.heat_index);
});
});
});
});
HTML
<button id='data_refresh' type="button">Refresh Data</button>
<div class="sensor">
<h3> PH:<span id='ph'></span></h3>
</div>
<div class="sensor">
<h3> Water Temperature: <span id='water_temp'></span></h3>
</div>
<div class="sensor">
<h3> Water Level: <span id='distance'></span></h3>
</div>
<div class="sensor">
<h3> Air Temperature: <span id='air_temp'></span></h3>
</div>
<div class="sensor">
<h3> Humidity: <span id="humidity"></span></h3>
</div>
<div class="sensor">
<h3> Heat Index: <span id="heat_index"></span> </h3>
</div>
FLASK/python
@app.route("/data_refresh")
def data_refresh():
ser = serial.Serial('/dev/ttyUSB0', 9600, 8, 'N', 1)
data = ser.readline().rsplit()
# temp = temp_sensor1.read_temp()
ph = float(data[0])
distance = int(data[1])
humidity = float(data[2])
air_temp = float(data[3])
heat_index = float(data[4])
now = datetime.now().strftime("%A %-m/%d/%y %-I:%-M:%-S %p")
ser.close()
return jsonify(ph=ph, distance=distance, humidity=humidity, air_temp=air_temp, heat_index=heat_index, now=now)