We available for hire! — Need help with a web or mobile project?
From yensdesign we develop technology projects based on web apps, mobile apps, consulting and databases. We are young and hard workers, passionate about innovation and focused in new technologies.If you want to ask for a budget, we hare available for hire!.
Create a shoutbox using PHP and AJAX (with jQuery)
January 5th, 2009Continuing with the tutorials about AJAX and jQuery we will create a stunning and dynamic shoutbox based in PHP and AJAX (using jQuery).
We will learn how to create a dynamic ajax based shoutbox with jQuery from scratch. It will be very interesting to know how to use the ajax function of jQuery and how it can be used to insert and recover data from a MySQL database via PHP in a way asynchronous.
Here you have a preview image:
You can try the living example before continue reading the tutorial.
Tested in: Firefox, Internet Explorer 6 (bad display of PNG icons, IE bug) & 7, Opera, Safari & Chrome.
Come on guys, let’s dive into the tutorial!
What we will do
For those who don’t know what is a shoutbox here you have a wikipedia dixit:
A shoutbox, saybox, tagboard, or chatterbox is a chat-like feature of some websites that allows people to quickly leave messages on the website, generally without any form of user registration.
Now that we know what we want to do, we will remember what we will use to achieve our purpose:
- xHTML & CSS
- PHP (We need a PHP server!)
- MySQL (We will need a MySQL database too!)
- Javascript & AJAX (via jQuery, of course!)
Don’t worry if you don’t know a lot about MySQL, We only need it to create a small table and to inser & recover data in a simply way via PHP.
Let’s face the step 1 guys!
Step 1: The Layout
First of all we will create the layout (as always, you know), it will be similar to the tabbed menu tutorial and it will have 2 main divisions:
- Form (fields with the user and message to send)
- Container division (contains the messages)
- Loading division (as a part of the Container division, displays the loading animated gif… while messages are loading)
So now we have have seen the main divisions, take a look at the xHTML code:
[code language="html"]
Latest Messages
We are limiting the maxlength of both fields: nick(25) & message(255) because our shoutbox table will have these length limitations.
Nothing more to explain over here, let’s go to the CSS part.
Step 2: Adding some style with CSS
There is nothing special in this case for the css part, just remember you that we are reusing the CSS trick for the tab that we have used in the tabbed menu tutorial.
Here you have the entire CSS code:
[code language="CSS"] @CHARSET "UTF-8"; /******* GENERAL RESET *******/ html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, font, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td { border:0pt none; font-family:inherit; font-size: 100%; font-style:inherit; font-weight:inherit; margin:0pt; padding:0pt; vertical-align:baseline; } body{ background: #fff; line-height:14px; font-size: 12px; font-family: Arial, Verdana, Helvetica, sans-serif; margin:0pt; cursor:default; overflow: hidden; } html,body{ height:100%; text-align: center; } .clear{ clear: both; height: 0; visibility: hidden; display: block; } a{ text-decoration: none; } strong{ font-weight: 700; } /******* GENERAL RESET *******/ /******* LOGO *******/ #logo{ margin-top: 1em; display: block; } /******* /LOGO *******/ /******* FORM *******/ #form{ margin: 5em auto 3em; width: 300px; } #form table td{ text-align: left; font-size: 11px; } #form label{ font-weight: 700; } #form input{ border: 1px solid #d0ccc9; background: #fff; color: #5f95ef; font-size: 11px; font-weight: 700; } #form input.text{ font-weight: normal; color: #565656; border: 1px solid #9c9c9c; width: 250px; padding: 2px; margin-bottom: 5px; text-align: left; } #form input.text.user{ width: 100px; } /******* /FORM *******/ /******* MENU *******/ #container{ margin: 1em auto; width: 400px; } #container ul{ list-style: none; list-style-position: outside; } #container ul.menu li{ float: left; margin-right: 5px; margin-bottom: -1px; } #container ul.menu li{ font-weight: 700; display: block; padding: 5px 10px 5px 10px; background: #fff; border: 1px solid #d0ccc9; border-width: 1px 1px 0 1px; position: relative; color: #5f95ef; cursor: pointer; } /******* /MENU *******/ /******* CONTENT *******/ .content{ margin: 0pt auto; background: #efefef; background: #fff; border: 1px solid #d0ccc9; text-align: left; padding: 10px; padding-bottom: 20px; font-size: 11px; } .content h1{ line-height: 1em; vertical-align: middle; height: 48px; padding: 10px 10px 10px 52px; font-size: 32px; background: transparent url(images/bubble.jpg) no-repeat scroll left top; } .date{ font-weight: normal; font-size: 9px; color: #aeaeae; } /******* /CONTENT *******/ /******* LOADING *******/ #loading{ text-align: center; } /******* /LOADING *******/ [/code]
As you may noticed, we have an empty ul element with no li elements, that’s because we will load his content via AJAX
Let’s create the MySQL table.
Step 3: Creating shoutbox table in MySQL
As I told you, we will make use of a MySQL database to store our messages and then we will retrieve data via PHP. So we only need to create a simple table called shoutbox with these columns:
- id (int primary key and with auto increment)
- date (timestamp default CURRENT_TIMESTAMP)
- user (varchar 25)
- message (varchar 255)
So here you have the MySQL code that you must execute in your database (via phpmyadmin for example):
[code language="SQL"] CREATE TABLE `shoutbox`( `id` int(5) NOT NULL auto_increment, `date` timestamp NOT NULL default CURRENT_TIMESTAMP, `user` varchar(25) NOT NULL default 'anonimous', `message` varchar(255) NOT NULL default '', PRIMARY KEY (`id`) ); [/code]
So now that we have our layout ready and the MySQL table created let’s continue with the PHP part.
Step 4: Using PHP to insert & recover data from MySQL database
Last two steps (step 4 & step 5) are very important so guys pay attention! With jQuery.ajax() function from jQuery we can load a remote page using an HTTP request.
We will make use of the jQuery.ajax() function to make a POST request to a PHP script named shoutbox.php that will manage the insert / retrieve data action with a switch sentence. We will receive a XMLHttpRequest object from $.ajax() function that will have a property called responseText. This property will give us the required information to display the shoutbox’s messages (in case of select action) or the confirmation (in case of insert action).
So before add the AJAX code we need to create our shoutbox.php that will manage all the requests from our future javascript file shoutbox.js. We will define some constants to the MySQL connection:
[code language="PHP"] /************************ CONSTANTS /************************/ define("HOST", "YOUR HOST"); define("USER", "YOUR USER"); define("PASSWORD", "YOUR USER PASSWORD"); define("DB", "YOUR DATABASE"); [/code]
As you may noticed the second parameter of each define() function it’s wrong / empty, you must change them for values that apply in your case.
Now we have defined our constants to the connection with MySQL we will create 3 functions:
- connect(): It will open a connection to a specific host selecting a specific database too.
- getContent(): It will retrieve the last messages from our shoutbox table in plain text.
- insertMessage(): It will insert the new message in our shoutbox table.
So here you have the three functions:
[code language="PHP"] /************************ FUNCTIONS /************************/ function connect($db, $user, $password){ $link = @mysql_connect($db, $user, $password); if (!$link) die("Could not connect: ".mysql_error()); else{ $db = mysql_select_db(DB); if(!$db) die("Could not select database: ".mysql_error()); else return $link; } } function getContent($link, $num){ $res = @mysql_query("SELECT date, user, message FROM shoutbox ORDER BY date DESC LIMIT ".$num, $link); if(!$res) die("Error: ".mysql_error()); else return $res; } function insertMessage($user, $message){ $query = sprintf("INSERT INTO shoutbox(user, message) VALUES('%s', '%s');", mysql_real_escape_string(strip_tags($user)), mysql_real_escape_string(strip_tags($message))); $res = @mysql_query($query); if(!$res) die("Error: ".mysql_error()); else return $res; } [/code]
It’s almost finished guys. As we said, we will manage via switch sentence the POST requests from AJAX (from the future shoutbox.js file) so we will make use of the three previous functions to retrieve and insert data:
[code language="PHP"] /****************************** MANAGE REQUESTS /******************************/ if(!$_POST['action']){ //We are redirecting people to our shoutbox page if they try to enter in our shoutbox.php header ("Location: index.html"); } else{ $link = connect(HOST, USER, PASSWORD); switch($_POST['action']){ case "update": $res = getContent($link, 20); while($row = mysql_fetch_array($res)){ $result .= "
And that’s all in the PHP part guys.
Just comment that we are avoiding the direct access to shoutbox.php by checking the post variable action that we send in each request to shoutbox.php from javascript code (from shoutbox.js remember).
Let’s go to the final step… the AJAX part!
Step 5: Adding AJAX and some magic with jQuery
So now we have done the layout with the CSS, the shoutbox table in a MySQL database and the PHP script to insert / retrieve data.
We only need to know how to make POST requests from our shoutbox.js javascript file to our soutbox.php PHP script file.
All the following code will be in a javascript file named shoutbox.js and in the $(document).ready of jQuery. First of all we will define some variables to save some references to jQuery selectors:
[code language="javascript"] //global vars var inputUser = $("#nick"); var inputMessage = $("#message"); var loading = $("#loading"); var messageList = $(".content > ul"); [/code]
We will need a function to check if all fields are filled before send the data to our database, it will be called checkForm():
[code language="javascript"] //check if all fields are filled function checkForm(){ if(inputUser.attr("value") && inputMessage.attr("value")) return true; else return false; } [/code]
As we said in the Step 1, we will load the messages of our shoutbox table via AJAX from the first instance, so let’s create a function to retrieve this data:
[code language="javascript"] function updateShoutbox(){ //just for the fade effect messageList.hide(); loading.fadeIn(); //send the post to shoutbox.php $.ajax({ type: "POST", url: "shoutbox.php", data: "action=update", complete: function(data){ loading.fadeOut(); messageList.html(data.responseText); messageList.fadeIn(2000); } }); } [/code]
What’s happening here? We are showing the loading animated gif while we are retrieving data from shoutbox table via POST request to our shoutbox.php.
With the data parameter of $.ajax() function we can send post variables (action = update), in this case we are sending $_POST['action'] = “update”, so shoutbox.php can manage the specific action in the switch sentence that we have made before.
Finally when the request is completed, we hide the loading animated gif, load the new data in our xHTML layout and show it.
So adding a call to this function, updateShoutbox() in the ready event of jQuery we can load the data in a first instance:
[code language="javascript"] //Load for the first time the shoutbox data updateShoutbox(); [/code]
Finally we need to manage the submit event to insert user’s messages in our shoutbox table and then refresh the content in the shoutbox (with the updateShoutbox() function, you know):
[code language="javascript"] //on submit event $("#form").submit(function(){ if(checkForm()){ var nick = inputUser.attr("value"); var message = inputMessage.attr("value"); //we deactivate submit button while sending $("#send").attr({ disabled:true, value:"Sending..." }); $("#send").blur(); //send the post to shoutbox.php $.ajax({ type: "POST", url: "shoutbox.php", data: "action=insert&nick=" + nick + "&message=" + message, complete: function(data){ messageList.html(data.responseText); updateShoutbox(); //reactivate the send button $("#send").attr({ disabled:false, value:"Shout it!" }); } }); } else alert("Please fill all fields!"); //we prevent the refresh of the page after submitting the form return false; }); [/code]
As you can see we are making use of some previously defined functions like checkForm() to check if all fields are filled and updateShoutbox() to refresh the shoutbox content. In addition, we have disabled the submit button of our form till the process isn’t completed.
In this case we are sending more information in the data parameter of the $.ajax() function: nick and message, it will allow us to save in our shoutbox table via php the values of $_POST['nick'] and $_POST['message'].
It’s important to know that if we have more than one variable in data parameter, we need to separate them by using the “&” symbol, like in GET parameters.
All done guys!
Step 6: Testing our amazing Shoutbox!
And that’s all guys, as you can see it’s easy to achieve our goals if we want to learn
That’s all guys, I hope you enjoy this tutorial!
You can try the tutorial online here to see how It is working and download here all sources.
One more thing guys! Remember that you can solve your doubts in our forums and follow os on Twitter to know more about what are we doing in any moment!
See you on next tutorial and remember that we want you suggest tutorials to write!
One more thing…
Real 642-845 exam preparation in easy and fast way! Subscribe for certkiller 642-825 training and pass your 650-177 exam in first attempt.
Calendar Printing Services at PsPrint.com.
Enjoy this post?
Your vote will help us to grow this website and write more entries like this one :)
We available for hire! — Need help with a web or mobile project?
From yensdesign we develop technology projects based on web apps, mobile apps, consulting and databases. We are young and hard workers, passionate about innovation and focused in new technologies. We try to help you, sharing our knowledge acquired on worked projects, while helping the community and showing our capabilities.If you want to ask for a budget, we hare available for hire! Don't doubt in get in touch with us!.
Well you haven’t thought about security. I was able to enter in the message box :
alert(“Security”); and get the alert message box.
I haven’t even looked at the SQL injection. So htmlentities and striptags function in php is a point to start!
@Gafitescu thanks for posting! I forget this part! I am a fu***** newbie
It’s fixed now, thanks!
Nice, but if JavaScript is off, it’s totally unusable:
Messages are never displayed (loading forever), and form does not submit.
You should make it work without JavaScript before adding cool AJAX effects. Once it works without JavaScript, you just have to override behaviors with JavaScript. That way, it will degrade nicelly.
By the way, cool icon set you have. Where is it from?
@Antoine Thanks for posting! But I don’t pretend that it works without javascript, this tutorial it’s to understand a little better the $.ajax() function in jQuery, not to create a simple shoutbox in PHP.
Here you have an article featuring these icons http://yensdesign.com/2008/12/stunning-128-free-icons-wefunction/
Bye!
[...] here to read the rest: Create a shoutbox using PHP and AJAX (with jQuery) | yensdesign … digg_url = ‘http://jilo.biz/mixblog/?p=41410′; digg_bgcolor = ‘#ffffff’; digg_skin = ‘compact’; [...]
[...] the rest here: Create a shoutbox using PHP and AJAX (with jQuery) | yensdesign … digg_url = ‘http://jilo.biz/mixblog/?p=41411′; digg_bgcolor = ‘#ffffff’; digg_skin = ‘compact’; [...]
@Adrián: I am just becoming paranoid, because I see this kind of thing in production websites.
Thanks for the link!
Thanks for the post. I was thinking about doing something like this on my blog over the weekend, didn’t have time, and now I see you did it for me!
Great tutorials.
Great tutorial, I’ll certainly use this in my next project!
Thanks!
I was intending to do something like this over the weekend, but didn’t get around to it. Now you’ve done it for me!
brilliant thx
nhmmhm
Great post. This will help me in my up coming project to create a shout box. Thanks for sharing here
“@Antoine Thanks for posting! But I don’t pretend that it works without javascript, this tutorial it’s to understand a little better the $.ajax() function in jQuery, not to create a simple shoutbox in PHP.”
Really? Doesn’t look like that, reading the title and the article. Maybe “Learning to use the $.ajax() function” would me more appropiate if that’s was your initial intention.
Sarcasm off, it’s really important to understand that a lot of your readers are going to use your tutorials “as is” for production sites. That’s why things like security and degrading, are very important. You should be more responsible with whatever you publish because of that, helping to improve the web in the long term instead of the opposite.
A reader
@A reader thanks for posting! I respect but don’t share your opinion as I said.
I try to help people with my tutorials, and upload the code to try by their selves but I am not “selling” these tutorials as a “package ready to use” and If you read one more time the introduction it says that we will see how to use the $ajax function by creating a dynamic shoutbox, that’s all.
Thanks for posting one more time!
[...] Articolo: Create a shoutbox using PHP and AJAX (with jQuery) [...]
I’m planning to use this in my website and I’m new to this stuff. I was just wondering how can I make the shoutbox to scroll. It fills all my DIV. Thanks.
@Marvin Just activate the CSS property overflow-y in the desired div! And remember to set a height to begin the scroll!
See? That’s what I was talking about.
Of course you can do whatever you want, but think that most people new to this stuff, are going to use your tuts “as is”, with a simply copy & paste. That’d make me think.
Thanks for cool chat script
Tutorial added
http://www.tutorialand.com
Thanks… I’m adding some code in this shoutbox and I hope you could release a version of this with emoticons. Thank you!
Nice man, try adding some page functions too…
Thanks! How to make this chat автообноляемым? That function updateShoutbox (); it was started every 10 seconds.
Sorry…
Thanks! How to make a chat updated automatically? That function updateShoutbox (); it was started every 10 seconds.
[...] Go here to read the rest: Create a shoutbox using PHP and AJAX (with jQuery) | yensdesign … [...]
[...] More: Create a shoutbox using PHP and AJAX (with jQuery) | yensdesign … [...]
I like the shoutbox.
But, can you make it become an auto refresh shoutbox, i mean the shoutbox will refresh automatically every number minutes.
so, it will look like a realtime chatbox.
thx before.
@andha Thanks for posting! It isn’t a good practise make continue refreshing from the server. It’s a shoutbox not a chat.
By the way, If you want to try that, use timers in javascript: http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/
@adrian. iap i know this is shoutbox, not a chatbox, but maybe it’ll be more cool if we make it like a chatbox. i’m using the setTimeout script. and it’s working fine, the shoutbox will be reloaded every 5 seconds without affecting the whole page, because i’m using iframe for the shoutbox. the problem is, each times the shoutbox is being reloaded. the browser will show a loading bar at the status bar, and a rotating thingy at the tab. they are a bit annoying. i don’t want the visitors know that the shoutbox is being reloaded. and i saw a site that could solve the problem, but i don’t have any clues how could they solve that. hope you get my point. and thx for the reply. i do appreciate it so much.
@andha More cool… but not efficient hehe
Take a look at this tutorial http://yensdesign.com/2008/11/creating-ajax-websites-based-on-anchor-navigation/ We are using a timer. I don’t think you need an iframe to achieve it.
Good luck!
chatbox:
//Auto update shoutbox data
setInterval(updateShoutbox, 30000);
Nice write-up! Looking to do something similar with a java backend and dojo framework instead of jQuery. The architecture is what I was having trouble getting my head around but I like the approach you took here. Hopefully, I can get this approach ported over to the java/dojo platform without much trouble.
Незнаю, я на хупс перенёс.
Рашен форевер.
Thanks for the tutorial.
By the way adding page function would be nice to read old ones. Like a guest book.
@adrian : Thx for the link adrian. I’ve combined those two tutorials that you gave to me. And it’s werking great. I now have a chatbox. Thx a lot adrian. Looking forward your new tuts.
thanks a lot….
Hi again
I’m trying to integrate tutorial codes with Pagination (http://plugins.jquery.com/project/pagination) but I’m kind of noob about ajax. Is there any chance to help me Adrian? or any one else?
Thanks
Awesome tutorial. I was wondering if there was any way to make it so that it updates this for everyone (sort of polling the server to check for new messages) so if you write a new message and someone else has the computer open, it updates it for them too. is there something in jquery that allows you to do that?
@Vikram sorry but it’s harder than you expected… You will need to use something like “sockets” called comet or server push. Take a look at google…
Good luck!
@Vikram, sure. That’s what i’m doing with my site. Even i haven’t hosted it, still on construction in my localhost. And i did that all by using jquery. I made the shoutbox (or i should call that chatbox) refreshes every 5 seconds, without making the browser reload the whole page. Thx to Adrian who provided me the link to the tutorial. So that i could combine that tutorial with this.
grgrrgrgr
[...] 17. Create a shoutbox using PHP and AJAX (with jQuery) [...]
wow… very helpful tutorial.. thxs
[...] Chat-Raum für die Benutzer der Seite. Wie kriege ich die jetzt aber sicher und elegant hin? Die Lösung mit AJAX/php/jQuery findet sich als Anleitung bei [...]
I recently try this script. and I found some problem. when I click “Shout it!” there’s two row inserted on shoutbox(content).Then I checked my database and I just find one row. How it could happen?Please Help Me…
I’ve fixed that. just my fault.
[...] Create a shoutbox using PHP and AJAX (with jQuery) | yensdesign – Tutorials, Web Design and Coding (tags: howto php development javascript ajax web tutorials jquery tutorial shoutbox) [...]
[...] Crer un shoutbox usando Php y Ajax (con jQuery) [...]
[...] Create a shoutbox using PHP and AJAX (with jQuery) | yensdesign – Tutorials, Web Design and Coding – [...]
[...] Create a shoutbox using PHP and AJAX (with jQuery) [...]
[...] Create A Shoutbox Using PHP And AJAX: [...]
[...] mai mult pe tutoriale, ne învaţă (oferă link de fapt) cum cu PHP & AJAX să facem un shoutbox sau o listă to-do. Desigur, multe altele: formulare, încărcare date în tabele, schimbarea [...]
[...] 17. Create a shoutbox using PHP and AJAX (with jQuery) [...]
[...] Create a shoutbox using PHP and AJAX (with jQuery) [...]
what do I have to do to implement this to joomla
nice!
great job!
[...] Create a shoutbox using PHP and AJAX with jQuery [...]
[...] 9. 使用PHP + AJAX创建一个Shoutbox [...]
[...] 17. Как создать чат с использованием PHP и AJAX (с jQuery) [...]
[...] YensDesign est un site que je viens de découvrir et qui s’avère extrêmement riche en matière de programmation. [...]
[...] visualizzare un esempio cliccando qui. La guida completa la potete trovare a questo indirizzo web: http://yensdesign.com/2009/01/create-a-shoutbox-using-php-and-ajax-jquery/ Questo articolo è stato pubblicato venerdì 10 aprile 2009 alle ore 18:55 all’interno [...]
You really shouldn’t post tutorial like these… many ppl will follow it and create ajaxified things that displays nothing with JavaScript disabled :/
if no javascript enabled, u can’t use perhaps 99% of the web apps…
if u dislike JS, pls go back to oldie of “web1″, click submit, pull the server, return whole page, again again again.
hw about graphic, CSS, javaapplet, flash, silverlight, flex, adobe air…etc. disable all and go to sleep. web isn’t right for u.
esta muy bueno el shoutbox pero deberian de limpiar el textbox del mensaje cuando uno presiona el boton “send” asi ya no se enviaria varios mensajes con el mismo contenido
should clear the textbox of “message” after sending the comment
I tried to look in the forum for some troubleshooting advice but it seems it’s not there anymore or the link isn’t working. Anyway, here’s the problem I’m having:
When I press submit, I get the “Loading…” image for a few seconds but then nothing happens. My words still show up and there’s nothing in the shoutbox. I’ve poured over everything numerous times but this isn’t something I know much about so I haven’t found what’s wrong. Any suggestions on what the problem might be?
Thanks!
[...] Site: http://yensdesign.com/2009/01/create-a-shoutbox-using-php-and-ajax-jquery/ [...]
Hi. Could you describe please, how to automatically refresh content when new message added? Or, just how to repeat function “updateShoutbox” each 5 seconds? I tried “window.setTimeout(“updateShoutbox()”,5000);” but it doesnt works.
[...] 10. Create a shoutbox using PHP and AJAX [...]
Hello! Thanks for this plugin…
A question : It’s possible to transform your shoutbox plugin into a comments plugin ? I would like to post a comment based on the news ID.
I add a field “id_news” in the table shouthbox. This id_news must match with the ID of the news. Thus, when I click on a news (I can see the ID of the news through the URL), I want to post a message or several messages. All must matches of the ID of the news.
To display messages, I try this method :
$id=$_GET['id'] // To recover the ID of news
SELECT * from southbox WHERE id_news=$id // To display the messages matches of the news
To insert message (match with the ID of a news), I don’t know how to put in place…
But I can’t! I don’t use the proper method. It’s possible to create this plugin ? Can you help me ?
Thanks!
PS: sorry for my english
[...] 10. Create a shoutbox using PHP and AJAX [...]
@Anton: Use setInterval(updateShoutbox, 10000); in the js
hey, how do you fix if the message contain & or + ?
With the + in the message, the + will strip out.
With the & in the message, it will truncate everything after the & and the & itself.
?
wiw..!!
@sql: i think with str_replace we can fix the problem…
example:
sorry…
example:
<?php
echo”<?php
$a = \”My Name is Dan Brown & I’m Cool\”;
$a = str_replace(\”&\”,\”&\”,$a);
?>”;
?>
[...] Create a shoutbox using PHP and AJAX with jQuery [...]
@theovan: this is javascript, no php. The code is in javascript transfer the data to php script.
$.ajax({
type: “POST”, url: “/ajax_shoutbox.php”, data: “action=insert&nick=” + nick + “&message=” + message,
complete: function(data){
How do you add a refresh button besides the shout it button?
[...] View Tutorial No Comment var addthis_pub=”izwan00″; BOOKMARK This entry was posted on Monday, June 8th, 2009 at 4:19 am and is filed under Javascript Tutorials. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site. [...]
please tell me how to implement pagination for this………………
very well written article. thanks a for the step-by-step explanation.
I’ve tried to edit this in many different ways to get it to auto refresh.
None of them have worked. I’ve read your articles on targets and setTimeout.
I can’t figure out how to combine the target method with this script, and the setTimeout, setInterval methods don’t work.
Would it be possible for you to include a tutorial for auto refreshing this great script.
It has been requested so many times.
I am almost at the point of abandoning this script for one that will refresh.
Even if it means sacrificing for less quality.
I was able to get it to auto update by using the setInterval method, after I included
header(“Cache-Control: no-cache”);
in shoutbox.php
To clear the input field after submitting,
Add
$(‘#message’).val(”);
After
//reactivate the send button
$(“#send”).attr({ disabled:false, value:”Shout it!” });
I’d also like to solve the & and + issue, if anyone has any ideas.
Really cool program. And @A Reader….. You’re an idiot. Most people looking for AJAX should mostly be experienced web programmers/web scripters. Even if you are a noob it takes like 5 minutes to go to php.net/stripslashes look at the code and apply it accordingly. And htmlentities and all that good stuff. But yeah, Adrian thanks for the tutorial. Your work is appreciated by most.
To fix the “&” and “+” issue
Add
function parseMsg(m)
{
var i=j=1;
while (i || j) {
if(m.indexOf(“+”)!=-1)
{
m=m.substring(0,m.indexOf(“+”))+”%2B”+m.substring(m.indexOf(“+”)+1,m.length);
}
else i=0;
if(m.indexOf(“&”)!=-1)
{
m=m.substring(0,m.indexOf(“&”))+”%26″+m.substring(m.indexOf(“&”)+1,m.length);
}
else j=0;
}
return m;
}
After
//functions
And Add
message=parseMsg(message);
After
var message = inputMessage.attr(“value”);
[...] 10. Create a shoutbox using PHP and AJAX [...]
first of all I added this to make the text clear after submit someone may find it usefull
function clear_form_elements(ele) {
$(ele).find(‘:input’).each(function() {
switch(this.type) {
// case ‘text’:
case ‘textarea’:
$(this).val(”);
break;
this.checked = false;
}
});
}
// onclick=”clear_form_elements(‘#message’)”
Secondly whats with inserting & into mysql i assumed mysql_real_escape_string would take care of that I have played about with addslashes with no luck … Any Ideas?
[...] · Demo Ver Contenido‘ · Tutorial Ver Contenido‘ [...]
This a good article ,
thanks
[...] 10. Create a shoutbox using PHP and AJAX [...]
[...] d’une shoutbox qui ferait office de messagerie interne en utilisant ce tuto. Abandon mais ceci m’a permis de découvrir une technologie intéressantes : l’ajax qui [...]
You are using an XHTML Doctype.
In XHTML you should mark empty tags as instead of .
Sorry, no offense and that Transitional isn’t better either.
BUT still a great tutorial!!
THX
sorry my tags got strip_tagged away
(open tag)ul /(close tag) instead of (open tag)ul(close tag)
[...] Create a shoutbox using PHP and AJAX (with jQuery) [...]
[...] Create a shoutbox using PHP and AJAX (with jQuery) | yensdesign – Tutorials, Web Design and Co… (tags: ajax javascript jquery tutorial web2.0 shoutbox) [...]
[...] Create a shoutbox using PHP and AJAX (with jQuery) [...]
the chat box does not response when I’ve submitted the messages. Messages are never displayed (i mean loading forever), and form does not submit when I checked on my database. But your live demo chatbox is work. I don’t know why, please help me!
BTW, i’m apologize about my bad english
[...] and recover data from a MySQL database via PHP in a way asynchronous ajax, jquery, shoutbox, php Tutorial Posted in ajax | Tags: ajax, asynchronous, database, jquery, mysql, php, shoutbox How to [...]
Is it possible to add a captcha? Every Caprcha script I found uses POST to send the data to a PHP file… but how can this implemented in this script?
[...] 9 – Create a shoutbox using PHP and AJAX [...]
A very nice work
I found your page when seeking for a clone of facebook chat bar
but anyway
i want to add a chat to my new website so may be i’ll take yours )
Thanks anyway )
[...] Tutorial | Demo VN:F [1.7.7_1013]please wait…Rating: 0.0/10 (0 votes cast)VN:F [1.7.7_1013]Rating: 0 (from 0 votes)Share it Share Tags: guestbook, Jquery, shoutbox, Tutorial This entry was posted on December 2, 2009 at 12:38 am, and is filed under Jquery, ajax. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. [...]
great tutorial,
fast loading when i try…
[...] 9. Create a shoutbox using PHP and AJAX [...]
[...] http://yensdesign.com/2009/01/create-a-shoutbox-using-php-and-ajax-jquery/ [...]
On Local, (heasyphp v.5.2.10) i have error:
Notice: Undefined variable: result in C:\Programmi\EasyPHP5.2.10\www\shoutbox\shoutbox.php on line 60
This is a very interesting site. ^.^
thank you very much good archives tahanks
there is a little problem.
when i said something,i can see it in your shoutbox in my computer,i don’t need to refrash the ie;
but other’s computer can’t see it ,they need to refrash.
how to fix it?
[...] 8. Create a Shoutbox [...]
ok this is my issue:
i have everything working fine except in internet explorer, the comments don’t show, but they are put into the database. in google chrome they do show. im wondering why this is, but can’t figure it out.
also, how and where do you insert the overflow-y to give the shoutbox a scroll bar? i tried putting it in the css under .content, but it squeezes the div container and gives it a horizontal (overflow-x scroll) scroll bar as well. how do fix these problems???
Excellent tutorial, I find it amusing that a few people are complaining about the fact that it uses javascript…. what do these people think AJAX stands for!!!
Asyncronous JAVASCRIPT and xml!!
there was a clue in there somewhere.
thanks alot
If you like autoreload, look at this:
function checkReload(){
var checkbox_status = $(‘#autoreload’).attr(“checked”);
var checkbox_obj = $(‘#autoreload’);
if (checkbox_status) {
$(‘#onoff’).stop(true, true).fadeIn(300).text(“Autoreload is on”).delay(2000).fadeOut(400);
updateShoutbox();
intervalID = setInterval(updateShoutbox, 20000);
} else {
$(‘#onoff’).stop(true, true).fadeIn(300).text(“Autoreload is off”).delay(2000).fadeOut(400);
clearInterval(intervalID);
updateShoutbox();
} }
$(‘#autoreload’).click(function() {
checkReload();
});
checkReload();
And add this where ever you want
appendix :
And add this where ever you want
>input type=”checkbox” id=”autoreload” checked=”checked” class=”button2″ /<
>span style=”padding-left:5px;” id=”onoff”< >/span<
SQL injection?
Please use since php 5.1:
$dbh->exec(“INSERT INTO REGISTRY (name, value) VALUES (“.$dbh->quote($name,PDO::PARAM_STR).”, “.$dbh->quote($value,PDO::PARAM_INT).”)”);
instead of:
mysql_real_escape_string
Hi,I just want to add refresh button,I try to add new form named “refresh” with html,then add $(“#refresh”).submit(function(){ updateShoutbox();}); to javascript,but it refresh whole page not just message list.
Need help,thanks!
[...] 10. Create a shoutbox using PHP and AJAX [...]
hi! do you know how to clear the forms after sending the message.? I tried your codes and i added autoclear on the shoutbox.js, the autoclear works but it will refresh the whole page.
Could not connect: php_network_getaddresses: getaddrinfo failed: No such host is known.
Nice script but how can i fetch only recent 3 records to be shown in the shoutbox?
Hi!
I have an error
Notice: Undefined variable: result in C:\wamp\www\chat\shoutbox.php on line 62
How can i fix it?
hi everybody. Adrián Mato Gondelle : Realy good work , i like it . But , i have a question . When im response text like in tutorial , it’s working good . But when i’m trying show last_tweet in bottom of shoutbox all my dreams felldown. I’m using code like this :
//shoutbox.php update
for($i=$num_row;$i>=0;$i–){
echo (““.$row[$i]['name'].
“ : “.$row[$i]['tweet'].”");
}
//shoutbox.js updateShoutbox();
messageList.html(data.responseText);
and nothing more.
Can i show last_tweet in bottom of shoutbox and how ? Any idea, i realy need your help .
So sory for my broken English…
Anyone say how to add sound alert on new shoutbox message?
Thanks in advance!
Very nice script! I’m working on putting captcha on it, I’ll post back some details here in case anyone will be needing it. Thanks!
[...] Tutorial [...]
This was really easy to follow! Thanks for the help.
[...] 3. Create a shoutbox using PHP and AJAX (with jQuery) [...]
“.$row['user'].”\”-\”".$row['message'].” “.$row['date'].”"; } echo $result; break; case “insert”: echo insertMessage($_POST['nick'], $_POST['message']); break; } mysql_close($link); } ?>
I got these error on my Latest Message box, why?
I’m using WampServer 2.1.
Thanks before
pls help i cannot run this application T_T .. i am just a beginner.. pls help me what i must config
pls help me.. i do not know where to config.. i am just a beginner.
Hi,
Very nice code….
is it possible to make the viewpane scrollable.. so you can scroll back to the very first input ?
[...] 10. Create a shoutbox using PHP and AJAX [...]
N!ce post i;m now using it.
Very well done and beautiful!
so I want to make a chatbox with “online” status………like gmail’s and facebook’s status for online, busy, or offline………..where in this code could I do this? I have a database that updates when user is logged in/off……….so as soon as it changes in the database, i want it to reflect on my site? I was told that some code here could do that…..but I am unable to find which piece or how to do it?
one more thing.. after shouting the shout the fields are not reset…
Hi, Neat post. There is a problem with your site in internet explorer, would check this… IE still is the market leader and a big portion of people will miss your excellent writing due to this problem.
[...] and its functions.Do let us know which one of them is your favourite tutorial?Smart Image ResizerCreate a shoutbox using PHP and AJAXSend Hassle Free and dependable HTML emails with PHPRetrieve Your Gmail Emails Using PHP and IMAPHow [...]
[...] Read Full Article [...]
Hi
(“.content > ul”) means (“.content ul”)? or something else? new to jquery.
London Stock market…
[...]Create a shoutbox using PHP and AJAX (with jQuery) | yensdesign – Tutorials, Web Design and Coding[...]…