Ajax

Reddit Outage - Promoting Ron Paul

Tagged:  

I just went to Reddit to see what was happening on the social network to find that the network is down (it is having a 503 - service not available issue). It is possible that the outage is due to some type of upgrade, but I'm not sure.

What I really thought was interesting is that Reddit has a link to Ron Paul's web site. Could you imagine the outcry from half the Digg community if they did the same thing? I'm not sure if this means that they are supporting Ron Paul or just pandering to their audience as Ron Paul has a huge support on the internet (although it hasn't translated to votes). Either way it is interesting to see how Reddit does not seem to have the same problem with Ron Paul content as Digg does.

Update: Reddit appears to be back up.

Yahoo! and MySpace - Games and Partnerships

Tagged:  

A lot is happening over at MySpace and Yahoo! these days.

First MySpace has launched a new game section that is loaded with Flash games including multi-player games. Warning many of these games will cause a lack of productivity. As is normal on MySpace you can add games that you like to your profile to share it with your friends (although can you imagine how much longer this could make some profiles load). You can click here to go to the games.

Even bigger news is the possibility of a partnership between News Corp (owners of MySpace) and Yahoo. Below is an excerpt of the Mashable post of the rumored partnership.

A report out this afternoon in The Wall Street Journal pumps life back into the rumor that Yahoo and News Corp are negotiating a deal that would trade MySpace and other Fox Interactive properties for a significant stake in Yahoo.

According to the Journal, the negotiations hinge on valuations; News Corp wants MySpace to be valued between $6 and $10 billion, while Yahoo needs to come in with a valuation that beats Microsoft’s $44.6 billion offer to stand any chance. Adding up the numbers between MySpace and other News Corp properties such as IGN, plus a likely infusion of cash, the WSJ says the stake in Yahoo could be more than 20 percent.

The rumor of a News Corp-Yahoo alliance is nothing new – there was significant chatter about the possibilities as recently as last summer. But with Yahoo seemingly desperate to avoid falling into Microsoft’s hands, it’s not surprising they are resuming talks.

Once again, I’m left not seeing a way that any sort of News Corp alliance is going to maximize value for shareholders of either company, especially with Yahoo and News Corp both going into the talks with valuation numbers grounded in nothing other than self-interest. Similar to Microsoft making a relatively small investment in Facebook that valued the company at $15 billion – just because Yahoo and News Corp say the deal makes Yahoo worth $50 billion and MySpace worth $10 billion doesn’t mean the public markets will see it that way (which, is all that really matters).

You can read more about it at Mashable.

I would love to hear your thoughts on all of this news. As always you can either comment on it or you can write your own post on this blog if you sign-up for a free account.

Simple AJAX chat in PHP

Tagged:  

Over at the .NET Butchering (and JAVA messes) blog they have posted a very good tutorial on creating a Chat application in PHP using Ajax. In Web 2.0 social applications chat is very often a desired feature.

Below is an excerpt from the tutorial.

The first thing to be done is creating MySQL tables:



CREATE TABLE `db_name`.`chat_rooms` (

`id` int(10) unsigned NOT NULL auto_increment,

`name` varchar(45) NOT NULL,

`description` text NOT NULL,

`table_name` varchar(45) NOT NULL,

PRIMARY KEY (`id`)

) ENGINE=InnoDB DEFAULT CHARSET=latin1;



CREATE TABLE `db_name`.`roomX` (

`id` int(10) unsigned NOT NULL auto_increment,

`date` datetime NOT NULL,

`message` text NOT NULL,

`user` varchar(45) NOT NULL,

PRIMARY KEY (`id`)

) ENGINE=InnoDB DEFAULT CHARSET=latin1;

The first table, chat_rooms, contains a list of all available chat rooms, used to know wich table name will be used for each room. The second one, roomX is a template for a "chat room-like" table: it contains the date (date+time) of each message, the message itself and the user that inputed it (actually it should be an integer, that refers to an appropriate users table, but this is simple version of the script without logging features).

The first thing we're gonna do is execute those SQL scripts (we will be using MySQL and PHP native methods) replacing "roomX" with i.e. "friends_table", and after that we're going to populate the first table, to add an available chat room:



INSERT INTO chat_rooms(name,description,table_name)

VALUES("Friends chat","Comment...","friends_table");

The next step is to compose the "web application". Let's see this picture:

We will use a main page, chat.php, a dinamically reloaded page, room.php and a simple iframe with inside the page sender.php with some controls to post a message.

Let's see chat.php, removing all HTML stuff (like header and formatting, that's up to you):



<?php

session_start();

/* probabily login stuff */

$_SESSION['chat_time'] = $date;

?>

<script type="text/javascript" src="timer.js"></script>

<script type="text/javascript" src="httpRequest.js"></script>

<script language="javascript">

var chatRoomId=<?=$charRoomChoosen?>;

</script>

<body onload="InitializeTimer(); StartTheTimer();">

<div id="chatText" style="overflow:auto;"></div>

<iframe src="sender.php" name="msgFrame"></iframe>

</body>

We'll talk further about the session variable chat_time; I've added 2 javascript scripts: the first one is a simple timer, the second one contains some methods to make HTTP requests.
This is httpRequest.js:



var xmlHttp;



function loadURL()

{

xmlHttp=GetXmlHttpObject()

if (xmlHttp==null)

{

alert ("Browser does not support HTTP Request")

return

}

var url="room.php?chatRoomId="+charRoomId;

xmlHttp.onreadystatechange=stateChanged;

xmlHttp.open("GET",url,true);

xmlHttp.send(null)

}



function stateChanged()

{

if (xmlHttp.readyState==4 xmlHttp.readyState=="complete")

{

/* trim message */

var newlines = xmlHttp.responseText.replace(/^\s+\s+$/g,"");

if(newlines!='')

{

var html = document.getElementById("chatText").innerHTML;

document.getElementById("chatText").innerHTML = html + newlines;

document.getElementById("chatText").scrollTop=20000000;

}



}

}



function GetXmlHttpObject()

{

var xmlHttp=null;

try

{

// Firefox, Opera 8.0+, Safari

xmlHttp=new XMLHttpRequest();

}

catch (e)

{

//Internet Explorer

try

{xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");}

catch (e){xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");}

}

return xmlHttp;

}

This class does an HTTP request (using Firefox, Explorer and other browser Request objects), as I explained in the [Javascript]XML Loading post, and writes the result inside the DIV with id chatText, calling the room.php script (that actually outputs last message sent to the room). The charRoomId used as a parameter of the calling method, is a global variable defined in the chat.php header using a PHP variabile (it should be a $_REQUEST variable).

As we are using asyncronous calls, we need a component that recalls this request periodically. This is the code below (timer.js):



var secs;

var timerID = null;

var timerRunning = false;

var delay = 500;



function InitializeTimer()

{

// Set the length of the timer, in seconds

secs = 1;

StopTheClock();

StartTheTimer();

}



function StopTheClock()

{

if(timerRunning)

clearTimeout(timerID);

timerRunning = false;

}



function StartTheTimer()

{

if (secs==0)

{

StopTheClock();

// Here's where you put something useful that's

// supposed to happen after the allotted time.

// For example, you could display a message:

loadURL();

secs = 1;

timerRunning = true;

timerID = self.setTimeout("StartTheTimer()", delay);

}

else

{

self.status = secs;

secs = secs - 1;

timerRunning = true;

timerID = self.setTimeout("StartTheTimer()", delay);

}

}

This is a timer, called from the chat.php page with onLoad method, that recalls each delay milliseconds the function loadURL() function, defined inside the previous js file.

Now let's see what is inside the chat.php file:



<?php



/* **************** SESSION VARIABLES **************************** */

session_start();



if(!isset($_SESSION['chat_time']))

{

$_SESSION['chat_time'] = date("Y-m-d H:i:s");

$_SESSION['chat_time_delete'] = time();

}





/************** DB connection ********************+*/

$db_user = "root";

$db_password = "root1";

$db_host ="localhost";

$connection = mysql_connect($db_host,$db_user,$db_password);

mysql_select_db("test",$connection);



/********** RETRIEVES THE NAME OF THE CHAT ROOM TABLE NAME **********/

function getChatTableName($connection,$chatRoomId)

{

/* recupera il nome della tabella della chat room */

$query = "SELECT table_name FROM chat_rooms WHERE id = '".$chatRoomId."'";

$result = mysql_query($query, $connection);

$tableName = NULL;

while($row=mysql_fetch_array($result))

{

$tableName = $row['table_name'];

}



if($tableName==NULL)

{

return NULL;

}



return $tableName;

}



/******************* MESSAGE VISUALIZATION ********************************/





$tableName = getChatTableName($connection,$_REQUEST['chatRoomId']);



if($tableName==NULL)

{

echo "Error selection char room.";

exit();

}

$login_date = $_SESSION['chat_time'];



/* load messages */

$query = "SELECT c.message, c.date, c.user FROM ".$tableName." c WHERE c.date > '".$login_date

."' ORDER BY c.date ASC ";

$result = mysql_query($query,$connection);



$last = "";

while($row=mysql_fetch_array($result))

{

$message = html_entity_decode($row['message']);

echo "[".$row['user']."][".$row['date']."] ".$message." <br/>";

$_SESSION['chat_time'] = $row['date'];

}



/* delete messages older that 60 seconds*/

if((time()-$_SESSION['chat_time_delete'])>60 )

{

$query = "DELETE FROM ".$tableName." WHERE (NOW()-date)>60";

mysql_query($query,$connection);

$_SESSION['chat_time_delete']=time();

}



mysql_close($connection);

?>

We can see session variables initialization: chat_time is the time in which you entered the chat room or of the last message received, while chat_time_delete is the time in which you last deleted a message.
The scripts work this way:

  • connect to the database
  • retrieve the chat room table name using the chatRoomId request variable and the getChatTableName() function
  • query the DB searching for messages not yet received (basing unpon the time of last message received, and at the end of the loop we have a new value for chat_time, that is the last received message time
  • (because) once received messages are useless (a user after connection never received messages of the past), the script delete messages older than 60 seconds

Of course you can format as you like the message board.

At the end we find the sender.php page, that is wrapped in an HTML iframe (because every submission must not cause the entire page reload):



<?php



/***************+ DB variables *****************+*/

$db_user = "root";

$db_password = "root1";

$db_host ="localhost";

$connection = mysql_connect($db_host,$db_user,$db_password);

mysql_select_db("test",$connection);



/********************* NOME TABDELLA CHAT ROOM **************************+*/

function getChatTableName($connection,$chatRoomId)

{

$query = "SELECT table_name FROM chat_rooms WHERE id = '".$chatRoomId."'";

$result = mysql_query($query, $connection);

$tableName = NULL;

while($row=mysql_fetch_array($result))

{

$tableName = $row['table_name'];

}



if($tableName==NULL)

{

return NULL;

}



return $tableName;

}





if($_POST['action']=="send")

if($_SESSION['userid']!="")

{

$tableName = getChatTableName($connection,$_REQUEST['chatRoomId']);



if($tableName==NULL)

{

echo "Error selecting chat room.";

exit();

}



$query = "INSERT INTO ".$tableName."(user,message,date) VALUES(\""

.$_POST['userid']."\",\""

.htmlentities(htmlspecialchars($_POST['message']))."\",NOW())";



mysql_query($query,$connection);



}

?>



<body onload="document.msgForm.message.focus();">



<form name="msgForm" action="sender.php" method="post">

<input type="hidden" value="send" name="action"/>

<input type="hidden" value="1" name="chatRoomId"/>

<input type="text" name="userid" value="<?=($_POST['userid']=="")?"guest":$_POST['userid']?>" size="10" />

<input type="text" name="message" style="width:400px" maxlength="1500"/>

<input type="submit" value="invia"/>

</form>

</body>



<?php

mysql_close($connection);

?>

This page simply prints out a web form (in which users insert their nick name -in this version without a check- and the message) and -consequently to the submission- insert the message in the DB, that will be outputted by the timer.js routine.

This will be your final result:

You can read the full tutorial here.

Hopefully this tutorial will be useful to you.

Hack the Day Away with Google

Tagged:  

If you are in the Mountain View area you can attend a "Hackathon" with Google on Friday, February 29th from 2pm - 10pm (there are two sessions one from
2pm - 5:30pm and another from 6pm - 10pm). This "Hackathon" is centered around Ajax development and is a great time to learn the below API's from the experts.

Google Gears [http://code.google.com/apis/gears/]
Google AJAX Search/Feeds [http://code.google.com/apis/ajaxsearch/]
Google Gadgets [http://code.google.com/apis/gadgets/]
Google Maps [http://code.google.com/apis/maps/index.html]

There will be a quick over view of the API's before the "Hackathon" starts. A few other things that all of we developers like is that there will be free food, prizes and schwag! Also, make sure to bring your laptop as laptops will not be provided.

You can read more about the event here.

To RSVP your spot click here.

Accessing JSON Web Services with the Google Web Toolkit

Over at GWT Site they have written a good post about using the Google Web Toolkit with JSON Web Services. Since JSON is fast becoming a standard for web services that are cross domain and GWT is a heavily used development tool this is a useful post.

below is an excerpt from the post.

The main difficulty when trying to talk to some web service on another server is getting past your web browser’s Same-Origin Policy. This basically says that you may only make calls to the same domain as the page you are on. This is good for security reasons, but inconvenient for you as a developer as it eliminates the use of GWT’s HTTP library functions to achieve what we want to do. One way to get around this is to call a web service through a javascript <script> tag which bypasses this problem. In his book, Google Web Toolkit Applications, Ryan Dewsbury actually explains this technique in more detail and provides a class called JSONRequest which handles all the hard work for us. JSON is one of the more popular data formats, so most web services support it. Lets leverage Ryan’s code and take a quick look at how it works.

public class JSONRequest {
  public static void get(String url, JSONRequestHandler handler) {
    String callbackName = "JSONCallback"+handler.hashCode();
    get( url+callbackName, callbackName, handler );
  }	
  public static void get(String url, String callbackName, JSONRequestHandler handler ) {
    createCallbackFunction( handler, callbackName );
    addScript(url);
  }
  public static native void addScript(String url) /*-{
    var scr = document.createElement("script");
    scr.setAttribute("language", "JavaScript");
    scr.setAttribute("src", url);
    document.getElementsByTagName("body")[0].appendChild(scr);
  }-*/;
  private native static void createCallbackFunction( JSONRequestHandler obj, String callbackName)/*-{
    tmpcallback = function(j) {
      obj.@com.gwtsite.client.util.JSONRequestHandler::onRequestComplete(Lcom/google/gwt/core/client/JavaScriptObject;)(j);
    };
    eval( "window." + callbackName + "=tmpcallback" );
  }-*/;
}

To make our request we call the get method with the web service url, and an implementation of the JSONRequestHandler interface. This interface has one method called onRequestComplete(String json). This is where you’ll handle the JSON formatted data once it comes back from the server. When calling a service from within a script tag, we need to specify the name of a callback function in the request. Most services let you specify the name yourself, so the first get method generates a callback name for you. The createCallback method is a JSNI method that simply calls your JSONRequestHandler implementation when the call returns via the callback name. Note, if you use this class, to make sure and change the package name for the JSONRequestHandler call to the correct location. Finally, the get method will call the addScript function which is responsible for embedding the <script> tag on your page and setting its src attribute to the web service url.

You can read the full post here.

Since I am a fan of both JSON and GWT I enjoy seeing good posts about using these two technologies. I recommend this post for any Java developer that wants to make Ajax applications using Web Services.

Multi-player Ajax Games

Today I came across an interesting article about creating multi-player video games using Ajax. The article mainly deals with how you would send data to and from the server and also touches on keeping the game in sync on multiple clients.

The below code is how the post purposes that you would send data to the server side (this code uses a hand rolled Ajax call, but you could change it to use a library).

var httpSend = null;
var httpGet = null;

function send(action)
{
httpSend=GetXmlHttpObject();
if (httpSend==null){alert (?Your browser does not support AJAX!?);return;}

var url=?send.php?;
url=url+??action=?+action;
url=url+?&p=?+player;
url=url+?&g=?+gameid;
url=url+?&sid=?+Math.random();
httpSend.onreadystatechange=stateSend;
httpSend.open(?GET?,url,true);
httpSend.send(null);
}

function get()
{
if(httpGet != null) { return 0; }

httpGet=GetXmlHttpObject();
if (httpGet==null){alert (?Your browser does not support AJAX!?);return;}

var url=?get.php?;
url=url+??sid=?+Math.random();
url=url+?&p=?+player;
url=url+?&g=?+gameid;
httpGet.onreadystatechange=stateGet;
httpGet.open(?GET?,url,true);

httpGet.send(null);
}

function stateSend() {
if (httpSend.readyState==4){}
}

function stateGet() {
if (httpGet.readyState==4)
{
str = httpGet.responseText;
if(str != ?){
eval(str);
}
httpGet = null;
}
}

function GetXmlHttpObject() {
var xmlHttp=null;
try {
xmlHttp=new XMLHttpRequest();
}
catch (e) {
try {
xmlHttp=new ActiveXObject(?Msxml2.XMLHTTP?);
}
catch (e) {
xmlHttp=new ActiveXObject(?Microsoft.XMLHTTP?);
}
}
return xmlHttp;
}

The following code would be on the server side to receive messages. In the case of this example the code is PHP and the file is called Get.php

<?php
include(?config.php?);
$p = $_GET[?p’];
$g = $_GET[?g’];
$action = ?;
$query = mysql_query(?SELECT * FROM actions WHERE id = ?.$g);
$row = mysql_fetch_array($query);
$action = $row[$p];
$action = stripslashes($action);
$str = ?update actions set `?.$p.?` = ? where id = ?.$g;
mysql_query($str);
echo $action;
?>

The following code would be on the server side to send messages. In the case of this example the code is PHP and the file is called Send.php

<?php
include(?config.php?);
$p = $_GET[?p’];
$g = $_GET[?g’];
if($p == 1)
{
$b = 2;
}
elseif($p == 2)
{
$b = 1;
}
$action = $_GET[?action?];
$action = addslashes($action);
$query1 = mysql_query(?select * from actions where id = ?.$g);
$row = mysql_fetch_array($query1);
$str = $row[$b];
$str = $str . $action;
$str = ?UPDATE actions SET `?.$b.?` = ??.$str.?? where id = ?.$g;
$query = mysql_query($str);
if(!$query)
{
echo mysql_error().$str;
}
else
{
echo 0;
}
?>

You can read the full post here

The post also touches on the possibility of sending data via a text string. I personally think that for multi-player games JSON is a perfect data transfer method. Unlike XML there is not a large overhead and unlike sending data via a text string there is no parsing needed on the client which should help performance. This post is interesting as I think that Ajax can be a very useful method of transferring data for multi-player games.

More JavaScript/Ajax Cheatsheets

Tagged:  

Scott Klarr has posted a collection of some JavaScript/Ajax cheatsheets on his blog.

The cheatsheets include:

  • Javascript Cheat Sheets
  • jQuery Cheat Sheets
  • Scriptaculous Cheat Sheets
  • Prototype Cheat Sheets
  • Microsoft Ajax Library Cheat Sheets
  • Yahoo YUI Cheat Sheets
  • ...and more...
  • Click here to read the post and to download the cheatsheets.

Prototype 1.6.0.2 Cheat Sheet

Tagged:  

A new cheat sheet was posted today over at the Prototype blog that is current with all the updates in the recent release of Prototype version 1.6.0.2. Kangax, the author of the cheat sheet, even color coded deprecated 1.6 methods in red.

In the event that this is the first time you've heard of the Prototype 1.6.0.2 release, it happened a few days ago. It contains some bug fixes and performance enhancements, as well as official support for Opera 9.

Click here to read about [and download] the cheat sheet.

Cross Browser Sound - Flash Only as a Last Resort

Tagged:  

After creating World of Solitaire and seeing how much of a success it was, I soon looked at what my next JavaScript game would be.

Although I hadn't made a decision yet, I knew that I wanted this game to have sound.
I also knew that I didn't want to use Flash.

So thus began that adventure of looking into how the different browsers played sound, without Flash or other plugins.

Turns out many browsers have support for sound built in.
Opera for example supports the WHATWG proposed Audio object, while IE has the proprietary bgsound attribute.

I decided that I would write up some JavaScript that would use the built in browser support for sound playing whenever possible, falling back to plugins and flash only as a last resort.

For a demo and the code check out: http://www.telparia.com/browsersoundtest/

Just use View->Source to see the code.
The guts of it are located here: http://www.telparia.com/browsersoundtest/js/Sound.js

You'll see some other JS files such as P.js
The sound engine itself only needs P.js as a way to detect browser platform.

The other files including the YahooUI are not needed for the Sound.js file to work.

I haven't actually used this code in a production environment yet, but I have tested it and it works in the following browsers:
* - Opera 9.23 on Windows XP [Audio object]
* - Opera 9.51 beta 3 on Linux (can't force stop) [Audio object]
* - IE 6 on Windows 2000 [bgsound]
* - IE 7 on Windows XP [bgsound]
* - Opera 8.53 on Windows XP [iframe embed]
* - Safari 3.0.2 on Windows XP [embed]
* - Firefox with plugin for audio/x-wav [embed]
* - Anything with a plugin for application/x-shockwave-flash [flash]

I don't have access to a Mac, so I'm not sure how it behaves on that platform.

Also, it's a little slow to start the sound as it is loaded into the browser. However after it is cached, it performs quite well indeed.

I welcome any bug reports or suggestions or changes. I some day intend to use this code in my next web game :)

Ajaxonomy's del.icio.us Spy - Released!

Tagged:  

You are probably familiar with Digg Spy, but I was very surprised when I found out that there was no similar application for del.icio.us (if you are not familiar with del.icio.us it is a great social bookmarking site).

So, we at Ajaxonomy we decided to make our own del.icio.us spy application. The application allows you to see the latest bookmarks being added to del.icio.us so that you can find great new sites. The application also includes links to help make it easy to share what you find with others.

The application allows you to filter results (i.e. type in "web" and you will only see links containing the word web) and to be notified (via sound) when new items are added. The application also allows you to pause the items that are shown so if you find something you like you can see it for a while.

You can go to the application by clicking here. The application will also be available in the Ajaxonomy Labs section on the right bar of this blog.

As with all the applications in the Ajaxonomy Labs section, this application is open source and you can download the source code here.

Syndicate content