Stats: 3,186,500 members, 7,929,633 topics. Date: Friday, 23 August 2024 at 06:18 PM |
Nairaland Forum / Science/Technology / Webmasters / Create Ajax Chat & Learn Web Page Data Xchange via Json Vs Xml (8367 Views)
How To Make Google Index Your New Blog Post, Web Page Quickly. / Learn Web Design LIVE On Nairaland!!! / Form Validation Tutorial Using Javascript, Php And Ajax! (2) (3) (4)
Create Ajax Chat & Learn Web Page Data Xchange via Json Vs Xml by Nobody: 1:28pm On Jan 04, 2009 |
Today we are going to have a short session on how to store data on web pages other than in database: The workshop here: how to build an ajax chat - and this is going to be a few hours lesson - after that i will post the demo for the chat - source code and all. Thereafter, questions can now start coming in. The Chat App The link is invalid at this time, was lost - but all the codes are here. I am doing maintenance of my sites, so links are scattered at this time - this is a redit You can download it at (moved, please send) The name is ajax web chat 2009 The code documentation is explained below. I apologize for the way i dump the codes. There is much i talked about in here. However if i dont do it that way - this thread will be extremely long. But i am open for questions anyway. JSON First [Most people already know XML] JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language. JSON is built on two structures: A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array. An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence. These are universal data structures. Virtually all modern programming languages support them in one form or another. It makes sense that a data format that is |
Re: Create Ajax Chat & Learn Web Page Data Xchange via Json Vs Xml by Nobody: 1:35pm On Jan 04, 2009 |
Since is so lightweight, it makes it an ideal candidate for AJAX applications. So what does JSON look like. The JSON code our JSON AJAX Chat application will be returning will look something like this: dbase.js
As you can tell, it looks a lot like structured data - and it is. This same data structure might be represented with XML like: dbase.xml
|
Re: Create Ajax Chat & Learn Web Page Data Xchange via Json Vs Xml by Nobody: 1:41pm On Jan 04, 2009 |
chat.sql
This table message will hold our list of messages that are sent from our JSON AJAX Chat web page. It basically consists of who sent the message, when they sent it, and what the message was. The field chat_id would be used if you wanted to have more than one chat session. |
Re: Create Ajax Chat & Learn Web Page Data Xchange via Json Vs Xml by Nobody: 1:44pm On Jan 04, 2009 |
The HTML Skeleton Now that we have created our database tables, we need to create our HTML Skeleton. This is a very basic layout that could easily be made to look nicer with CSS, but we're not concerned with looks right now. We just want the basic functionality. For the sake of the demo, we'll just put the necessary CSS style information on the HTML page in a style tag. In a production environment, you should place your CSS into an external file for caching benefits, especially when you start having lots of CSS rules. We will also place our JavaScript on the HTML page in a script tag for the sake of the demo. We will write that in just a few minutes. Our basic HTML page will look like: chat.html
|
Re: Create Ajax Chat & Learn Web Page Data Xchange via Json Vs Xml by Nobody: 1:47pm On Jan 04, 2009 |
As you can see we have a simple header that is just a title, a paragraph where we can display status messages in the event of any errors, and a main DIV for displaying the chit-chat. We also have an HTML form with 4 HTML control elements. We have a refresh button to restart the JavaScript timer in the event of an error. This button should only be for test purposes. We have a button to reset the chat which will clear all the messages off the screen. Finally, a text area and a button to send a new chat message to the server. In the HTML, we have one inline CSS class on the text box to expand its width, and one CSS class on the main DIV that hasn't been defined yet. The undefined CSS class will look like:
All these values should be pretty self explanatory with the exception of "overflow". The overflow: auto; attribute allow the DIV to behave somewhat like an IFrame in the sense that when the content is larger than the DIV's size, scrollbars will be provided rather than expanding the dimensions. |
Re: Create Ajax Chat & Learn Web Page Data Xchange via Json Vs Xml by Nobody: 1:48pm On Jan 04, 2009 |
The JavaScript Now onto the AJAX! It's time to write all the magic code that makes AJAX so neat. We'll start with my favorite piece of AJAX code. chat.js
This simply returns a browser specific XmlHttpRequest object - the basis for AJAX functionality. The XmlHttpRequest object allows us to make asynchronous requests to the web server without refreshing the page. IE uses an ActiveX object where Firefox and most of the other browsers out there use a native object. IE 7 allows the use of both a native object and the ActiveX object which would eliminate the need for this block of code, however people will be using IE 6 for many years to come so you better get use to writing this. We can now use this code to create a browser specific XmlHttpRequest object anywhere in our page. Lets start out by adding four global variables to the top of our page.
We need two XmlHttpRequest objects - one for sending new chat messages and one for receiving chat messages. We also need a variable to store the last message we have received to avoid sending the entire message list each time, and a timer to periodically poll the server for new messages. We place the auto refresh timer in a global variable so that we can clear out the setTimeout at any point to avoid having more than one timer running at once. Now let's add the function to make the call to receive the most recent messages on the server.
The first line of code in the function checks to make sure our XmlHttpRequest object is not currently in the middle of a different request. 0 is uninitiated and 4 is complete. Any other readyState is in the middle of a request. The next line setups up the connection to the server: receiveReq.open("GET", 'getChat.php?chat=1&last=' + lastMessage, true); Since we aren't sending much data a standard HTTP "GET" will be fine. When we send the message later you will see how to create an AJAX request using a HTTP "POST" The second parameter is the URL we want to make the AJAX request to. Notice that we are passing a parameter in the URL querystring that contains the last message we received as well as the chat session that we want messages for. The chat parameter is hard coded as a 1, but if we wanted to have more than one chat room, we could make this a dynamic parameter based on which chat session we were in. The last parameter, "true", is a flag used to mark if the request is asynchronous or not. We don't really need this parameter because by default it is asynchronous, but will explicitly set it anyway. The next line sets the call back function that will get executed every time the the XmlHttpRequest objects readyState changes. receiveReq.onreadystatechange = handleReceiveChat; We will simply set this to a function we will write in just a minute. The third and file line makes the actual AJAX request to the server. The null value parameter is where you could pass additional values to the server if this was an HTTP POST request as you will see later. |
Re: Create Ajax Chat & Learn Web Page Data Xchange via Json Vs Xml by Nobody: 1:52pm On Jan 04, 2009 |
The Client Side JSON Now we are going to create the function that handles the AJAX server response. This function is also where we get to see JSON in action.
This function will fire every time the XmlHttpRequest object's readyState changes, not just when it is complete, so we need to check to make sure the readyState = 4 which is complete. The first line simply gets a reference to DIV that holds all of our chat messages. We are simply doing this so we don't have to reference the DIV with document.getElementById each time. The next line is the really cool part, and is the reason I will be using JSON for AJAX in the future rather than XML. With JSON, we can use JavaScript's built-in eval() function to create a usable object that we can reference with "dot" notation. var response = eval("(" + receiveReq.responseText + " ![]() ![]() What is happening here is the JSON response is transformed into an object with child arrays using the eval() function. The receiveReq.responseText gets the string returned from the AJAX request. The other option would be responseXML, which would return an XML DOM object. Notice that since we are passing in the responseText to the eval function as a string we need to wrap it in parentheses. Otherwise this would throw an error - it certainly got me more than once. Now that we have our AJAX response data stored in a usable JavaScript object, we can loop through each of the messages provided and update our chat DIV. Let's take one more look at the format our JSON response will be in:
As you can see we have a "Root" messages object followed by a message element with X number of message values. JSON key value pairs are seperated by colons ( ![]() Since we have this data represented as a JavaScript object, we can access its values including the length of message values through standard JavaScript dot notation.
This line loops through each element. The next three lines add the message values to our chat DIV.
Notice how we can access our values through .user .time and .message rather than some complicated getElementByTag call required with XML. The next line is a nice little usability addition that automatically scrolls our DIV to the bottom so the most recent message is always visible - thanks for this one Eric.
Finally, we set the last message we received using the same JSON functionality as we did to populate the chat DIV:
Once we finally fall out of our message loop, we will reset the time to check for any new messages in 2 seconds. Depending on your server load, you may want to throttle this even more, although the amount of data being sent down the pipe is fairly minimal - probably never never more than 10K.
|
Re: Create Ajax Chat & Learn Web Page Data Xchange via Json Vs Xml by Nobody: 1:57pm On Jan 04, 2009 |
Sending a Message Next we need to write the code to send a message to the server. We will send our message as an HTTP "POST" rather than a "GET" this time since we will be sending larger amounts of data. URL's only support a couple of thousand characters on older browsers, and the RFC for URL's state you should try to not go over 255 characters. This will keep us from getting into trouble with any long messages getting sent. Creating a POST AJAX request isn't that much different that creating an AJAX GET request.
As you can see, it's basically the same code, but instead of passing the parameters in the URL, we pass them when we call the XmlHttpRequest.send method and mark our method as a POST when we initialize the request.
The parameters are & spaced just like in a URL query string. We are passing three values to the server, our message text, our name, and the chat session we are currently in - which is currently hard coded to my name and 1 for the sake of this tutorial. Our callback function for this AJAX request is extreamly basic.
All we are doing is clearing out the old timer and starting an AJAX request for new messages with the function we already wrote. Resetting the Chat We now have everything we need in our HTML and JavaScript to send message back and forth from the server. The only thing left for us to do is add the ability to reset the chat. In a real implementation, you would probably want to have have the server "prune" the messages every so often rather than give the user the ability to clear it out.
This function is essentially the same as sending the message, but instead of sending the message as a parameter, we are sending an action parameter to reset the chat. The callback to this function is also very similar to handleSendChat with the addition of clearing out the text (innerHTML) of our chat DIV. The last thing we need to do to our HTML page it to add onclick handlers to our HTML buttons.
Each button gets pointed to its corresponding JavaScript function. |
Re: Create Ajax Chat & Learn Web Page Data Xchange via Json Vs Xml by Nobody: 1:59pm On Jan 04, 2009 |
The Backend This tutorial will use PHP and MySQL as the backend, but this could easily be modified to use any server-side language (ASP, ASP.NET, JSP, CFM, RoR, etc.). The response is a simple text response so the choice of language is pretty much up to personal preference. We only need the one page since all of our AJAX requests go to the same page. They are then sorted out based on the parameters sent in the response. The first thing the backend file does is create some HTTP headers to keep the users browsers from caching the response.
Probably the most important header is the first "Expires" header. You can see we set it to a date that has already passed. Without this header, IE tends to cache the response regardless of the other headers. The other header we send is the Content-Type. We don't really need this since we're sending plain text. This would be much more important if we were sending XML. The next line includes a file that contains our database functions. I like to abstract my database functions in a seperate file in case I need to change by
This file can be changed to connect to pretty much any database type with some simple changes to the file. The first action we perform is to see if a new message was sent in our POST parameters.
If a new message was set, then we create a SQL INSERT statement to add the message to the database. We use the function db_input - which is included in the database.php file to escape any quotes or other dangerous SQL that may have been entered by the user. You should always cleanse user input before you execute SQL statements with it. Acutally you should be using stored procedures or prepared statements, but that's a little beyond the scope of what we're doing here. Finally we execute the query to add the new message to the database. Next we check to see if a reset action was sent in our POST parameters. If it was we will delete all of the messages with the give chat_id.
Obviously if this were a production system you would want to have some security built around this to keep others from deleting messages in chat sessions they didn't belong to, but since this is just a proof of concept, we're not going to worry about it. |
Re: Create Ajax Chat & Learn Web Page Data Xchange via Json Vs Xml by Nobody: 2:01pm On Jan 04, 2009 |
Creating the Response Once we have performed any INSERTS or DELETES to the system, it's time to create our JSON response. The first thing we'll do is create our JSON root element since this will always be sent back to the server.
If we didn't we will send a response informing them they need to enter one before they can receive any messages. Once again, in a real system you would want to do security checks here to ensure the user has permissions to access the chat room. If we did receive a chat room id then we will run a SQL query to see if any new messages have been added since the last request.
If we didn't receive a "last" parameter, we will assume that the user hasn't received any messages yet and set this value to zero. If there are any messages the user hasn't received yet, we will loop through each one and create a JSON message for each.
As you can see we simply create a message object and assign it the values from the database. If there were no new messages, then we need to create an empty message object for our JSON response to avoid JavaScript errors when we test for the length of messages sent back.
The last thing we need to do is close out the JSON data structure and send the response back to the server.
We are now ready to test out our JSON AJAX Driven Web Chat. Be sure that you have already created the database tables and set the correct database connection values in database.php |
Re: Create Ajax Chat & Learn Web Page Data Xchange via Json Vs Xml by Nobody: 2:04pm On Jan 04, 2009 |
Usability Additions We can see that we have a semi-functioning AJAX driven chat application. To finish off part one of this tutorial, we will make a few small additions to the HTML in order to make it a bit more user friendly. One of the first things you'll probably notice is that when you type a message and press enter, the page refreshes and your message isn't added. You have to actually click the "Send" button to add your message to the chat. To fix this, we will add a simple JavaScript function that is called on the form's submit event.
This function will call our sendChatText function and return false to keep the form from submitting.
This will add our message to the chat every time we enter a message and press enter. You will also notice that when you first open the page, the chat is not refreshing itself. We will create a JavaScript function that is called when the page loads to handle initializing our application.
When the document loads, we start refreshing the chat messages by calling the getChatText() function.
Additionaly we set the focus to the message textbox so the user can immediately start typing a message. One last thing that I will add to the tutorial is the ability to have the chat area auto scroll with the messages. This is simple little addition that really increases the usablilty of the Chat. In our handleRecieveChat function, we will add the line:
After we add the chat message to the chat_div. Now when a new message arrives, and the chat_div grows beyond it's containing size, the new message will be visible without having to scroll. This concludes the first part of the AJAX driven web chat tutorial. In the next installment, we will see how to create multiple chat rooms with different user names. We will also see other ways to extend our chat application to make it more robust and user friendly. Hopefully this tutorial gave you a good introduction to creating application using AJAX technologies. |
Re: Create Ajax Chat & Learn Web Page Data Xchange via Json Vs Xml by Nobody: 2:05pm On Jan 04, 2009 |
Source code has been pasted on the first message in case you are looking for it. |
Re: Create Ajax Chat & Learn Web Page Data Xchange via Json Vs Xml by OmniPotens(m): 3:05pm On Jan 04, 2009 |
Stuffs becoming much in here ![]() Piecemeal for better comprehension. Actually I was expecting you to have started off tomorrow. Never mind, I'm going to store up the links to all these tutorials for easier reference by members in here. |
Re: Create Ajax Chat & Learn Web Page Data Xchange via Json Vs Xml by Nobody: 3:11pm On Jan 04, 2009 |
I did not really plan to do this - i just thought it would a great idea - i will post the demo link and the source codes shortly. So there we are - we know have a crossbrowser web chat - the questions can now start coming. Meanwhile - i will appreciate if someone like @Abidemi and people from other tribes of web languages start giving us plugins for asp.net, jsp and the likes so that more people can use this solution. |
Re: Create Ajax Chat & Learn Web Page Data Xchange via Json Vs Xml by OmniPotens(m): 3:17pm On Jan 04, 2009 |
You know, after posting the demo link and the codes, you can stop then wait for question. Or, I think I'll start by asking dummy questions so that those who fall in from their holidays will pick up and follow sharply and smartly. |
Re: Create Ajax Chat & Learn Web Page Data Xchange via Json Vs Xml by uspry1(f): 6:55pm On Jan 07, 2009 |
@poster Right now i got stuck with Flash-based (AS3) PHP/text file mini-Forum/Message board application that has failed loading Message thread content after hitting a button "create a post". It does not work, even though the owner's forum/tutorial is not helping to solve this error. Because the owner recently changed from Flash AS1 into reworked Flash AS3 mini-Forum/Message board application. No one has succeeded installing AS3 Flash-PHP-text mini-Forum/Message board so far. The readme.txt says it can be switched from text file to MySQL file or Flash remoting file. Until I saw your scripting on AJAX chat thread here on NL last week, it seems that is possible to switch from text file to Fjax file using Flash mini-Forum/Message board application. I don't know! Let me try that myself. Thank you for caught my attention having great desire to learn more about your scripting: AJAX chat. Last week, I had been researched about FJAX that is for Flash application using AJAX to load any content dynamically like AJAX chat possible. Right now i already downloaded both FJAX SDK and your script: AJAX chat to see if it works on my Flash application. I will let you know my outcome of new Fjax application. Cross my finger!!! |
Re: Create Ajax Chat & Learn Web Page Data Xchange via Json Vs Xml by Nobody: 8:02pm On Jan 07, 2009 |
The only flash programming i do after flash 6.0 is Flex Builder 3.0 - it has a GUI rather like visual studio .NET - i am quite efficient at it - i have built a forum with it before - that is as fast as a chatroom to post and read posts - however i decided to scrap it for now - because our internet speed in nigeria is not yet ready to start throwing flash from server to clients - any other flash lang i am not conversant with. I am working on a multi-messenger chat on my new project - something very close to facebook chat - and i am using completely different techniques from this one - this is about the 3rd type of chat i have created - still i am not satisfied. |
Re: Create Ajax Chat & Learn Web Page Data Xchange via Json Vs Xml by nickky25(m): 11:22pm On Feb 20, 2011 |
Pls i have just entered this section for the first time. Am new to web design, I can work with HTML & Dreamwaver but does not know how to configure a webform to work with my email so that when a visitor to my website submits an information on my contact page form, it gets direct to my email box. I will be grateful if you can assist me with a step by step detail or just create a little configured form so i can follow the steps outlined. Here is my email address: infopeternow@gmail.com Awaiting your fast response. Best Regards, Peter Nickky |
Re: Create Ajax Chat & Learn Web Page Data Xchange via Json Vs Xml by Nobody: 12:21pm On Feb 21, 2011 |
i am assuming you know how to use php? or what web languages can you use? |
Re: Create Ajax Chat & Learn Web Page Data Xchange via Json Vs Xml by nickky25(m): 4:28pm On Mar 03, 2011 |
Hello friend, I can do much with HTML but not with php, Please help me with anyone and provide me with a step by step detail on how to configure it. |
Re: Create Ajax Chat & Learn Web Page Data Xchange via Json Vs Xml by eedide: 9:20am On Dec 23, 2011 |
can't find the link to the source code, can't find the demo link either! |
Re: Create Ajax Chat & Learn Web Page Data Xchange via Json Vs Xml by Nobody: 11:25am On Dec 23, 2011 |
Please search google for " ajax chat" or visit - http://www.blogs..net/content/ajax-web-chat-2009 |
Re: Create Ajax Chat & Learn Web Page Data Xchange via Json Vs Xml by mckanute: 11:19am On Sep 02, 2014 |
You could also search out "african tech feed" and click on rhumsiki, you'll get clean hands on XML/CSS/PHP website |
(1) (Reply)
Adsense Link Ads Are The Best / 7 Untold Dumb Mistakes That Won't Make Your Blog Last Long / 15 Proven Ways To Drive Traffic To Your Blog
(Go Up)
Sections: politics (1) business autos (1) jobs (1) career education (1) romance computers phones travel sports fashion health religion celebs tv-movies music-radio literature webmasters programming techmarket Links: (1) (2) (3) (4) (5) (6) (7) (8) (9) (10) Nairaland - Copyright © 2005 - 2024 Oluwaseun Osewa. All rights reserved. See How To Advertise. 100 |