1

Im having trouble putting some simple data from and html page into a MySQL database

the error I am receiving is

werkzeug.exceptions.HTTPException.wrap.<locals>.newcls: 400 Bad Request: KeyError: 'matchID'

This is the python code I am using to push it into the MySQL database

import mysql.connector as conn
from flask import (
render_template,
Flask,
jsonify,
request,
abort as ab
)

app = Flask(__name__)

def conn_db():
return conn.connect(user='***********',
                    password='***********',
                    host='***********',
                    database='**********'
                    )


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


@app.route('/addScore', methods=['POST'])
def add_score():
cnx = conn_db()
cursor = cnx.cursor()
MatchID = request.form['matchID']
Home_Score = request.form['homeScore']
Away_Score = request.form['awayScore']

print("Updating score")
if not request.json:
    ab(400)

cursor.execute("INSERT INTO scores (Match_ID, Home_Score, Away_Score) VALUES (%s,%s,%s,%s)",
               (MatchID, Home_Score, Away_Score))




if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0')

And this is the html with the ajax I am using

<!DOCTYPE html>
<html>

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>

<body>

<h1>Scores</h1>


<form method="POST">
<label>Match ID :</label>
<input id="matchID" name="matchID" required type="number"><br>
<label>Home Score:</label>
<input id="homeScore" name="homeScore" required type="number"><br>
<label>Away Score:</label>
<input id="awayScore" name="awayScore" required type="number"><br>
</form>

<button id="addScoreButton">Add score</button>
<button id="retrieveScoreButton">Retrieve all scores</button>
<br>

<div id="Scores">
<ul id="scoresList">
</ul>
</div>

<script>
$(document).ready(function () {
        var matchID = $('#matchID').val();
        var homeScore = $('#homeScore').val();
        var awayScore = $('#awayScore').val();

        $("#addScoreButton").click(function () {
                $.ajax({
                        type: 'POST',
                        data: {MatchID: matchID, Home_Score: homeScore, Away_Score: awayScore},
                        url: "/addScore",
                        success: added,
                        error: showError
                    }
                );
            }
        );
    }
);


$(document).ready(function () {
        $("#retrieveScoreButton").click(function () {
                console.log(id);
                $.ajax({
                        type: 'GET',
                        dataType: "json",
                        url: "/allScores",
                        success: showScores,
                        error: showError
                    }
                );
            }
        );
    }
);

function showScores(responseData) {
    $.each(responseData.matches, function (scores) {
            $("#scoresList").append("<li type='square'>" +
                "ScoreID: " + scores.Score_ID +
                "Match Number: " + scores.Match_ID +
                "Home: " + scores.Home_Score +
                "Away: " + scores.Away_Score
            );
            $("#scoresList").append("</li>");
        }
    );
}

function added() {
    alert("Added to db");
}

function showError() {
    alert("failure");
}


</script>

</body>

</html>

Any help at all is greatly appreciated,

I have included the sql for created the scores table I am adding into, see below

CREATE TABLE Scores ( Score_ID int NOT NULL AUTO_INCREMENT, Match_ID int NOT NULL, Home_Score int NOT NULL, Away_Score int NOT NULL, PRIMARY KEY (Score_ID) );

1 Answer 1

1

You're getting form values on document.ready when they are not defined yet:

$(document).ready(function () {
        var matchID = $('#matchID').val();
        var homeScore = $('#homeScore').val();
        var awayScore = $('#awayScore').val();

You have to get the values when your form is submitted so the required attributes on the fields would respected.

So you have to change your html:

<form method="POST">
  <label>Match ID :</label>
  <input id="matchID" name="matchID" required type="number"><br>
  <label>Home Score:</label>
  <input id="homeScore" name="homeScore" required type="number"><br>
  <label>Away Score:</label>
  <input id="awayScore" name="awayScore" required type="number"><br>
  <button id="addScoreButton">Add score</button>
</form>

<button id="retrieveScoreButton">Retrieve all scores</button>

And your JavaScript (please notice the comments):

$(document).ready(function() {

  $(document).on('submit', 'form', function() {
    // Here you get the values:
    var matchID = $('#matchID').val();
    var homeScore = $('#homeScore').val();
    var awayScore = $('#awayScore').val();

    // OR
    // you have a simpler option:
    // var data = this.serialize();

    $.ajax({
      type: 'POST',
      data: {
        MatchID: matchID,
        Home_Score: homeScore,
        Away_Score: awayScore
      },
      // OR
      // data: data, // if you use the form serialization above
      url: "/addScore",
      success: added,
      error: showError
    });
  });


  $("#retrieveScoreButton").click(function() {
    console.log(id);
    $.ajax({
      type: 'GET',
      dataType: "json",
      url: "/allScores",
      success: showScores,
      error: showError
    });
  });

});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.