TalkPHP
 
 
Account Login
Latest Articles
» The basic usage of PHPTAL, a XML/XHTML template library for PHP
» Vulnerable methods and the areas they are commonly trusted in.
» Simple way to protect a form from bot
» The Basics On: How Session Stealing Works
» How to keep your forms from double posting data
IRC Channel
IRC Speech Bubble Join the friendly bunch on IRC...
(#TalkPHP on Freenode)

...Also available via a web interface.

See this thread for information on the TalkPHP Free Hugs Initiative™. Subject to availability.
Associates
Associates
CSS Tutorials
Advertisement
Simple AJAX with JQuery
   i. The Aim of this Article
By the end of this article, you will hopefully understand how to add data, submitted via a form, into a MySQL database without reloading the entire page (the asynchronous part) and show a message saying so.

ii. Diving Straight In
Including our Framework
First we should include our jQuery file, which can be downloaded at http://www.jquery.com:

Code:
<script type="text/javascript" src="jquery.js"></script>
That was easy enough!

By the way, during development and testing you can link to the most up to date version of jQuery via the following link:
http://code.jquery.com/jquery-latest.js

The form
This is normal HTML. My example is a simple newsletter subscription form.

Code:
	<form action="" method="post">
			<p>
				<label for="name">Name:</label><br />
				<input type="text" name="username" id="name" size="25" />
			</p>
			<p>
				<label for="email">Email:</label><br />
				<input type="text" name="email" id="email" size="25" />
			</p>
			<p>
				<input type="button" name="submit" id="submit" value="Subscribe" onclick="register()"/>
			</p>

</form>
Note that the button with which we submit the form is not a submit button. Instead, we use a normal button with an onclick value of register() (This will come clear once we get on to the manipulation part.)

The Response Div
Normally, once a script has completed we echo out a message telling the user that the data was inserted into the database successfully (or words to that effect). We can do this with AJAX too. Therefore, we add a response div in which we will echo out our message:

Code:
	<div id="response">
		<!-- Our message will be echoed out here -->
	</div>
Manipulation
Now we can start to manipulate the framework to do what we want it to. I will give the complete code first and then will break it down bit by bit:

Code:
	<script type="text/javascript">

	function register(){
		$.ajax({
			type: "POST",
			url: "submit_data.php",
			data: 	"username=" + document.getElementById("username").value + 
					"&email=" + document.getElementById("email").value,
			success: function(html){
				$("#response").html(html);
			}
		});
		
		}
	
	</script>
On a first glance this may seem a little daunting, but if we really concentrate its not that hard!

Code:
 	function register(){
Remember that register() value we set to onclick in the html form? Well this is the function that it is referring to. It basically means that when the button is pressed, this function will be executed.

Code:
 $.ajax({
This basically sets up our AJAX function

Code:
 type: "POST",
Normally when a form is submitted, its method is either POST or GET. This line tells the browser that we want to use the method POST.

Code:
 url: "submit_data.php",
This is the file we want to be executed when the button is pressed.

Code:
 
	data: 	"username=" + document.getElementById("username").value + 
			"&email=" + document.getElementById("email").value,
Like a normal form submit, we refer to the values our user submits by name="". In this instance, we only require the name and the email. We then use the information our user has submitted so that we can enter the information into the database (in submit_data.php). An example of this is ?username=gareth&email=myemail@email.com

Code:
	success: function(html){
		$("#response").html(html);
Here we basically set what we want to do with whatever is echoed out of submit_data.php. For example, I might echo out: "You are now subscribed to our newsletter. Thank you!" Remember that response div we set up? That will now be placed in that div ($("#response'")).

We then close of the rest of the brackets and the script tag and we are done!

submit_data.php
The last thing to do is to set up our php script. I assume you already know most of this, and how most of this works, so I will give you an example code so that you can edit it to your needs. Note that we access the user information by $_POST['field'] or error checking.

PHP Code:
<?php
    
        
// Variables
            
                
$db_host 'localhost';
                
$db_user 'user';
                
$db_pass 'pass';
                
$db_name 'db';

        
$Username $_POST['username'];
        
$Email    $_POST['email'];    
        
        
// DB
        
        
$connect mysql_connect$db_host$db_user$db_pass ) or die( mysql_error() );
        
$connection $connect;
        
        
mysql_select_db$db_name$connect ) or die( mysql_error() );
    
        
// Inserting into DB
        
        
$qInsertUser mysql_query(" INSERT INTO `database` (`id`, `username`, `email`)
                                     VALUES ( ``, `$Username`, `$Email`)
                                  "
);
        
        if (
$qInsertUser){
            echo 
"You are now subscribed to our newsletter. Thank you!";
        } else {
            echo 
"Error!";
        }
    
    
?>
iii. Conclusion

This article shows just how easy jQuery makes AJAX. Not that this is the only way to accomplish the task, but it is, in my opinion, one of the easiest methods to understand. Of course, this method is totally dependent on the fact that we assume our users have JavaScript turned on. In my next article, I will explain how we can still make the form work if they have it turned off. But, I think for now, this is enough.

Gareth
Report this Article
Last 5 Article Reviews Read All Reviews
   Good Article
Review added by SpYkE112 on 06-01-2008
It is fairly good, but from a newbies point of view, it is bad that you don't secure the mysql query from injections, therefor 4/5 :)
   Nice article
Review added by coiyeun2b on 03-20-2008
Thanks for sharing. Short article but it's very nice :)
   .....
Review added by freenity on 03-10-2008
Nice article, thanks :)
Stupid me making ajax functions from skratch when there is already made solutions :)
   .....
Review added by flyingbuddha on 03-08-2008
Please can an admin remove my replies and tell me how I can post code to this review so other's can read.
   sorry.. code example
Review added by flyingbuddha on 03-08-2008

All times are GMT. The time now is 01:51 PM.

 
     

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0
Inactive Reminders By Icora Web Design