Geekpedia Programming Tutorials






PHP and Javascript: Dynamic update with MySQL

This tutorial shows you how to create a Web page that extracts information from a MySQL database without refreshing the page (dynamic update). Javascript and PHP knowledge is required

On Wednesday, October 5th 2005 at 04:21 PM
By Nabeel Akhtar (View Profile)
****-   (Rated 4.1 with 23 votes)
Contextual Ads
More PHP Resources
Advertisement


In this tutorial we will create a web page that extracts data from a MySQL database without having to refresh the page. That is right... the web page will not be refreshed and the information will show up in the existing web page. -- Impressed?



Before you start reading the tutorial, I recommend that you take a look at this script in action. This will give you an idea of what the end product will look like.



For this tutorial we will be creating two files:



  • mysql_insert.html (YES, HTML. This is the page that users will see)



  • mysql_insert.php (This file will do all the hard work and will return results to mysql_insert.html)




The Flow:



This approach makes use of JavaScript and updates elements in the parent page from a child page. You can pass variables
to the child file and process information using PHP. Core concept for this tutorial was drawn from a tutorial posted on devshed.com. This tutorial takes the same approach but it also shows how you can add/query data from mysql on the fly.



This tutorial does not discuss the basics. If this is your first time creating a page that updates without having to reload, read this tutorial.



Lets Get Down and Dirty:



In order to create this functionality on your web-server, you will have to create a table in your mysql database. I created a table and called it php_js. This table will store the user information. Following is the code to create a table:







CREATE TABLE `php_js` (
`srno` INT NOT NULL AUTO_INCREMENT ,
`u_name` VARCHAR( 50 ) NOT NULL ,

`u_email` VARCHAR( 55 ) NOT NULL ,

PRIMARY KEY ( `srno` )
);



The three columns that in the table are "srno", "u_name" and "u_email". Names will be stored in the u_name column and email addresses will be stored in the u_email column.



Now lets look at the code in the HTML and PHP files. Here is the code to the html file:



mysql_insert.html








In the HTML file we have defined two functions (attach_file and show_hint). The attach_file() function calls up another file and appends the information to the parent (this) page. The show_status() function updates the text in the status box. When the page loads, the default text is set to "Ready..." but once the user presses the button to submit the information, the function is called again and the text is set to "Busy...". The text in the status box will read "Busy..." until all the data has been processed and displayed in the parent window. This is a pretty nice tool and lets you know when the system is ready. You can further enhance the application and maybe display an image while the information is being loaded.



<span id="from_mysql">
</span>
is the most important field in the html file. The table that you see (with user names and email addresses) is constructed within this span field. If you change the name (id) of this span, be sure to change the name in the mysql_insert.php file.



When the child window is called, parameters from input fields are passed along. You might have noticed that in the line that reads




onClick="javascript:attach_file( 'mysql_insert.php?u_name=' + u_name.value + '&u_email=' + u_email.value) ; show_status('Busy');



Our other file is called mysql_insert.php and this is the file that adds and queries the database. All the information is stored in a variable and then javascript is used to update the information on parent window.



mysql_insert.php







We start off with PHP tags and define a header as

header( 'Content-Type: text/javascript' );

This tells the browser to treat this file as a text file with javascripts. However within the file we have PHP functions that process in the information.



Next I have made a connection to the database. Be sure to change the Database Name and define your username and password.



The IF block is executed if the user has typed in a Name and a valid Email in the input fields. If these values were entered, the information is stored in the database.





Next, all the information from the table is queried and stored in a variable called $output. Once the information is stored, javascript's getElementById method is used to update the <SPAN> tag that we created in the Parent window.


This is in no way a secure script. You will have to modify the script to make it secure.



If you have any questions about this tutorial, please contact our team at http://www.nabeelakhtar.net/contact/ or

for discussion go to http://forum.nabeelakhtar.net



More tutorials available at http://www.nabeelakhtar.net/tutorials/

Live Online Support available at http://www.nabeelakhtar.net
Digg Digg It!     Del.icio.us Del.icio.us     Reddit Reddit     StumbleUpon StumbleIt     Newsvine Newsvine     Furl Furl     BlinkList BlinkList

Rate Rate this tutorial
Comment Current Comments
by Tejal on Tuesday, March 14th 2006 at 07:32 AM

Hi ,

I want to write content in file.But my content is comes from javascript.so how can i do this .

Thnaks,
Tejal.

by chris on Wednesday, August 9th 2006 at 09:23 PM

After cleaning up all the code. and fixing the php, it works great. THANKS!

If you can't get it to work, all you have to do is:

remove all of the <br /> tags in the mysql_insert.html, in the java and css script sections, and in the mysql_insert.php. Also in the mysql_insert.php you have to add '. and .' between all the variable declaration.

by avi on Sunday, September 24th 2006 at 10:51 AM

it doesnt work

i remove the br
\"
you have to add \'. and .\' between all the variable declaration.\"

i dont understand where i need to put them

by Yesid Hernandez on Tuesday, February 13th 2007 at 08:37 PM

Hi, thanks for the tutorial although I had to do some changes to get it working. I would like to know how can I do to do the new query and get just one result table. I have seen that every time I add a user the table draws all again. Thanks in advance for you help.

by mickael on Monday, June 25th 2007 at 08:20 PM

ffewre

by velislav on Friday, June 29th 2007 at 08:03 PM

to work proper :
1. remove <br /> as chris wrote

2. wellwriten code must be ( .. ) and (..) and (..) but it works fine in the current style also

3. put \\ BACKSLASH before each \" except the first and the last one i line $output = ...
the line must be:
$output = \"<table width=\\\"600\\\" border=\\\"0\\\" cellpadding=\\\"3\\\" cellspacing=\\\"0\\\" class=\\\"table1\\\"><tr><td width=\\\"41\\\" align=\\\"center\\\" bgcolor=\\\"#3366CC\\\"><span class=\\\"style1\\\">Srno</span></td><td width=\\\"149\\\" align=\\\"center\\\" bgcolor=\\\"#3366CC\\\"><span class=\\\"style1\\\">Name</span></td><td width=\\\"384\\\" align=\\\"center\\\" bgcolor=\\\"#3366CC\\\"><span class=\\\"style1\\\">Email</span></td></tr>\";

4. BEWARE when test: proper names are that containing MORE THAN ONE letter

by Jens on Thursday, August 2nd 2007 at 08:49 AM

you need to change this line aswell in order to make it work:

$output .= "<tr class="$row_style"><td>$srno</td><td>$u_name</td><td>$u_email</td></tr>";

needs to be:

$output .= "<tr class=\"$row_style\"><td>$srno</td><td>$u_name</td><td>$u_email</td></tr>";

by jens on Thursday, August 2nd 2007 at 08:50 AM

$output .= "<tr class=\"$row_style\"><td>$srno</td><td>$u_name</td><td>$u_email</td></tr>";

i ment :)

by jens on Thursday, August 2nd 2007 at 08:51 AM

hmm just add slashes around "$row_style" :)

by Ztarlight on Saturday, August 18th 2007 at 08:00 AM

An easier way to do this is to just change the apostrophe.. from double (\") to a single (\') in the beginning and the end. This allows the html-tags to stay the way they should without php messing things up.

Example:
$output .= \'<table width=\"600\" border=\"0\" cellpadding=\"3\" cellspacing=\"0\" class=\"table1\"><tr><td width=\"41\" align=\"center\" bgcolor=\"#3366CC\"><span class=\"style1\">Srno</span></td><td width=\"149\" align=\"center\" bgcolor=\"#3366CC\"><span class=\"style1\">Name</span></td><td width=\"384\" align=\"center\" bgcolor=\"#3366CC\"><span class=\"style1\">Email</span></td></tr>\';


Just copy these files.. but they won\'t work without the database.


================================================
mysql_insert.html

<html>
<head>
<script language=\"JavaScript\"><!--
//these function from:
//http://www.devshed.com/c/a/PHP/PHP-and-JavaScript-Pooling-Your-Resources/
//this function calls the child file
function attach_file( p_script_url ) {
// create new script element, set its relative URL, and load it
script = document.createElement( \'script\' );
script.src = p_script_url;
document.getElementsByTagName( \'head\' )[0].appendChild( script );
}

//this function updates the status box
function show_status( status_text ) {
document.getElementById(\'status\').innerHTML = status_text;
}
//-->
</script>
<title>PHP MySQL and Javascripts Working Together </title>
<!-- CSS Details -->
<style type=\"text/css\">
<!--
.table1 {
border: 1px solid #CC6600;
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 10px;
font-style: normal;
text-transform: none;
}
body {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 8px;
background-position: center top;
margin: 0px;
padding: 15px;
}
input {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 10px;
font-style: normal;
font-weight: bold;
font-variant: normal;
color: #0099CC;
background-color: #FFFFCC;
border: 1px solid #FF9900;
}
.row1 {
background-color: #CCFFCC;
}
.style1 {
color: #FFFFFF;
font-weight: bold;
}
.row2 {
background-color: #FFFFFF;
}
-->
</style>
</head>

<body onLoad=\"javascript:attach_file( \'mysql_insert.php\' ) ; show_status(\'Ready...\'); \">
<table width=\"600\" border=\"0\" cellpadding=\"1\" cellspacing=\"3\" class=\"table1\">
<tr>
<td width=\"88\">Status Box: </td>
<td width=\"493\" bgcolor=\"#CCCCCC\"><span id=\"status\" /></span> </td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td>Name</td>
<td><input name=\"u_name\" type=\"text\" id=\"u_name\" size=\"40\" maxlength=\"40\"></td>
</tr>
<tr>
<td>Email</td>
<td><input name=\"u_email\" type=\"text\" id=\"u_email\" size=\"40\" maxlength=\"45\">
(email MUST contain the \'@\' and \'.\') </td>
</tr>
<tr>
<td> </td>
<td><input type=\"button\" name=\"Button\" value=\"Click Here to Insert into Mysql...\" onClick=\"javascript:attach_file( \'mysql_insert.php?u_name=\' + u_name.value + \'&u_email=\' + u_email.value) ; show_status(\'Busy\'); \"></td>
</tr>
</table>

<br>
Data from MySQL: <br>

<!-- Do not remove this or the table will not show up -->
<span id=\"from_mysql\">
</span>

<br>
</body>
</html>

==============================================
mysql_insert.php

<?php
header( \'Content-Type: text/javascript\' );
//database info: Change password and DB Name
$db = mysql_connect(\"localhost\", \"root\", \"\") or die (mysql_error());
mysql_select_db (\"test\", $db) or die (mysql_error());

//get values if input fields
$u_name = addslashes($_GET[\'u_name\']); //Name
$u_email = addslashes($_GET[\'u_email\']); //Email

//If name and email are NOT empty, insert into mysql
if (strlen($u_name)>1 and strlen($u_email)>1 and strstr($u_email,\"@\") and strstr($u_email,\".\") ) {
$insert = mysql_query(\"INSERT INTO php_js (u_name, u_email) VALUES (\'$u_name\', \'$u_email\')\",$db) or die(mysql_error());
}

//Now Refresh the table at the bottom id=from_mysql
$row_count = 0;
$output = \'<table width=\"600\" border=\"0\" cellpadding=\"3\" cellspacing=\"0\" class=\"table1\"><tr><td width=\"41\" align=\"center\" bgcolor=\"#3366CC\"><span class=\"style1\">Srno</span></td><td width=\"149\" align=\"center\" bgcolor=\"#3366CC\"><span class=\"style1\">Name</span></td><td width=\"384\" align=\"center\" bgcolor=\"#3366CC\"><span class=\"style1\">Email</span></td></tr>\';
$result = mysql_query(\"SELECT srno, u_name, u_email FROM php_js\",$db) or die (mysql_error());
While( $rows = mysql_fetch_array($result)) {
$srno = $rows[\'srno\'];
$u_name = $rows[\'u_name\'];
$u_email = $rows[\'u_email\'];
$row_style = ($row_count % 2) ? \"row1\" : \"row2\";
$output .= \'<tr class=\"\'.$row_style.\'\"><td>\'.$srno.\'</td><td>\'.$u_name.\'</td><td>\'.$u_email.\'</td></tr>\';
$row_count = $row_count + 1;
}
//Free Results
mysql_free_result($result);
$output .= \'</table>\';
?>

from_mysql_obj = document.getElementById( \'from_mysql\' );
from_mysql_obj.innerHTML = \'<? echo $output; ?>\';


//update status box
my_status = document.getElementById( \'status\' );
my_status.innerHTML = \'Ready...\';

//clear values from text fields
document.getElementById(\'u_name\').value = \'\';
document.getElementById(\'u_email\').value = \'\';
?>

by Richard on Wednesday, January 9th 2008 at 05:35 PM

I also needed to remove the last
?>
from the mysql_insert.php above
and it finally worked.

by Jiim Mashore on Wednesday, March 26th 2008 at 09:50 AM

I copied the code above and run the program. Everything works fine as long as you don\\\'t submit the same record twice in a row (ie same u_name and u_email). This only really became apparent when I started trying to modify the code to match my needs. A easy way to overcome this hurdle (with my limited knowledge of .js) is to always have a variable you post that is different. For instance in my case, I include :

------------------ Begin Code Block ----------------------
<a href=\\\"javascript:curr_time =new Date();callServer(\\\'update_RINEX_Order.php?x_var=\\\'+curr_time.getSeconds());show_status(\\\'Busy..\\\');\\\">Call server now!</a>
---------------------- End Code Block ---------------------

This seems to solve the problem although I suppose if someone were getting really busy on the mouse it could cause the problem to reoccur but it seems to clear itself up once the time value changes.

I\\\'d be interested in knowing if anyone else has experienced this behaviour and what they did to resolve it.

by Endrik on Tuesday, September 16th 2008 at 04:30 AM

Very Nice coding...man..!

Million Thanks

by Nicky on Friday, September 26th 2008 at 04:08 AM

This code was very useful when I got it working.It worked fine with ie6 but then I switched (belatedly) to ie7 and it doesn't work anymore. Does anyone have any ideas why it should stop working with ie7?

Any help gratefully received...


Comment Comment on this tutorial
Name: Email:
Message:
Comment Related Tutorials
There are no related tutorials.

Comment Related Source Code
There is no related source code.

Jobs PHP Job Search
My skills include:
Enter a City:

Select a State:


Advanced Search >>
Latest Tech Bargains

Advertisement

Free Magazine Subscriptions

Today's Pictures

Today's Video

Other Resources

Latest Download

Latest Icons