0

Hi I'm working on my final project, an online two player game based on the cs5o Finace distribution code, I got tic-tac-toe to work and am now trying to update the playing field displayed to the user via ajax. I have included my javascript, python and html code below. My issue is that when a user submits a play, the html in my javascript code shows up above the default html for that (so the playing field is displayed twice) and without the changes the player would have made.

Ex: 1.I load the game by reloading page 2.The default html shows up with all the moves that have been made so far. 3.the player submits a play for an empty field (field 3 is empty and player 2 asks that an 'O' be put there) 4.The javascript submits a POST request to "/convert" (status code -200) and successfully updates the database. 5.The html in my javascript code shows up (without the page reloading), but the move the player just made isn't included.

If anyone would be willing to help me I would very much appreciate it!!!!!!

Javascript:

document.addEventListener('DOMContentLoaded', () => {
    document.querySelector('#tttform').onsubmit = () => {
        //Initializing new request
        const request = new XMLHttpRequest();
        const play = document.querySelector('#tttplay').value;
        request.open('POST', '/convert');

        //Callback function when request is completed
        request.onload = () => {

            //Exract JSON data from request
            const data = JSON.parse(request.responseText);

            //Update the result div
            if(data.success) {
                const contents = '<table class="ttttable"><tr><td>One</td><td>Two</td><td>Three</td></tr><tr><td>{{ data["one"] }}</td><td>{{ data["two"] }}</td><td>{{ data["three"] }}</td></tr><tr><td>Four</td><td>Five</td><td>Six</td></tr><tr><td>{{ data["four"] }}</td><td>{{ data["five"] }}</td><td>{{ data["six"] }}</td></tr><tr><td>Seven</td><td>Eight</td><td>Nine</td></tr><tr><td>{{ data["seven"] }}</td><td>{{ data["eight"] }}</td><td>{{ data["nine"] }}</td></tr></table>';
                document.querySelector('#tttfield').innerHTML = contents;
            }
            else {
                document.querySelector('#tttfield').innerHTML = 'There was an error.';
            }
        };

    //Add data to send with request
    const data = new FormData();
    data.append('play', play);

    request.send(data);
    return false;
    };

});

Python for "/tictactoe":

@app.route("/tictactoe", methods=["GET", "POST"])
@login_required
def tictactoe():

    if request.method == "GET":
        g = db.execute("SELECT * FROM games WHERE id = :game", game=session['gameid'])
        gInfo =g[0]
        t = db.execute("SELECT * FROM tictactoe WHERE id = :game", game=session['gameid'])
        tInfo = t[0]
        p = gInfo['PlayerOne']
        if tInfo['status'] == 'finished':
            a = check_win_conditions(tInfo, 3, 3)
            if a == 'X':
                session['winner'] = a
                return redirect("/game-over")

            if a == 'O':
                session['winner'] = a
                return redirect("/game-over")

            b = check_draw(tInfo)
            if b == 1:
                session['winner'] = 'D'
                return redirect("/game-over")
        data = tInfo

        return render_template('tictactoe.html', gInfo = gInfo, tInfo = tInfo, turn = p, data = data)

Python code for "/convert":

@app.route("/convert", methods=["GET", "POST"])
@login_required
def bts():

    if request.method == "POST":

        g = db.execute("SELECT * FROM games WHERE id = :game", game=session['gameid'])
        gInfo =g[0]
        f = open("gInfo.txt", "w")
        f.write( str(gInfo) )
        f.close()
        t = db.execute("SELECT * FROM tictactoe WHERE id = :game", game=session['gameid'])
        tInfo = t[0]
        fp = request.form.get("play")
        p = wordify(fp)
        n = db.execute("SELECT username FROM users WHERE id = :uid", uid=session['user_id'])
        u = n[0]

        turn = gInfo['PlayerOne']

        if tInfo[p] == '_':
            if u['username'] == gInfo['PlayerOne']:
                tInfo[p] = 'X'
                db.execute("UPDATE tictactoe SET :p = :v", p=p, v=tInfo[p])
                turn = gInfo['PlayerTwo']
            if u['username'] == gInfo['PlayerTwo']:
                tInfo[p] = 'O'
                db.execute("UPDATE tictactoe SET :p = :v", p=p, v=tInfo[p])
                turn = gInfo['PlayerOne']

        a = check_win_conditions(tInfo, 3, 3)
        if a == 'X':
            session['winner'] = a
            return redirect("/game-over")

        if a == 'O':
            session['winner'] = a
            return redirect("/game-over")

        b = check_draw(tInfo)
        if b == 1:
            session['winner'] = 'D'
            return redirect("/game-over")

        data = tInfo

        return jsonify({"success": True, "one": data["one"], "two": data["two"], "three": data["three"]})

and

HTML code for tictactoe.html:

{% extends "layout.html" %}

{% block title %}
    Tic-Tac-Toe
{% endblock %}

 {% block main %}
    <div class='tttgamemain'>
        <script type="text/javascript">
//HERE IS WHERE THE JAVASCRIPT CODE IS!!!
</script>
        <div>
            <h1>Tic-Tac-Toe</h1>
        </div>
        <div>
            <h3>{{ gInfo['PlayerOne'] }} VS {{ gInfo['PlayerTwo'] }}</h3>
        </div>
        <div id="tttfield">

        </div>
        <div >
            <h4>It is {{ turn }}'s turn:</h4>
            <form id='tttform'action="/tictactoe" method="post">
                                <table class="ttttable">
                    <tr>
                        <td>One</td><td>Two</td><td>Three</td>
                    </tr>
                    <tr>
                        <td>{{ tInfo['one'] }}</td>
                        <td>{{ tInfo['two'] }}</td>
                        <td>{{ tInfo['three'] }}</td>
                    </tr>
                    <tr>
                        <td>Four</td><td>Five</td><td>Six</td>
                    </tr>
                    <tr>
                        <td>{{ tInfo['four'] }}</td>
                        <td>{{ tInfo['five'] }}</td>
                        <td>{{ tInfo['six'] }}</td>
                    </tr>
                    <tr>
                        <td>Seven</td><td>Eight</td><td>Nine</td>
                    </tr>
                    <tr>
                        <td>{{ tInfo['seven'] }}</td>
                        <td>{{ tInfo['eight'] }}</td>
                        <td>{{ tInfo['nine'] }}</td>
                    </tr>
                </table>
                <div class="form-group">
                    <input  id='tttplay' onkeyup='resetTimer = true' autocomplete="off" autofocus class="form-control" name="play" placeholder="Field Number" type="text">
                </div>
                <button class="btn btn-primary" type="submit" border='0'><img src="/static/playbutton.jpg" alt="PLAY!"></button>
            </form>
        </div>
    </div>
{% endblock %}

PS: I know there are a couple unclean aspects to my code(/convert having a GET method, etc.) I've been going back and forth between diffrent options and will clean those up as soon as I have a working piece of code! Thank you soooooooooo much for getting this far!

You must log in to answer this question.

Browse other questions tagged .