Evening all.
I am working on my final project and have a question about db.execute. When I run my SQL search the return always has the format {"key": value}. Is there any way to then extract the value as a string and assign it to a new variable?
I am attempting to pass a search parameter from the client to the server. Preform a search of my database on the server using db.execute. Then return the value from the database to the client and use this text to update the website.
Currently when the data is jsonify'ed and passed back it is still in the {"key": value} format and this all shows up in the website text.
Python code:
@app.route("/retrieveposts", methods=["POST"])
@login_required
def retrieveposts():
"""Retrieves a previous post so that the admin can make any edits
required"""
date = request.form.get("date")
print(date)
post = db.execute("SELECT post FROM posts WHERE date_of_post = :date_of_post",
date_of_post=date)
print(post)
if not post:
t = jsonify({"success": False})
return t
else:
f = jsonify({"success": True, "post": post})
return f
Javascript (Please ignore all my comments to myself and logs):
function retrievePost() {
console.log('is this thing on?');
// A new AJAX object
const ajax = new XMLHttpRequest();
// The target of the event listener passed in to the function as e
const date = document.querySelector('#dateofpost').value;
console.log(date);
// Sends the ajax POST request to the server to run the function at /votecheck
ajax.open('POST', '/retrieveposts', true);
// When the request is complete, and ajax returns, run this function
ajax.onload = function () {
console.log('returned ajax')
// Pasrses the JSON file and extracts the text from the response
const data = JSON.parse(ajax.responseText);
const post = data.post;
const stringpost = JSON.stringify(post);
console.log(stringpost);
if (data.success == true) {
console.log('else statement happened ok');
var text = document.getElementById('postedit').innerHTML;
console.log(text);
document.querySelector('#postedit').innerHTML = stringpost;
console.log(text);
//return false;
} else if (data.success == false) {
alert(`Unfortunately there were no story posts on that date`);
//return false;
}
}
const data = new FormData();
data.append('date', date)
console.log(data);
ajax.send(data);
console.log('ajax sent?');
return false;
};
var elDateofpost = document.getElementById('submitdate');
elDateofpost.addEventListener('click', retrievePost, false)
A further issue with this is that when the text appears in the text box on the site it only does so for a fraction of a second and then is replaced by the placeholder text almost immediately. Any help with this additional issue would be great.
Many thanks in advance
jsonify(post)
heref = jsonify({"success": True, "post": post})
?