1

I am trying to send data from webpage to python flask using ajax and receiving nothing as response

1. The data is saved to dictionary in javascript in 'requestPayload' variable. And the 'callApi' function is called. code is below

const registerinfo = 'http://127.0.0.1:5000/register_info'

console.log(JSON.stringify({requestPayload}))
result = callApi('POST', registerinfo, {'data': JSON.stringify(requestPayload)})
console.log(result)

2. The 'callApi' further calls ajax function. code is below

function callApi(method, url, data){
    $.ajax({
        method: method,
        url: url,
        data: data,
        dataType: "json"
    })
    .done((data) => {return data})
    .fail((xhr,textStatus, errorThrown) =>{ alert(xhr.status + "      "  + textStatus + "       " + errorThrown)})
}

3. The flask function takes the data from ajax and returns nothing. code is below

@app.route('/register_info')
def registerInfo():
    request_payload = json.loads(request.form['data'])
    print(request_payload)
    return ('',204)

The output of the 'console.log' in javascript and print function in python flask is below

output in the console in javascript

and

output of the print function in flask function

The problem is I am getting the ajax.fail() and not firing ajax.done function and I am not able to find what the error is, Please help me with this.

Karthik
  • 11
  • 2
  • You should stringify the JSON ```result = callApi('POST', registerinfo, JSON.stringify(requestPayload))``` – Krk Rama Krishna May 28 '21 at 07:28
  • I have stringified and sent the data, even the python flask function works But the ajax .done function is not working. – Karthik May 28 '21 at 07:35
  • Okay, I think the problem is with returning the data in the `.done` method because it is like a promise you cannot return data without a call back so you can try something like this https://stackoverflow.com/questions/33679371/how-to-return-data-to-variable-after-ajax-call-success – Krk Rama Krishna May 28 '21 at 08:03

1 Answers1

0

The ajax was not working because the access control allows origin not done true.

Karthik
  • 11
  • 2