0

I was following a Tutorial about sending AJAX requests with jQuery in Flask which actually was successful. But after playing around with AJAX it seems like I have not understood everything about this system.

My js File:

$.ajax({
        data : {
            name : $('#nameInput').val(),
            email : $('#emailInput').val(),
            test : $('#test').val()

        },
        type : 'POST',
        url : '/process',
        contentType: 'application/json'
    })
    .done(function(data) {

        if (data.error) {
            $('#errorAlert').text(data.error).show();
            $('#successAlert').hide();
        }
        else {
            $('#successAlert').text(data.name).show();
            $('#errorAlert').hide();
        }

    });

Now my data has three text input fields, two of them are in a form, one of them is just an tag:

<form class="form-inline">
  <div class="form-group">
    <label class="sr-only" for="emailInput">Email address</label>
    <input type="email" class="form-control" id="emailInput" placeholder="Email">
  </div>
  <div class="form-group">
    <label class="sr-only" for="nameInput">Name</label>
    <input type="text" class="form-control" id="nameInput" placeholder="First Name">
  </div>
  <button type="submit" class="btn btn-default">Submit</button>
</form>
<br>
<input type="text" id="test" placeholder="Test">
<br>

Now if I am understanding correctly, then it does not matter for jquery where the input fields are in the HTML-document it will find my id-tag and bind it to my data-object. But for some reason when trying to read my post request in my flask app, it cant read my object.

Here is my flask @route function:

@app.route('/process', methods=['POST'])
def process():
test = request.form['test']
email = request.form['email']
name = request.form['name']

if name and email:
    newName = test[::-1]
    return jsonify({'name' : newName})
return jsonify({'error' : 'Missing data!'})

The weird part is that when removing all of my "test"-tags and leaving only email and name, my code works. Only if I put the test input in there and the jquery-line test:$('#test').val() and the line in my python code test = request.form['test'] it works.

What detail am I missing? I have tried a lot of things there

Helmut K.
  • 121
  • 1
  • 3
  • 11
  • add dataType: 'json' or take a look to [$.post](http://api.jquery.com/jquery.post/) – gaetanoM Mar 05 '19 at 21:35
  • One problem is that you're setting `contentType: 'application/json'` but you're sending `application/x-www-form-urlencoded`. Anyway, do proper debugging and simply log the content of `request.form` –  Mar 05 '19 at 21:35

0 Answers0