0

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)

1 Answer 1

1
$.each(result, function(i, field){
      $('#ph').text(data.ph);

I'm not seeing where you've declared the data variable. You probably want to use the result variable.

Honestly, the best thing to do would probably be to open your browser's dev tools, head to the Network tab and look for the AJAX call. You should be able to see what you're receiving in raw form. If it's in properly-formatted JSON, you'll probably also have a "Preview" view to help see the data in a tree-like view.

Furthermore, I dont understand the purpose of function(result), function(data)((not shown)),function() ((not shown ))in the ajax/jquery language.

 $.getJSON($SCRIPT_ROOT + '/data_refresh', function( result ) {

What we're doing here is using the getJSON function to fetch from a specific URL (1st param), and then putting an anonymous function as the callback (2nd param of your getJSON() function). Within that function's scope we're passing in a variable named result.

I'm going to take a leap (sorry, I don't know FLASK/Python) but I'm going to assume that the response you're getting back is actually

result = {
    ph         : 'your PH value',
    distance   : 'your distance value',
    air_temp   : 'your air temp value',
    humidity   : 'your humidity value',
    heat_index : 'your heat index value',
};

To get the value of each key of result, you would do as you did. Want the humidity? result.humidity it is.

The way you're doing it, you're taking the result object/array and treating it as an array of results that each have the ph, distance, air_temp, humidity and heat_index values.

So, rather than

{
    ph         : 'your PH value',
    distance   : 'your distance value',
    air_temp   : 'your air temp value',
    humidity   : 'your humidity value',
    heat_index : 'your heat index value',
}

you're treating it more like

result = [
    {
        ph         : '1st element's PH value',
        distance   : '1st element's distance value',
        air_temp   : '1st element's air temp value',
        humidity   : '1st element's humidity value',
        heat_index : '1st element's heat index value',
    },
    {
        ph         : '2nd element's PH value',
        distance   : '2nd element's distance value',
        air_temp   : '2nd element's air temp value',
        humidity   : '2nd element's humidity value',
        heat_index : '2nd element's heat index value',
    },
    {
        ph         : '3rd element's PH value',
        distance   : '3rd element's distance value',
        air_temp   : '3rd element's air temp value',
        humidity   : '3rd element's humidity value',
        heat_index : '3rd element's heat index value',
    }, 
    .....
];

In case it helps, the $.each(result, function(i, field){ function is a jQuery iterator that will take return (1st param) and loop over it as an array, return the index(i) and the value(field) within that callback's scope. Its benefit for many years was that it can also iterate over an object(non-numeric array keys, if you will) as well, the i would become the key and field would be the value. ( We now have for...in and for...of within vanilla JS )

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for the thorough reply, something weird is going on with my code. I changed data with "result" to try and reference the variables coming in from Flask in json format. however, no matter what I changed I keep getting the same response and result when I click the button. Even if I fully delete the ajax code I still receive sensor values somehow. Very confusing
So, I got it to work with your edits...thank you for pointing that out to me. However, what is even more puzzling is that I realized after all the changes to my JS code I was making none of them were being updated to the webserver. I dont know why this is the case. Everytime I need my JS to be updated I have to clear my browsing history.
That's totally normal. It's a feature, not a bug. ;) Easy-peasy cache-busting technique for now: Whenever you upload a new version of your JS file, add a query var like bla.js?v=2 and keep incrementing it (in your HTML, where you're including it).
HA! Classic new guy mishap. Appreciate the tip I saw someone else online give that suggestion as well thank you. So are you saying I should incrementally change the name of my javascript in relation to my html. Like when I reference my javascript in the html I should manually increase ?v=2(+1) at the end of the filename everytime i change the JS?

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.