Sunday 17 July 2011

Snippet - AJAX

This is useful for many things with HTML5 game development. You could use it as a means to pass a user's score to a php script which adds it to a database.
Or you could do it the other way round, and make it get the highscores from the database, and the function would return the script's response, which could be used to then write the scores on the canvas, or wherever.


For Example:
ajaxCall("addScore.php?username=Slash&score=500");

That would have called the php script in addScore.php, and passed in the username and score parameters.
The php script could have simply been written to take those parameters with $_GET['username'] and $_GET['score'], and insert the values into a MySQL database.


This is just a snippet. I might later make a full tutorial on how to keep a scoreboard. But this function will allow you to call any php script with AJAX and use it's responseText if necessary.


The JavaScript Code:
function ajaxCall(scriptURL) {
  var xmlhttp;
  if(window.XMLHttpRequest)
  {
    xmlhttp=new XMLHttpRequest();
  }
  else
  {
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function()
  {
     if (xmlhttp.readyState==4 && xmlhttp.status==200)
     {
       return xmlhttp.responseText;
     }
  }
  
  xmlhttp.open("GET", scriptURL, true);
  xmlhttp.send();
}


Example PHP Script:
// set up connection
$con = mysql_connect("localhost", "DBuser","DBpass") or die(mysql_error());
mysql_select_db("DBname", $con) or die(mysql_error());

// Get params from the url used
$username = mysql_real_escape_string($_GET['username']);
$score = mysql_real_escape_string($_GET['score']);

// insert the score into the scores table for the user
$query = "INSERT INTO scores (username, score) VALUES ('" . $username . "', '" . $score . "')";
mysql_query($query, $con) or die(mysql_error());


This example PHP script will work for the stuff I mentioned earlier, calling the JavaScript function with something like ajaxCall("addScore.php?username=Slash&score=500");

Note that this is an example to show what goes on with AJAX. However, in a professional situation, PDO would be used rather than MySQL, and jQuery would often be used in the JavaScript. Libraries are used a lot because they are already optimized code and you also have less code to write yourself.

2 comments:

  1. This comment has been removed by a blog administrator.

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete