Search code examples
javascriptajaxasynchronousfetch

json field not getting sent to the server using fetch


I have this form being submitted to a flask app using AJAX fetch method but for some reason it doesn't go through to the server, i can alert the input no problem.

<html>
    <head>
        <title>TODO App</title>
    </head>
    <style>
        .hidden {
            display: none;
        }
    </style>
    <body>
        <form id="form" >
            <input type="text" id="description" name="description" />
            <input type="submit" value="Create" />
        </form>
        <div id="error" class="hidden">Something went wrong</div>
        <uL id="todos">
            {%for d in data%}
            <li>{{d.description}}</li>
            {%endfor%}
        </uL>
    </body>
    <script>
        document.getElementById('form').onsubmit = function(e) {
            e.preventDefault();
            //alert(document.getElementById('description').value);
            let desc = document.getElementById('description').value;
            alert(desc);
            fetch('/todos/create', {
                method: 'POST',
                body: JSON.stringify({
                    'description': desc
                }),
                headers: {
                    'content-type': 'application/json'
                }
            })
            .then(function (response){
                return response.json();
            })
            .then(function(jsonResponse){
                console.log(jsonResponse);
                const liItem = document.createElement('LI');
                liItem.innerHTML = jsonResponse['description'];
                document.getElementById('todos').appendChild(liItem);
            })
            .catch(function(){
                document.getElementById('error').className = '';
            })
        }
    </script>
</html>

the python function that listens for this if needed:

@app.route('/todos/create', methods=['POST'])
def create_todo():
  #description = request.form.get('description', '')
  description = request.form.get_json()['description']
  todo = Todo(description=description)
  db.session.add(todo)
  db.session.commit()
  #return redirect(url_for('index'))
  return jsonfiy({
    'description' : todo.description
  })

the text input with the id = description is the one in question i always get the error message that's specified in the catch. not sure what the problem is ! when the python function had a default value in case the field was not filled the item would get added to the database no problem but when i removed the default value problems arise because input is not carried over tot he server


Solution

  • so the problem was using

    request.form.get_json()
    

    in the python function where it should actually be:

    request.get_json()
    

    that fixed it thanks for all the comments.