AJAX callbacks with jQuery
Step 1 : Linking jQuery
Include the jQuery library in your section as following (i used version 1.2.1, but this changes a lot):
HTML4STRICT
- <script type="text/javascript" src="../jquery-1.2.1.js"></script>
Step 2 : The callback
Next, add this JavaScript function to the . In this function, all the "magic" happens:
JAVASCRIPT
- function addNumbers() {
- var number1 = $('#number1').attr('value');
- var number2 = $('#number2').attr('value');
- $.get("giveMeSomething.php", { number1: number1, number2: number2 },
- function(data){
- alert("Data Loaded: " + data);
- });
- }
In line 2 we get the calue from the first field in our page. This variable is used in row 4 again in the AJAX callback. In line 3, we do the same for the second field. In line 4 to 7 is the actual AJAX callback. I put this function on multiple rows for readability, but you can put it on one line if you like.
The first parameter is the file you want to do the call on. This can be PHP or whatever. I made a file in the same directory as the HTML file, called "giveMeSomething.php". In this file, all the actions are done (see step 4). The second parameter (between curly brackets) contains all the values you want to pass to the PHP file. The values are delimited bij comma's. Left of the : is the name of the variable in the PHP file, and right of the : is the value (in this case the vars you defined in line 2 and 3).
At last we define a function that is executed after the callback finishes. The data you get (and display in an alert) is everything that was echo-ed in the PHP file.
Stap 3 : Form
Add the input fields to the :
HTML4STRICT
- <input type="button" onclick="addNumbers();" value="=" />
Stap 4 : PHP file
Create a new PHP file with the name "giveMeSomething.php" and this content:
PHP
- <?
- ?>
Comments
Name: Goinglogo (09 May 2010 - 18:20)
Brilliant example with all principles included.A great starting point.
Name: jeet Lal Patel (10 November 2009 - 10:22)
Thanks a lot for ajax with jquery examplesName: Najam (11 September 2009 - 19:45)
Stap 3 and Stap 4 sounds funny.. :DName: riz (03 December 2008 - 07:18)
Easy to understand...same tim i need to upload a file
Name: Jacek (16 September 2008 - 12:57)
Where is error handling!?Name: Andy J (28 November 2007 - 20:54)
Hahaha... I second that, DreamDealer. Thanks for the quick and dirty of it!Name: DreamDealer (19 November 2007 - 09:49)
I think the title of the tutorials says enough on what the tutorial is about.Name: lucian ciufudean (12 November 2007 - 18:29)
The "main point" at the beginning of a tutorial is to say what the tutorial is about and not that "This tutorial is not very well suited for inexperienced webdevelopers" !

