0

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

1
  • Does it help if you jsonify(post) here f = jsonify({"success": True, "post": post})? Dec 2 '18 at 2:57
1

Much like you would have seen in the CS50 Finance, db.execute returns a list of dict objects. So just as you accessed the cash value for your index page using rows[0]['cash'] you need to access your value by grabbing the first dict item using post[0] and then grab the value of the key "post": post[0]["post"]

1
  • Thanks again. I believe we discussed this on the discord too. It is accessing the correct data now. However the text still only appears in the text box momentarily before being replaced with the placeholder text again. The process is also only about 25% reliable, returning the ajax request about 1 in 4 attempts.
    – Ben Rogers
    Dec 2 '18 at 8:25

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .