Saving data in Javascript efficiency ?
Saving data in Javascript efficiency ?
I have a quick question about the most efficient way to update MySql from Javascript. I'm toying with making a javascript game and I want to save player data as the player plays the game. My question is which method of updating is more efficient. Saving the data each time data is updated or waiting to update data every so often?
I feel it's a bit of overkill to update the database each time a player takes a step or collects money but it seems the safest way to maintain continuity. The interval update seems be less strain on the database but easier to lose continuity.
I know a lot of the games from Zynga uses the interval method. For anyone that plays those games know that if you close the game or you lose connection to the server you can lose the last 5-10 minutes of progress.
I feel it's a bit of overkill to update the database each time a player takes a step or collects money but it seems the safest way to maintain continuity. The interval update seems be less strain on the database but easier to lose continuity.
I know a lot of the games from Zynga uses the interval method. For anyone that plays those games know that if you close the game or you lose connection to the server you can lose the last 5-10 minutes of progress.
Re: Saving data in Javascript efficiency ?
I`m sorry, Javascript is no server language, it only runs in the browser ( except the odd cases like node.js ) so if you don`t have a javascript server running like node.js ( which is C++ really... small detail ) there`s no real way to update your mysql db.
However, using javascript making ajax calls to your server is still possible. You can use any language like Java, PHP, ASP or what ever you want ( Ruby maybe? )
On the storage itself, you can store data locally and update the player every xx seconds, however, don`t ever break continuity, if players know they get updated every 10 seconds, make sure it`s every 10 seconds, else you better store every action on itself, or every 2 seconds. Also, there`s a difference for actions, collecting items or killing items should be continuous, however the updates for the statistics ( gold, resources ) can be done over a longer period of time, besides that stuff can be calculated in batches )
Other then that i wouldn`t really bother on intervals yet, make a game first before worrying about details
However, using javascript making ajax calls to your server is still possible. You can use any language like Java, PHP, ASP or what ever you want ( Ruby maybe? )
On the storage itself, you can store data locally and update the player every xx seconds, however, don`t ever break continuity, if players know they get updated every 10 seconds, make sure it`s every 10 seconds, else you better store every action on itself, or every 2 seconds. Also, there`s a difference for actions, collecting items or killing items should be continuous, however the updates for the statistics ( gold, resources ) can be done over a longer period of time, besides that stuff can be calculated in batches )
Other then that i wouldn`t really bother on intervals yet, make a game first before worrying about details
Re: Saving data in Javascript efficiency ?
The best thing to use would be jQuery to start of with:
http://jquery.com/
The second thing would be to use JSON and Ajax.
script.php
Another thing, when you're storing sessions, it's best to stop any session writing straight away in PHP. Otherwise pages will take forever to load.
About the constant updating. You would probably want to look into websockets or polling.
I've built loads of apps that poll a MySQL database and they run just fine even with loads of users. So polling is no problem with MySQL for the people who want to dissagree.
http://jquery.com/
The second thing would be to use JSON and Ajax.
Code: Select all
data = {
something : 'something\'s value',
anotherthing : 'anotherthing\'s value'
}
$.post('script.php', data, function()
{
alert('Sent');
});
Code: Select all
echo $_POST['something']; // something's value
echo $_POST['anotherthing']; // anotherthing's value
// mysql
mysq_query("UPDATE `table` SET `somethings` = '". mysql_real_escape_string($_POST['something']) ."' WHERE `anotherthing` = '". mysql_real_escape_string($_POST['anotherthing']) ."'");
Code: Select all
session_start();
session_write_close();
echo $_SESSION['key']; // works fine
$_SESSION['key'] = 'value'; // NOTE: will not work
About the constant updating. You would probably want to look into websockets or polling.
I've built loads of apps that poll a MySQL database and they run just fine even with loads of users. So polling is no problem with MySQL for the people who want to dissagree.
Code: Select all
// last update received
var lastUpdate = 0;
function whatever()
{
$.getJSON('script.php', { 'time' : lastUpdate }, function(data)
{
lastUpdate = data['time']; // update lastUpdate to the latest time retrieved
alert(data['message']);
setTimeout(function(){ whatever() }, 500); // Call function whatever() again after 0.5 seconds, put inside a function for compatibility with IE
});
}
Code: Select all
do
{
$query = mysql_query("SELECT * FROM `table` WHERE `time` > '". (int)$_GET['time'] .""); // field time as timestamp
}
while( mysql_num_rows($query) == 0 ) // keep looping until there is a result
echo json_encode(mysql_fetch_assoc($query)); // return json string with data
Fighting for peace is declaring war on war. If you want peace be peaceful.
- Jackolantern
- Posts: 10891
- Joined: Wed Jul 01, 2009 11:00 pm
Re: Saving data in Javascript efficiency ?
Yeah, updating every step is out of the question with AJAX unless players only take a step every 1 - 2 seconds. So in that case you would likely need to build up a batch of movements and send them periodically.
You could update every step with Websockets, but that would drastically change the whole direction of your project.
You could update every step with Websockets, but that would drastically change the whole direction of your project.
The indelible lord of tl;dr
Re: Saving data in Javascript efficiency ?
Oh yeah, you might want to put a sleep() or usleep() function in your database polling loop. Ohterwise the mysql server is going to go nutts.
0.05 seconds works just fine when running the mysql server on the same machine as your web server.
Fighting for peace is declaring war on war. If you want peace be peaceful.
Re: Saving data in Javascript efficiency ?
I guess I should have said I'm using AJAX to PHP to actually save the data. With JQUERY as my library.
I'll look into Polling and the dreaded Websocket methods. I guess it would be good to learn Sockets anyway.
The basic set up I have for the game now grabs the initial data from the server loads the vars into JS and all actions after that manipulate the vars. The updating to the server happens in the background when actions are taken (Traveling, Crafting Timers, Killing creatures, etc). Once every 5 minutes the JS calls and double checks it's variables against the sever then updates itself to the server values.
Is the above method viable? So far it seems like it's working as intended...of course there is no real load on the server right now.
I'll look into Polling and the dreaded Websocket methods. I guess it would be good to learn Sockets anyway.
The basic set up I have for the game now grabs the initial data from the server loads the vars into JS and all actions after that manipulate the vars. The updating to the server happens in the background when actions are taken (Traveling, Crafting Timers, Killing creatures, etc). Once every 5 minutes the JS calls and double checks it's variables against the sever then updates itself to the server values.
Is the above method viable? So far it seems like it's working as intended...of course there is no real load on the server right now.
- Jackolantern
- Posts: 10891
- Joined: Wed Jul 01, 2009 11:00 pm
Re: Saving data in Javascript efficiency ?
It depends on how often things are done. At the fastest (all on a single location machine), AJAX calls take 1 - 2 seconds round trip. On the internet it can only take longer than that, so provided there is a lot of time between actions, it would work fine.
As far as Websockets go, they couldn't be easier on the client side. The place where they are complicated is on the server, since you can't use a traditional web server to run them. They require a dedicated (and often nearly completely custom) socket server, oftentimes written in Java or node.js.
As far as Websockets go, they couldn't be easier on the client side. The place where they are complicated is on the server, since you can't use a traditional web server to run them. They require a dedicated (and often nearly completely custom) socket server, oftentimes written in Java or node.js.
The indelible lord of tl;dr
Re: Saving data in Javascript efficiency ?
For saving data the quickest way would probably be to send an Ajax call that doesn't return data. Then run a separate call to a polling script. This sometimes returns quicker as the connection is already there. Another thing is using POST goes way slower than using GET through Ajax.
Here's a PHP polling script I wrote that works:
Here's the JavaScript that calls it:
Here's a PHP polling script I wrote that works:
Code: Select all
session_start();
if( empty($_SESSION['player']) ) die();
session_write_close();
include("../../connect.php");
$_GET['timestamp'] = empty($_GET['timestamp']) ? 0 : (int)$_GET['timestamp'];
$_GET['room'] = empty($_GET['room']) ? 0 : (int)$_GET['room'];
$query = mysql_query("SELECT * FROM `chat` WHERE `timestamp` > '". $_GET['timestamp'] ."' AND `room` = '". $_GET['room'] ."'");
while( mysql_num_rows($query) == 0 )
{
usleep(50000);
set_time_limit(2);
$query = mysql_query("SELECT * FROM `chat` WHERE `timestamp` > '". $_GET['timestamp'] ."' AND `room` = '". $_GET['room'] ."'");
}
$result = array( 'timestamp' => 0, 'results' => array() );
while( $array = mysql_fetch_array($query) )
{
$result['timestamp'] = $array['timestamp'];
$pQuery = mysql_query("SELECT `name` FROM `players` WHERE `id` = '{$array['player_id']}'");
$pArray = mysql_fetch_assoc($pQuery);
$result['results'][] = array( 'time' => date("H:i:s", $array['timestamp']), 'user' => $pArray['name'], 'message' => $array['message'] );
}
echo json_encode( $result ); Code: Select all
chat = {
timestamp : 0,
room : 0,
get : function()
{
if( typeof(chat.getRequest) == 'object' )
{
chat.getRequest.abort();
}
chat.getRequest = $.getJSON(
"assets/php/chatGet.php?timestamp=" + chat.timestamp + '&room=' + chat.room,
function(data)
{
if( data != null && data.hasOwnProperty('results') )
{
for( var i in data['results'] )
{
$("#chat .messages").html( $("#chat .messages").html() +
'<span>' + data['results'][i]['time'] + '</span>' +
'<span>' + data['results'][i]['user'] + ' said</span>' +
'<span>' + data['results'][i]['message'] + '</span><br />' );
}
chat.timestamp = data['timestamp'];
$('#chat .messages').animate( {scrollTop: $('#chat .messages').attr('scrollHeight') }, 'slow' );
}
setTimeout( function() { chat.get() }, 1 );
}
);
},
send : function()
{
$('#chatInput').attr( 'disabled', 'disabled' );
$.ajax(
{
url : "assets/php/chatPost.php?room="+ chat.room +"&message="+ $('#chatInput').val(),
complete : function()
{
$('#chatInput').val('');
$('#chatInput').attr( 'disabled', '' );
$('#chat input').focus( );
}
});
},
check : function()
{
if( typeof(chat.getRequest) != 'object' ) { alert( typeof(chat.getRequest) ) } else { return true };
setTimeout( function() { chat.check() }, 1000 )
}
}Fighting for peace is declaring war on war. If you want peace be peaceful.
- hallsofvallhalla
- Site Admin
- Posts: 12026
- Joined: Wed Apr 22, 2009 11:29 pm
Re: Saving data in Javascript efficiency ?
With JQUERY as my library.

haha i am kidding no one go ballistic on me
Chris you are a coding machine!