Ryan Ryan - 27 days ago 4x
Ajax Question

AJAX table update script

I'm making an online tile based game and I have just finished scripting the piece of code that takes the coordinates of where you are standing and builds the surroundings (tiles) around you (the game is made using a table with many cells that hold the tiles).

I need some help creating a bit of AJAX that can refresh my table every now and then (lets sat every 2 seconds for the sake of this question). I have no experience with AJAX and there would be no point learning it all (even though id like too) as I will only be using it for this small part of my game, plus I do not have time.

This is how my game is set up:

Some php that gets info on the character.*

Some html that displays the data in a graphical form.

So what I need is some AJAX that refreshes the php then the html every 2 seconds.


You should probably use jQuery, or Prototype JS. These libraries can both do 'some ajax'. If you are new to development, and this is a one-off project, I would suggest using Prototype.

In Prototype, you could have a function that does the ajax work, and a function that calls Prototype's periodicalExecuter with the work-doing function name as it's callback parameter, as in the example below. You need to send some parameters to the php script, and put the response into some element(s) on the page, once every x seconds. This should get you started:

    <script src="/js/Prototype.js">
    //calls renderResponse on completion of the AJAX post to the specified URL
    function sendRequest(parameters,URLEndpoint){
    	var myAjax = new Ajax.Request
    						 method: 'post', 
    						 postBody: parameters, 
    						 onSuccess: renderResponse

    //replace contents of 'character' div or whatever with output from PHP script
    function renderResponse(response){
       var el = $(characterTable); 
       elementId.innerHTML = resp.responseText;

    //execute sendRequest every 2 seconds
    function periodicalUpdate() {
        new PeriodicalExecuter(sendRequest('monkeys=2&carrots=7','http://mywebsite.com/game.php'), 2);

There's a jQuery plugin function that does the same job as PeriodicUpdate. I haven't tried it but it looks compelling: