Conor T Conor T - 3 days ago 8
jQuery Question

Why cant I POST into sqlite from AJAX?

Im trying to incorporate a local save feature into my Web App and every time I send data in any form I get the following error:

builtins.TypeError and then a stack trace in /SaveFile and jquery-3.1.1.js:9536 POST http://127.0.0.1:5000/SaveFile 500 (INTERNAL SERVER ERROR) in the console log when I run the app

I set up everthing in flask below as follows:

from flask import Flask, render_template, request
import sqlite3
import requests
from requests import Request
import json

DATABASE = 'data/data.db'

app = Flask(__name__)

db = sqlite3.connect(DATABASE)
cur = db.cursor()

cur.execute("CREATE TABLE IF NOT EXISTS myrecipes(id INTEGER PRIMARY KEY, name TEXT, rating TEXT, author TEXT, source TEXT)")


db.commit()

@app.route('/')
def index():
return render_template("index.html")

@app.route('/SaveFile', methods=['POST', 'GET'])
def SaveFile(data):
if request.method == 'POST':
cur.execute('INSERT INTO myrecipes(name) VALUES(?)', json.stringify(data))
db.commit()
return render_template('SaveFile.html')
if __name__ == "__main__":
app.debug = True
app.run()

#j=requests.get(url)


AJAX function:

function saveRecipe(title){

$.ajax({
type : "POST",
url : "/SaveFile",
data: { 'name': this.title },
success: function(data) {
console.log("correct");
},
error: function(err) { alert(err); }
});

}// Save end


Im sorry that I cant include more info in the post but im not even sure where im going wrong or what im missing, I added the table as I left that out of the code by mistake.

Answer

I see a couple things are incorrect here. You'll need to add a headers line into your AJAX method to get it to POST data to Flask. You'll also need to JSON.stringify the object to send like this:

function saveRecipe(title) {
    $.ajax({
        type: "POST",
        headers: {"Content-Type": "application/json"},
        url: "/SaveFile",
        data: JSON.stringify({name: title}),
        success: function(response) {
            console.log(response);
        },
        error: function(response, error) {
            console.log(response);
            console.log(error);
        }
    });
}

Within your Flask endpoint you're asking for a variable which is why you're getting a 500 error, instead the data must be accessed through the request.data object. Also, probably best for this method NOT to call render_template and to return JSON to your XHR method like so:

from Flask import jsonify


@app.route('/SaveFile', methods=['POST', 'GET'])
def SaveFile():
    send_back = {"status": "failed"}
    if request.method == 'POST':
        try:
            data = request.data
            cur.execute('INSERT INTO myrecipes(name) VALUES(?)', json.stringify(data["name"]))
            db.commit()
            send_back["status"] = "success"
        except Error as err:
            send_back["status"] = str(err)
    return jsonify(send_back)
Comments