Erdem Erdem - 1 year ago 176
Python Question

Passing json data from jquery to flask

I'd like to pass some Json data from jQuery to flask. I have an add user method which takes some form values and passes them to flask.

function kullaniciEkle(event) // add a user
{
event.preventDefault();

var hataSayisi = 0;

$('#addUser input').each(function (index, val) {
if ($(this).val() === '') {
hataSayisi++;
}
});

console.log("Number of errors: ", hataSayisi);

if (hataSayisi === 0) {

var yeniKullanici = {
'kullanıcıAdı' : $('#kullaniciEkle fieldset input#girisIsim').val(),
'eposta' : $('#kullaniciEkle fieldset input#girisEposta').val(),
'tamİsim' : $('#kullaniciEkle fieldset input#girisTamIsim').val(),
'yaş': $('#kullaniciEkle fieldset input#girisYas').val(),
'yer' : $('#kullaniciEkle fieldset input#girisSehir').val(),
'cinsiyet' : $('#kullaniciEkle fieldset input#girisCinsiyet').val()
}

console.log(yeniKullanici);
console.log(JSON.stringify(yeniKullanici));

$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(yeniKullanici),
url: '/add',
success: function(data){
console.log("Are we here?");
$('#kullaniciEkle fieldset input').val('');


},
error: function(xhr, textStatus, error){
alert(xhr.responseText);
},
dataType: "json"
});

} else {
alert("Please fill in all form fields");
}

}


And the add method in flask is like that.

@app.route('/add', methods=['POST'])
def addUser():
if request.method == "POST":
content = request.get_json(silent=True)
print (content)
return 'Hi there'


It looks like I may get the json data from flask. But on the jQuery side I suppose error part is executed. Because I get an alert message 'Hi there' if addUser() function returns this value or if it returns empty alert message if returned value is empty.

Answer Source

The dataType parameter in the ajax call tells jQuery what type to expect back from the server. You've specified json, but you are not returning JSON from the Flask handler so jQuery throws an error.

Either actually return JSON, or remove that parameter.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download