Skip to content
Advertisement

Can’t return multiple variables from Flask to Javascript AJAX function

I have a JS function that is updating subsequent select boxes based on the previous input. I am populating these with responses from a Flask function that queries a database. The issue is that the second variable that holds an array cannot be processed properly. The first function works fine, but the second just has an undefinded variable.

JS Function

function update(deptcity, destsets, datesets, dtimesets) {

        $.ajax({
          
          url:"/returncity/?q="+deptcity, //the page containing python script
          type: "POST", //request type,
          dataType: 'json',
          data: JSON.stringify(deptcity)
        })

        .then( function updateDest(destsets, datesets) {
          
          console.log(datesets)
          var dest = destsets.destsets;
            
          var select = document.getElementById("destination");
          var length = select.options.length;

          for (i = length-1; i >= 0; i--) {
            select.options[i] = null;
          }

          var len = dest.length;
          for (i = len - 1; i >= 0; i--) {
            document.getElementById("destination").add(new Option(dest[i]));
          }

          

        })
          
        .then( function updateDate(datesets) {

          console.log(datesets);
          var date = datesets;

          var select = document.getElementById("date");
          var length = select.options.length;

          for (i = length - 1; i >= 0; i--) {
            select.options[i] = null;
          }

          var len = date.length;
          for (i = len - 1; i >= 0; i--) {
            document.getElementById("date").add(new Option(date[i]));
          }
        })
          
        ;

      }

Flask Function

@views.route('/returncity/', methods = ['POST', 'GET'])
@login_required
def ajax_returncity():
    if request.method == 'POST':

        q = [request.get_json('data')]
        

        query = '''SELECT DISTINCT destination FROM Journey WHERE depart = ? ORDER BY destination ASC'''
        con = sqlite3.connect('Coachdatabase.db')
        cur = con.cursor()
        cur.execute(query, q)
        destrows = cur.fetchall()

        query = '''SELECT DISTINCT date FROM Journey WHERE depart = ? ORDER BY date ASC'''
        con = sqlite3.connect('Coachdatabase.db')
        cur = con.cursor()
        cur.execute(query, q)
        daterows = cur.fetchall()

        query = '''SELECT DISTINCT dtime FROM Journey WHERE depart = ? ORDER BY dtime ASC'''
        con = sqlite3.connect('Coachdatabase.db')
        cur = con.cursor()
        cur.execute(query, q)
        dtimerows = cur.fetchall()

        cur.close()
        con.close()

        destrow = []
        for i in destrows:
            for x in i:
                destrow.append(str(x))

        daterow = []
        for i in daterows:
            for x in i:
                daterow.append(str(x))
        print(daterow)
        
        dtimerow = []
        for i in dtimerows:
            for x in i:
                dtimerow.append(str(x))

        return jsonify(destsets = destrow, datesets = daterow, dtimesets = dtimerow)

I tried passing the variable through the first function to see if it would be accepted but it didn’t. The first function has it set to a string ‘success’. The second function returns ‘undefined’.

Thanks in advance for any help.

Advertisement

Answer

The answer is to create a JSON object within the flask function and return it as one varibale as well as only using one JS function. I am not sure of the reasoning behind it as I guess I don’t understand JSON and AJAX etc. very well. Flask

all_data = {'dest':destrow,'date':daterow, 'dtime':dtimerow}

return jsonify(all_data)

js

function update(deptcity, data) {

    $.ajax({
      
      url:"/returncity/?q="+deptcity, //the page containing python script
      type: "POST", //request type,
      dataType: 'json',
      data: JSON.stringify(deptcity)
    })

    .then( function updateDest(data) {
      
      
      var dest = data.dest;
      console.log(dest);
        
      var select = document.getElementById("destination");
      var length = select.options.length;

      for (i = length-1; i >= 0; i--) {
        select.options[i] = null;
      }

      var len = dest.length;
      for (i = len - 1; i >= 0; i--) {
        document.getElementById("destination").add(new Option(dest[i]));
      }

      console.log(data.date);
      var date = data.date;

      var select = document.getElementById("date");
      var length = select.options.length;

      for (i = length - 1; i >= 0; i--) {
        select.options[i] = null;
      }

      var len = date.length;
      for (i = len - 1; i >= 0; i--) {
        document.getElementById("date").add(new Option(date[i]));
      }

      console.log(data.dtime);
      var dtime = data.dtime;

      var select = document.getElementById("dtime");
      var length = select.options.length;

      for (i = length - 1; i >= 0; i--) {
        select.options[i] = null;
      }

      var len = dtime.length;
      for (i = len - 1; i >= 0; i--) {
        document.getElementById("dtime").add(new Option(dtime[i]));
      }

    })
      
      
    ;

  }
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement