skip to Main Content

I’m stumped why my Flask called JSON data is not being read by ajax success wait statement that works very well elsewhere. I realize the Success: statement is supposed to wait for data to returned and it does, but then the data returned isn’t accessible as any JSON. There are no console nor browser console errors to indicate why data is considered ‘invalid’

Flask Function

@blueprint.route('/target_liner')
def target_liner():

    ind_id = int(request.args.get('ind_id'))
    label = "1508 Loss Correction"
    data = '[{"Program_Name":"' + label + '"}]'
    return data

JSON Data

[{"Program_Name":"1508 Loss Correction"}] // This is confirmed legal JSON

Javascript

function updates() {
      $.ajax({
          url: "/target_line",
          method: "GET",
          data: {
              ind_id: 1508
          },
          success: function (data) {
            
            console.log(data);
            alert(data);  // This shows the JSON string correctly in Chrome Inspect console

            alert(data.Program_Name);
            alert(data[0]['Program_Name']);
            alert(data[0].Program_Name );
      }
    });
};

updates();

2

Answers


  1. You have three possibilities:

    1. in your flask change return data to return jsonify(data);
    2. add dataType: "json", to your ajax call as per comment by @Rocket Hazmat;
    3. add to the succes response a conversion from string to json: data = JSON.parse(data);
    $.ajax({
        url: "/target_line",
        method: "GET",
        data: {
            ind_id: 1508
        },
        success: function (data) {
    
            data = JSON.parse(data);
            console.log(data);
    
            console.log(Object.keys(data[0])[0]);  // print: Program_Name
            console.log(data[0].Program_Name );    // print: 1508 Loss Correction
        }
    });
    
    Login or Signup to reply.
  2. The data retuned is a String. You can either do a JSON.parse(data) after the success or you can use dataType: ‘json’ in your ajax request. you might get a parse error if your JSON String is not formed properly when you use dataType: ‘json’ .

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search