A step by step tutorial teaching you how to create your own chat client and chat server easily in C#, for local networks or the Internet.
A C# tutorial showing you how to make use of WMI to extract information on disk drives, such as model, capacity, sectors and serial number.
This tutorial will teach you how to calculate the shipping cost based on the weight, height, length and depth of the box, the distance and the UPS service type.
Creating a Rich Text Editor using JavaScript is easier to do than you might think, thanks to the support of modern browsers; this tutorial will walk you through it.
PHP and Javascript: Dynamic update with MySQLThis 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 3.8 with 39 votes) |
||
|
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:
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:
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 It!
Del.icio.us
Reddit
StumbleIt
Newsvine
Furl
BlinkList
|
|||
|
|||
Current CommentsHi ,
I want to write content in file.But my content is comes from javascript.so how can i do this .
Thnaks,
Tejal.
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.
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
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.
ffewre
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
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>";
$output .= "<tr class=\"$row_style\"><td>$srno</td><td>$u_name</td><td>$u_email</td></tr>";
i ment :)
hmm just add slashes around "$row_style" :)
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 = \'\';
?>
I also needed to remove the last
?>
from the mysql_insert.php above
and it finally worked.
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.
Very Nice coding...man..!
Million Thanks
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...
Cool - worked for me on both IE7
I love U! But i wrote my own version shorter and integrated with my framework.
Thank U very much!
I copied the code from Ztarlight, and I deleted the line specified by Richard; but does not work
fsdfdsfdsfdf
fsdfdsfdsfdf
fsdfdsfdsfdfsdsadsad
The above code does not work in IE7 ??
can anyone help with solution..
hello test
hello test
hello test
I tried changing the values eg newstitle not u_name but I just get the error newstitle is not define when it is the name of the field etc/
Original tutorial, not a copy:
http://www.nabeelakhtar.net/tutorial/25.php#
Hi! Nice tutorial! But i have a question for you. Say i want to send the data from the database to a option in select (html). If i want to submit something from one option, and the script is running, is it still working or will the selected option be unselected while this script is running?
Hope you understand my question.
Best regards!
Ok this has to be one of the coolest things ever! I've been needing to do this for a while but figured that I couldn't (with the php and js being on different sides) and this is perfect! I know I'm several years late, but thanks so much!
fs
http://www.aridetowncar.com
Related Tutorials
Related Source Code
PHP Job Search