SlideShare a Scribd company logo
1 of 22
Download to read offline
AJAX with jQuery
ACM Webmonkeys 2011
What is AJAX?
AJAX is a technology used to facilitate real-time data
changes and updates on a page without requiring a page
reload.
AJAX stands for Asynchronous Javascript And XML.
Let's break that down:
Asynchronous: The response from the server doesn't
have to be immediate, like a page load does. Other stuff
can happen in-between.
Javascript: The client-side language which you use to
make requests to and handle responses from the server
XML: The format often used to pass data between
Javascript and the server.
No, really, what is AJAX?
AJAX is basically a general term for making your webpage
able to do dynamic stuff on the server (like make a new
post, remove a user, etc) without having the user click on a
link which loads a new page.
It works similar to how any fancy JavaScript effect works,
except that the JavaScript makes a call to some page on
the server in the middle which causes something "real" to
happen.
Remember, JavaScript is client-side. It can't affect the
database directly. It needs to use a technique like AJAX
to cause an actual effect on the server.
A simple example
mypage.html
<h1>Stuff</h1>
<div id="box">
</div>
<a href='javascript:getStuff();'>Get stuff via AJAX.</a>
<script type='text/javascript'>
function getStuff() {
// Pseudocode for simplicity
request = makeHttpRequest("get_stuff.php");
document.box.innerHTML = request.text;
}
</script>
get_stuff.php
<?php
echo "This is the stuff that will go in
the box.";
?>
What happens?
Main idea
With AJAX, we use JavaScript to load a page, but the
output is not loaded directly onto the page.
The AJAX request will look the same to the server as if
the user loaded the page in their browser.
The output must be handled in JS to do what you want.
Don't confuse normal JavaScript functionality with AJAX -- it
only becomes AJAX when a remote call is involved.
Kind of like RPCs for HTML.
So, how do we write pages with AJAX?
There are two sides to an AJAX feature:
The JavaScript, which makes the request
The dynamic page, which does something and returns a
response
The dynamic side can be done in PHP, ASP, Ruby on Rails,
C++, or anything that runs on your webserver.
The JavaScript side needs to be done in JavaScript, of
course, but we have a couple options:
Straight, platform-specific JS (painful)
Wrapper libraries (like Prototype or jQuery)
What is jQuery?
http://www.jquery.com/
jQuery is a JavaScript library based around the idea of
attaching functionality to selected groups of elements.
The main function in jQuery is the selector, $, which
works like:
$("#thisisanid") -- finds the element with that id
$("div") -- finds all divs
Many more syntaxes are supported.
Once a group of elements (or a single element) has
been selected, you can call jQuery functions that act on
the entire group.
It also has some very easy-to-use AJAX wrappers.
More on jQuery
The general structure of writing jQuery is to define events
on elements; for example:
$("#somelink").click(function() { /*...*/ });
You typically pass in a function to the event function, which
specifies what happens when that event is triggered.
The function passed in is a closure, meaning it can refer
to any variable in the current scope.
$("somelink").ready(function() { // EVENT
$("somelink").fadeOut(); // ACTION
});
A simple example of jQuery
<script type="text/javascript" src="jquery.js"></script>
<body>
<div id="thediv" style="display:none;">
Content not yet loaded.
</div>
<script type="text/javascript">
$(document).ready(function() {
$("#thediv").fadeIn();
});
</script>
</body>
Adding AJAX
That example doesn't use AJAX, just normal JavaScript.
Let's add some AJAX by making the DIV load its contents
from another page.
For now, let's just use a static page. It makes no
difference to JavaScript whether the response comes
from a truly dynamic page, so using static pages is
useful for testing your AJAX code.
Let's first take a look at what jQuery has to offer for AJAX...
jQuery's shorthand AJAX methods
Let's look more in depth at the get() method.
jQuery.get()
The get() function is a method of the jQuery object, so we might
call it like $.get('blah.php'). The full arguments are:
Making a GET request with AJAX
As a reminder, GET data is passed as URL arguments (e.
g., ?foo=bar&a=c&b=2). So, a GET request is just loading a
specific URL with those arguments holding the request data.
So, if we want to load the URL data.txt (no arguments being
passed) and put the response (just the file's text) into the
div, we could do:
$.get('data.html', function(response) {
alert("Data incoming...");
$("#thediv").html(response);
});
Even simpler
If all you need to do is make a simple GET request, you can
just use the load function (applied to an element directly).
For example, we could just do:
$("#thediv").load('data.html');
Applying AJAX
Now that we've seen how to make an AJAX request, let's
take a look at how to use it to improve our web pages.
Remember, AJAX is just a way to make a web request
without reloading the page.
We can't do anything with it that we couldn't do without
it, but we can make things seem faster, and not require
reloading the page.
Checking username availability
Suppose we have a site that lets users create accounts with
custom usernames. However, no two users can share the
same username, so during the registration process we need
to let them know if there's a conflict.
We could do this by checking after they submit the form, but
let's write a system that automatically checks availability.
The process we want is:
User tabs out of the username field
Make an AJAX request to see if username is taken
Update form to display whether or not username is taken
The easy part -- server side
We'll need a server-side script to check whether or not a
username is taken. Let's write a username_check.php page
which takes one argument, username, that we'll call like:
username_check.php?username=blah
It'll look something like:
<?php
// connect to database somehow...
$sql = "SELECT 1 FROM users WHERE username='" . mysql_real_escape_string($_GET['username']) ."'
LIMIT 1";
$qry = mysql_query($sql);
if (mysql_num_rows($qry) > 0) {
echo "TAKEN";
} else {
echo "AVAILABLE";
}
?>
Adding an event to the text field
Back on the client side, we need to add an event for when
the user is done typing in their username. This event should
be called when the field loses focus, so we use the .
focusout() event handler in jQuery.
So, our code might be like:
<input id='username' type='text' name='username' />
<div id='username_error_box'></div>
<script type='text/javascript'>
$("#username").focusout(function() {
// ajax call will go here
});
</script>
Handling the AJAX request
We know how to make an AJAX request, so let's do it:
$.get( 'username_check.php',
{ username: $("#username").val() },
function(response) {
if (response == "TAKEN") {
$('#username_error_box').html("This username is taken.");
}
});
Security concerns
You might have noticed that an AJAX request just loads a
page on your website.
That is, anyone can load the same page, and supply
their own arguments to make their own request.
Even if you could enforce only requests coming from
your page, it's easy for malicious users to modify the
JavaScript on your page.
So, you shouldn't pass sensitive information via AJAX,
unless you take proper precautions in encrypting it (and
remember, all encryption has to be done server-side; you
can't do it via JavaScript).
Also, if you're using a login system, make sure to check the
session for proper credentials before fulfilling an AJAX
request. This is a common attack vector.
Summary
AJAX is a technique that lets you make your pages seem
more responsive and flashier.
If you use AJAX to perform sensitive tasks (like deleting
data), make sure your server-side pages can't be exploited.

More Related Content

What's hot

&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
tutorialsruby
 

What's hot (19)

React
React React
React
 
Introduction about-ajax-framework
Introduction about-ajax-frameworkIntroduction about-ajax-framework
Introduction about-ajax-framework
 
How to make Ajax work for you
How to make Ajax work for youHow to make Ajax work for you
How to make Ajax work for you
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
Html web workers
Html web workersHtml web workers
Html web workers
 
ajax_pdf
ajax_pdfajax_pdf
ajax_pdf
 
JAVA SCRIPT
JAVA SCRIPTJAVA SCRIPT
JAVA SCRIPT
 
Direct Web Remoting : DWR
Direct Web Remoting : DWRDirect Web Remoting : DWR
Direct Web Remoting : DWR
 
Jquery beltranhomewrok
Jquery beltranhomewrokJquery beltranhomewrok
Jquery beltranhomewrok
 
JavaScript: DOM and jQuery
JavaScript: DOM and jQueryJavaScript: DOM and jQuery
JavaScript: DOM and jQuery
 
Copy of ajax tutorial
Copy of ajax tutorialCopy of ajax tutorial
Copy of ajax tutorial
 
Java script
Java scriptJava script
Java script
 
jQuery - Chapter 1 - Introduction
 jQuery - Chapter 1 - Introduction jQuery - Chapter 1 - Introduction
jQuery - Chapter 1 - Introduction
 
Java script Advance
Java script   AdvanceJava script   Advance
Java script Advance
 
AJAX
AJAXAJAX
AJAX
 
RicoAjaxEngine
RicoAjaxEngineRicoAjaxEngine
RicoAjaxEngine
 
Java script by Act Academy
Java script by Act AcademyJava script by Act Academy
Java script by Act Academy
 
Ajax Presentation
Ajax PresentationAjax Presentation
Ajax Presentation
 
Ajax
AjaxAjax
Ajax
 

Similar to 1 ppt-ajax with-j_query

Ajax: User Experience
Ajax: User ExperienceAjax: User Experience
Ajax: User Experience
petrov
 
Java Script - A New Look
Java Script - A New LookJava Script - A New Look
Java Script - A New Look
rumsan
 
Using Ajax In Domino Web Applications
Using Ajax In Domino Web ApplicationsUsing Ajax In Domino Web Applications
Using Ajax In Domino Web Applications
dominion
 

Similar to 1 ppt-ajax with-j_query (20)

Writing and Testing JavaScript-heavy Web 2.0 apps with JSUnit
Writing and Testing JavaScript-heavy Web 2.0 apps with JSUnitWriting and Testing JavaScript-heavy Web 2.0 apps with JSUnit
Writing and Testing JavaScript-heavy Web 2.0 apps with JSUnit
 
Ajax
AjaxAjax
Ajax
 
Ajax.ppt
Ajax.pptAjax.ppt
Ajax.ppt
 
AJAX
AJAXAJAX
AJAX
 
Ajax Ppt 1
Ajax Ppt 1Ajax Ppt 1
Ajax Ppt 1
 
Ajax: User Experience
Ajax: User ExperienceAjax: User Experience
Ajax: User Experience
 
Jquery beltranhomewrok
Jquery beltranhomewrokJquery beltranhomewrok
Jquery beltranhomewrok
 
How to Use AJAX in PHP and jQuery.pdf
How to Use AJAX in PHP and jQuery.pdfHow to Use AJAX in PHP and jQuery.pdf
How to Use AJAX in PHP and jQuery.pdf
 
Java Script - A New Look
Java Script - A New LookJava Script - A New Look
Java Script - A New Look
 
JavaScript Libraries
JavaScript LibrariesJavaScript Libraries
JavaScript Libraries
 
Ajax.pdf
Ajax.pdfAjax.pdf
Ajax.pdf
 
Ajax
AjaxAjax
Ajax
 
Ajax
AjaxAjax
Ajax
 
mukesh
mukeshmukesh
mukesh
 
Ajax
AjaxAjax
Ajax
 
Using Ajax In Domino Web Applications
Using Ajax In Domino Web ApplicationsUsing Ajax In Domino Web Applications
Using Ajax In Domino Web Applications
 
Ajax
AjaxAjax
Ajax
 
JavaScript Web Development
JavaScript Web DevelopmentJavaScript Web Development
JavaScript Web Development
 
25250716 seminar-on-ajax text
25250716 seminar-on-ajax text25250716 seminar-on-ajax text
25250716 seminar-on-ajax text
 
M Ramya
M RamyaM Ramya
M Ramya
 

More from Fajar Baskoro

Membangun aplikasi mobile dengan Appsheet
Membangun aplikasi mobile dengan AppsheetMembangun aplikasi mobile dengan Appsheet
Membangun aplikasi mobile dengan Appsheet
Fajar Baskoro
 

More from Fajar Baskoro (20)

Generasi Terampil Digital Skill-2023.pptx
Generasi Terampil Digital Skill-2023.pptxGenerasi Terampil Digital Skill-2023.pptx
Generasi Terampil Digital Skill-2023.pptx
 
Cara Membuat Kursus Online Wordpress-tutorstarter
Cara Membuat Kursus Online Wordpress-tutorstarterCara Membuat Kursus Online Wordpress-tutorstarter
Cara Membuat Kursus Online Wordpress-tutorstarter
 
PPT-Kick Off Double Track 2024 melaksanakan Festival Ramadhan
PPT-Kick Off Double Track 2024 melaksanakan Festival RamadhanPPT-Kick Off Double Track 2024 melaksanakan Festival Ramadhan
PPT-Kick Off Double Track 2024 melaksanakan Festival Ramadhan
 
Buku Inovasi 2023 - 2024 konsep capaian KUS
Buku Inovasi 2023 - 2024 konsep capaian  KUSBuku Inovasi 2023 - 2024 konsep capaian  KUS
Buku Inovasi 2023 - 2024 konsep capaian KUS
 
Pemaparan Sosialisasi Program Dual Track 2024.pptx
Pemaparan Sosialisasi Program Dual Track 2024.pptxPemaparan Sosialisasi Program Dual Track 2024.pptx
Pemaparan Sosialisasi Program Dual Track 2024.pptx
 
Executive Millennial Entrepreneur Award 2023-1a-1.pdf
Executive Millennial Entrepreneur Award  2023-1a-1.pdfExecutive Millennial Entrepreneur Award  2023-1a-1.pdf
Executive Millennial Entrepreneur Award 2023-1a-1.pdf
 
1-Executive Millennial Entrepreneur Award 2023-1-cetak.pptx
1-Executive Millennial Entrepreneur Award  2023-1-cetak.pptx1-Executive Millennial Entrepreneur Award  2023-1-cetak.pptx
1-Executive Millennial Entrepreneur Award 2023-1-cetak.pptx
 
Executive Millennial Entrepreneur Award 2023-1.pptx
Executive Millennial Entrepreneur Award  2023-1.pptxExecutive Millennial Entrepreneur Award  2023-1.pptx
Executive Millennial Entrepreneur Award 2023-1.pptx
 
Pemrograman Mobile - JetPack Compose1.pptx
Pemrograman Mobile - JetPack Compose1.pptxPemrograman Mobile - JetPack Compose1.pptx
Pemrograman Mobile - JetPack Compose1.pptx
 
Evaluasi KPP Program Dual Track Provinsi Kaltim
Evaluasi KPP Program Dual Track Provinsi KaltimEvaluasi KPP Program Dual Track Provinsi Kaltim
Evaluasi KPP Program Dual Track Provinsi Kaltim
 
foto tenda digital skill program dari sekolah
foto tenda digital skill program dari sekolahfoto tenda digital skill program dari sekolah
foto tenda digital skill program dari sekolah
 
Meraih Peluang di Gig Economy yang cocok bagi remaja
Meraih Peluang di Gig Economy yang cocok bagi remajaMeraih Peluang di Gig Economy yang cocok bagi remaja
Meraih Peluang di Gig Economy yang cocok bagi remaja
 
Membangun aplikasi mobile dengan Appsheet
Membangun aplikasi mobile dengan AppsheetMembangun aplikasi mobile dengan Appsheet
Membangun aplikasi mobile dengan Appsheet
 
epl1.pdf
epl1.pdfepl1.pdf
epl1.pdf
 
user.docx
user.docxuser.docx
user.docx
 
Dtmart.pptx
Dtmart.pptxDtmart.pptx
Dtmart.pptx
 
DualTrack-2023.pptx
DualTrack-2023.pptxDualTrack-2023.pptx
DualTrack-2023.pptx
 
BADGE.pptx
BADGE.pptxBADGE.pptx
BADGE.pptx
 
womenatwork.pdf
womenatwork.pdfwomenatwork.pdf
womenatwork.pdf
 
Transition education to employment.pdf
Transition education to employment.pdfTransition education to employment.pdf
Transition education to employment.pdf
 

Recently uploaded

AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 

Recently uploaded (20)

call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions Presentation
 

1 ppt-ajax with-j_query

  • 1. AJAX with jQuery ACM Webmonkeys 2011
  • 2. What is AJAX? AJAX is a technology used to facilitate real-time data changes and updates on a page without requiring a page reload. AJAX stands for Asynchronous Javascript And XML. Let's break that down: Asynchronous: The response from the server doesn't have to be immediate, like a page load does. Other stuff can happen in-between. Javascript: The client-side language which you use to make requests to and handle responses from the server XML: The format often used to pass data between Javascript and the server.
  • 3. No, really, what is AJAX? AJAX is basically a general term for making your webpage able to do dynamic stuff on the server (like make a new post, remove a user, etc) without having the user click on a link which loads a new page. It works similar to how any fancy JavaScript effect works, except that the JavaScript makes a call to some page on the server in the middle which causes something "real" to happen. Remember, JavaScript is client-side. It can't affect the database directly. It needs to use a technique like AJAX to cause an actual effect on the server.
  • 4. A simple example mypage.html <h1>Stuff</h1> <div id="box"> </div> <a href='javascript:getStuff();'>Get stuff via AJAX.</a> <script type='text/javascript'> function getStuff() { // Pseudocode for simplicity request = makeHttpRequest("get_stuff.php"); document.box.innerHTML = request.text; } </script> get_stuff.php <?php echo "This is the stuff that will go in the box."; ?>
  • 6. Main idea With AJAX, we use JavaScript to load a page, but the output is not loaded directly onto the page. The AJAX request will look the same to the server as if the user loaded the page in their browser. The output must be handled in JS to do what you want. Don't confuse normal JavaScript functionality with AJAX -- it only becomes AJAX when a remote call is involved. Kind of like RPCs for HTML.
  • 7. So, how do we write pages with AJAX? There are two sides to an AJAX feature: The JavaScript, which makes the request The dynamic page, which does something and returns a response The dynamic side can be done in PHP, ASP, Ruby on Rails, C++, or anything that runs on your webserver. The JavaScript side needs to be done in JavaScript, of course, but we have a couple options: Straight, platform-specific JS (painful) Wrapper libraries (like Prototype or jQuery)
  • 8. What is jQuery? http://www.jquery.com/ jQuery is a JavaScript library based around the idea of attaching functionality to selected groups of elements. The main function in jQuery is the selector, $, which works like: $("#thisisanid") -- finds the element with that id $("div") -- finds all divs Many more syntaxes are supported. Once a group of elements (or a single element) has been selected, you can call jQuery functions that act on the entire group. It also has some very easy-to-use AJAX wrappers.
  • 9. More on jQuery The general structure of writing jQuery is to define events on elements; for example: $("#somelink").click(function() { /*...*/ }); You typically pass in a function to the event function, which specifies what happens when that event is triggered. The function passed in is a closure, meaning it can refer to any variable in the current scope. $("somelink").ready(function() { // EVENT $("somelink").fadeOut(); // ACTION });
  • 10. A simple example of jQuery <script type="text/javascript" src="jquery.js"></script> <body> <div id="thediv" style="display:none;"> Content not yet loaded. </div> <script type="text/javascript"> $(document).ready(function() { $("#thediv").fadeIn(); }); </script> </body>
  • 11. Adding AJAX That example doesn't use AJAX, just normal JavaScript. Let's add some AJAX by making the DIV load its contents from another page. For now, let's just use a static page. It makes no difference to JavaScript whether the response comes from a truly dynamic page, so using static pages is useful for testing your AJAX code. Let's first take a look at what jQuery has to offer for AJAX...
  • 12. jQuery's shorthand AJAX methods Let's look more in depth at the get() method.
  • 13. jQuery.get() The get() function is a method of the jQuery object, so we might call it like $.get('blah.php'). The full arguments are:
  • 14. Making a GET request with AJAX As a reminder, GET data is passed as URL arguments (e. g., ?foo=bar&a=c&b=2). So, a GET request is just loading a specific URL with those arguments holding the request data. So, if we want to load the URL data.txt (no arguments being passed) and put the response (just the file's text) into the div, we could do: $.get('data.html', function(response) { alert("Data incoming..."); $("#thediv").html(response); });
  • 15. Even simpler If all you need to do is make a simple GET request, you can just use the load function (applied to an element directly). For example, we could just do: $("#thediv").load('data.html');
  • 16. Applying AJAX Now that we've seen how to make an AJAX request, let's take a look at how to use it to improve our web pages. Remember, AJAX is just a way to make a web request without reloading the page. We can't do anything with it that we couldn't do without it, but we can make things seem faster, and not require reloading the page.
  • 17. Checking username availability Suppose we have a site that lets users create accounts with custom usernames. However, no two users can share the same username, so during the registration process we need to let them know if there's a conflict. We could do this by checking after they submit the form, but let's write a system that automatically checks availability. The process we want is: User tabs out of the username field Make an AJAX request to see if username is taken Update form to display whether or not username is taken
  • 18. The easy part -- server side We'll need a server-side script to check whether or not a username is taken. Let's write a username_check.php page which takes one argument, username, that we'll call like: username_check.php?username=blah It'll look something like: <?php // connect to database somehow... $sql = "SELECT 1 FROM users WHERE username='" . mysql_real_escape_string($_GET['username']) ."' LIMIT 1"; $qry = mysql_query($sql); if (mysql_num_rows($qry) > 0) { echo "TAKEN"; } else { echo "AVAILABLE"; } ?>
  • 19. Adding an event to the text field Back on the client side, we need to add an event for when the user is done typing in their username. This event should be called when the field loses focus, so we use the . focusout() event handler in jQuery. So, our code might be like: <input id='username' type='text' name='username' /> <div id='username_error_box'></div> <script type='text/javascript'> $("#username").focusout(function() { // ajax call will go here }); </script>
  • 20. Handling the AJAX request We know how to make an AJAX request, so let's do it: $.get( 'username_check.php', { username: $("#username").val() }, function(response) { if (response == "TAKEN") { $('#username_error_box').html("This username is taken."); } });
  • 21. Security concerns You might have noticed that an AJAX request just loads a page on your website. That is, anyone can load the same page, and supply their own arguments to make their own request. Even if you could enforce only requests coming from your page, it's easy for malicious users to modify the JavaScript on your page. So, you shouldn't pass sensitive information via AJAX, unless you take proper precautions in encrypting it (and remember, all encryption has to be done server-side; you can't do it via JavaScript). Also, if you're using a login system, make sure to check the session for proper credentials before fulfilling an AJAX request. This is a common attack vector.
  • 22. Summary AJAX is a technique that lets you make your pages seem more responsive and flashier. If you use AJAX to perform sensitive tasks (like deleting data), make sure your server-side pages can't be exploited.