AJAX Tutorial: 2 Player Tic-Tac-Toe Game (no database required)
If you haven’t read the first tutorial, the PHP version of this game without AJAX, then you should start there. This tutorial assumes you’ve already read the first one so I’m not going to explain how I actually go about programming the game. Instead this will focus on how you modify the original game so it works with AJAX. That means you won’t need to refresh the page between each player’s turn.
Download the Working Source Code
.zip archive
This is what you’ll be making 🙂
Getting jQuery
First thing is first we’ll need to get the jQuery library before we start updating any code. For those of you that don’t know, jQuery is code library that makes doing JavaScript quick and pretty painless. You can download or link to a copy offered on a Content Delivery Network (CDN) like Google Code. Personally I recommend downloading a copy if you’re going to post this game on a high traffic/visibility website. Sometimes if you link to a copy of jQuery on a CDN your site can experience lag and/or delays if the CDN is slow and your game won’t work at all if the CDN is down. On the other hand if you have a small website or limited space to store your files then there’s no need to download a copy of jQuery, linking to it is a better option. In this tutorial I’ve downloaded and included the jQuery file in the js folder of the .zip archive.
Setting Up For AJAX
Because we want our game to display using AJAX we need to create a new JavaScript file called hangman.js. This is what we’ll use to make all of our AJAX calls and respond to the player’s input.
Now that we have two JavaScript files we have to update our index.php file so it knows both of those JavaScript files are necessary to run the game. In thetag, under the link to our stylesheet, we add two lines of code that tell our browser to load our JavaScript files:
We also need to remove our $_SESSION[‘game’][‘tictactoe’] check from the top of our index file. Our AJAX calls will be running the game so it’s no longer necessary here. However we leave the session_start() at the top of the page so that if the player accidentally refreshes the page they don’t loose the game they had in progress.
Next we remove the code inside of our
Writing the Tic-tac-toe.js File
Now it’s time to jump into jQuery and AJAX.
$(document).ready(function() { //start the game when the page loads playGame(); });
jQuery uses a special function to check when the page has finished loading. Anything you put inside of this function will run as soon as the page is loaded, or in response to something someone has done on the page, like mouse clicks or using the keyboard. For this tutorial all we need it to do is call our AJAX function that will load and display the game to the content div on our index.php file.
/*** * Purpose: play tic-tac-toe * Preconditions: none * Postconditions: new game has started or existing game is in play ***/ function playGame() { $.ajax({ url: 'ajax/index.php', data: {type: 'playGame'}, success: function( data ) { $("#content").html(data); } }); }
Inside of our playGame() function we use AJAX to tell the browser to load our ajax file and send it some data (the type of action we’re doing, whether or not to start a new game, the player taking their turn). Then we use a success callback function to load the results of our ajax call onto the page. A callback function is a function that runs as a result of being called by another process. In this case our callback function, success, is loading the data we’ve retrieved through AJAX and putting it into the content div’s HTML property.
/*** * Purpose: place an X or O on the board * Preconditions: none * Postconditions: game status updated ***/ function makeMove() { var selected_spot = null; //find the first spot on the board they have an X or O inside of $(".board_spot").each(function() { if ($(this).val()) { //they have a value in this spot, break out of the loop selected_spot = $(this); return false; } }); //make sure they've selected a spot if (selected_spot == null) { alert("You must select a spot on the board first."); return false; } //make sure we only get an X or O value if ($(selected_spot).val() != "X" && $(selected_spot).val() != "O") { alert("Invalid selection made. Please try again."); return false; } //pass the spot and the value they selected to our ajax file $.ajax({ url: 'ajax/index.php', data: {type: 'playGame', spot:$(selected_spot).attr("name"), value:$(selected_spot).val()}, success: function( data ) { $("#content").html(data); } }); }
If we want to respond to someone trying to pick a spot we use a fairly similar process. First we loop through all of the input boxes on the page (we’ve added a call called board_spot to them in our displayBoard class function) and save the first one that has a value into our selected_spot variable. Then we check to make sure they’ve selected a spot and that the value in the spot is either an X or an O. Finally we send the spot they selected and the value to our ajax file.
/*** * Purpose: start a brand new game * Preconditions: none * Postconditions: new game has started ***/ function newGame() { $.ajax({ url: 'ajax/index.php', data: {type: 'playGame', newgame: true}, success: function( data ) { $("#content").html(data); } }); }
The last piece of our ajax file is the newGame function. When the game is over we want to make sure we use AJAX to update the game state and then refresh the page to a new game.
Writing the AJAX File
Now that our JavaScript file will send AJAX requests we need to write the file on the other end of the request — the file that responds to the data we’re sending it. Create a new folder and name is ajax. Inside of it make an index.php file. Inside of the file put the following: