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 (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 (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

Generasi Terampil Digital Skill-2023.pptx
Generasi Terampil Digital Skill-2023.pptxGenerasi Terampil Digital Skill-2023.pptx
Generasi Terampil Digital Skill-2023.pptxFajar Baskoro
 
Cara Membuat Kursus Online Wordpress-tutorstarter
Cara Membuat Kursus Online Wordpress-tutorstarterCara Membuat Kursus Online Wordpress-tutorstarter
Cara Membuat Kursus Online Wordpress-tutorstarterFajar Baskoro
 
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 RamadhanFajar Baskoro
 
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 KUSFajar Baskoro
 
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.pptxFajar Baskoro
 
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.pdfFajar Baskoro
 
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.pptxFajar Baskoro
 
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.pptxFajar Baskoro
 
Pemrograman Mobile - JetPack Compose1.pptx
Pemrograman Mobile - JetPack Compose1.pptxPemrograman Mobile - JetPack Compose1.pptx
Pemrograman Mobile - JetPack Compose1.pptxFajar Baskoro
 
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 KaltimFajar Baskoro
 
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 sekolahFajar Baskoro
 
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 remajaFajar Baskoro
 
Membangun aplikasi mobile dengan Appsheet
Membangun aplikasi mobile dengan AppsheetMembangun aplikasi mobile dengan Appsheet
Membangun aplikasi mobile dengan AppsheetFajar Baskoro
 
Transition education to employment.pdf
Transition education to employment.pdfTransition education to employment.pdf
Transition education to employment.pdfFajar 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

GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noidabntitsolutionsrishis
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 

Recently uploaded (20)

GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 

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.