0

I trying to create a sticky notes app. I'm stuck at a part where I try to send data in JSON format to Flask but when I print the POST request sent by the web page it it shows None Here is my code:

<head>
    <title>Ajax Notes</title>
    <meta charset="utf-8">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='styles.css') }}">
</head>

<body>

<div id="input_form">
    <h2>Add a note</h2>
    <form id="add_note" action="/add" method="post">
        <input id="input_title" type="text" name="input_title" style="width: 250px;" placeholder="Title">
        <input id="input_note" type="text" name="input_note" style="width: 250px; height:200px;" placeholder="Note">
        <input id="submit_note" type="submit" value="Add Note">
    </form>
</div>

{% for note in all_notes %}
    <div id='note'>
        <form id="delete_note" action="/delete" method="post">
            <input type="hidden" name="delete_note_id" value="{{ note['id'] }}">
            <input id="delete_button" type="submit" name="delete" value="X">
        </form>
        <form id="edit_form" action='' method="post">
            <h4 id="note_id" name="id" hidden>{{ note['id'] }}</h4>
            <h3 contenteditable="true" name="note_title" id="note_title">{{ note['title'] }}</h3><br><br>
            <p contenteditable="true" name="note_note" id="note_note">{{ note['note'] }}</p>
        </form>
    </div>
{% endfor %}





<script type="text/javascript">
    $(document).ready(function(){
            $(this).on('click','#note', function(){
                    var $changes = {
                    id : $('h4', this).text().trim(),
                    title : $('h3', this).text().trim(),
                    note : $('p', this).text().trim()
                };

                // console.log($("#edit_form").serialize())
                // console.log(JSON.stringify($changes))
                $.post('/edit', JSON.stringify($changes), function(res){console.log(res)}, 'json' );

                return false
        })
    });

</script>



</body>

What am I doing wrong or is there any other approach to this? I thought about using forms but it required a lot of jQuery which am not very familiar with and I have very less time left leaving lesser options for me. Here is my Flask app main file:

from flask import Flask, request, session, render_template, redirect
from mysqlconnection import MySQLConnector

app = Flask(__name__)
app.secret_key = "the biggest secret!"
mysql = MySQLConnector(app, 'notes')


def add_note(title, note):
    query = "INSERT INTO notes (title, note) VALUES(:title, :note)"
    data = {
        'title' : title,
        'note' : note
    }
    mysql.query_db(query, data)


def edit_note(id, title, note):
    query = "UPDATE notes SET title = :title, note = :note WHERE id = :id"
    data = {
        'id' : id,
        'title' : title,
        'note' : note
    }
    mysql.query_db(query, data)

def delete_note(id):
    query = "DELETE FROM notes WHERE id = :id"
    data = {
        'id' : id
    }
    mysql.query_db(query, data)


def all_notes():
    query = "SELECT * FROM notes"
    return mysql.query_db(query)


@app.route('/')
def index():
    notes = all_notes()
    return render_template('index.html', all_notes=notes)


@app.route('/add', methods=['POST'])
def add():
    title = request.form['input_title']
    note = request.form['input_note']
    add_note(title, note)
    return redirect('/')

@app.route('/delete', methods=['POST'])
def delete():
    note_id = int(request.form['delete_note_id'])
    delete_note(note_id)
    return redirect('/')


@app.route('/edit', methods=['POST'])
def edit():
    print request.json
    # note_id = request.form['edit_note_id']
    # title = request.form['edit_title']
    # note = request.form['edit_note']
    # edit_note(note_id, title, note)
    return redirect('/')



if __name__ == "__main__":
    app.run(debug=True)
Ketan
  • 115
  • 2
  • 10
  • Check out [this guy's answer](http://stackoverflow.com/a/20001283/1227353). As he points out, you should use `request.get_json()` instead of the `.json` property. – rcplusplus Jul 13 '16 at 01:19
  • 1
    I tried that before posting the question and tried it again now and it also returns `None`. – Ketan Jul 13 '16 at 01:26
  • 1
    Ok, I used force parameter to `request.get_json(force=True)` and it worked. Interesting! Thanks :) – Ketan Jul 13 '16 at 01:28

0 Answers0