Chapter 8, Exercise 2 – POSTing Scores With AJAX

Write a routine to post the player’s score to a fictional server address using jQuery’s ajax method. Post the score at the end of each level and write a checksum function to add basic security using your method of choice.

Assume we’re posting high scores to a directory called
We’re going to add a checksum when we post the score. The checksum value will be a simple modulus of the score. We could even use the number of bubbles the player fired and pass that parameter along with the score. This would give us another level of security: if we see suspicious scores, then we can see if the number of bubbles is realistic. If the player has used 100, or only 5, then it’s likely that something’s wrong.

POSTing the score will happen inside the endGame function in game.js:

var endGame = function(hasWon){
  if(score > highScore){
    highScore = score;
    score = 0;
    level = 0;
  $("#board .bubble").remove();
    url : '',
    data : {
      score : score,
      bubbles : numBubbles,
      cs : score % numBubbles
    type : 'POST',
    success : function(response){

We’re using jQuery’s AJAX method ( to POST the score, with the parameter “cs” containing our checksum. The parameters, in brief, are:

url : the url to post the score to
data : a JSON object containing our three parameters of score, number of bubbles, and checksum
type : POST, rather than GET
success : a function to call once the POST has been completed. This simply logs the response to the console, but in a full game you’re likely to want to do something with the result, such as show the user a confirmation message that their score has been saved.

If you put this into your game and keep the URL at you should see a message saying either “Score posted”. Try messing around with the checksum or posting a fake score and you’ll get a “Nice try” message instead.

Leave a Reply