SlideShare a Scribd company logo
1 of 25
AJAX

         Jussi Pohjolainen
Tampere University of Applied Sciences
AJAX
• Asynchronous JavaScript and XML
• AJAX is about updating parts of web page
  without reloading the whole page
• Google Maps, Gmail, Youtube…
How AJAX works? (W3schools)
Support
– Firefox 1.0 and newer
– Opera 8 and newer including Opera mini
– Safari 1.2 and newer
– Internet Explorer 7 and newer
Techniques
• XMLHttpRequest object
• JavaScript and DOM
• CSS and some dataformat (XML, JSON, HTML,
  text..)
XMLHttpRequest
• Modern browsers support built-in
  XMLHttpRequest object
• All about sending and receiving data from
  server.
• Instantiate in normal fashion:
  – var xmlobj = new XMLHttpRequest();
Send Request to Server
var xmlobj = new XMLHttpRequest();

xmlobj.open(“GET”,         // POST or GET?
       “somefile.txt”, // URL
       true);       // async or not?

xmlobj.send();        // Send it
Using POST
var xmlobj = new XMLHttpRequest();

xmlobj.open(“POST”,         // POST or GET?
       “somescript.php”, // URL
       true);      // async or not?

// Specify the data you want to send via POST
xmlhttp.setRequestHeader("Content-type","application/x-www-form-
urlencoded");

// Send data
xmlobj.send(“name=Kalle”);
Asynchronous?
• When setting the async parameter to true, the
  server side script is run in background.
• Javascript does not have to wait for the server
  response.. You can
  – Execute other scripts while waiting server
    response
  – Deal with the response when ready
• Specify a function that is called when
  response is ready!
Example
State of the Request
•   0: Not initialized
•   1: Server connection established
•   2: Request received
•   3: Processing request
•   4: Request Finished and Response Ready
Status of the Request
• Also HTTP Status is received
  – 200: “Ok”
  – 404: “Page not found”
  –…
• if(xmlobj.status == 200 &&
  xmlobj.readyState == 4) { .. }
Server Response
• XMLHttpRequest has two attributes for the
  response
  – DOMString responseText
  – Document responseXML
Parsing XML
Pattern for several callbacks
• Implement method like:
  – loadSomeXML(“url-here”, functionNameHere);
DATA FORMATS
HTML
•   Very simple way to do AJAX
•   Server has fragments of HTML
•   No parsing or converting
•   Easy to update UI: use can use innerHTML or
    standard DOM
XML
• Static XML Data on server or generated XML
• XML must be parsed: use DOM scripting
• Example of PHP -> XML -> AJAX
Example
function showResponse(req) {
  // if the request is ready
  if (req.readyState == 4 && req.status ==
  200) {
         var data = req.responseXML;
         // here we have to process XML data
   }
  }
}
JSON
•   JavaScript Object Notation
•   Storing and exchanging text
•   Smaller than XML, faster and easier to parse!
•   Language Independent
Example
{
    "employees": [
      {
         "firstName": "John",
         "lastName" : "Doe"
      },
      {
         "firstName": "Anna",
         "lastName" : "Smith"
      },
      {
         "firstName": "Peter",
         "lastName": "Jones"
      }
    ]
}
Parsing JSON in JS
• You can convert JSON text to Object using eval
  – function:
  – var myObject = eval(„(„ + JSONText + „)‟);
• You should NOT use eval for security issues!
  Eval executes also any js program…
• Use JSON Parses instead! It recognizes only
  JSON text
Example (wikipedia)
var my_JSON_object = {};
var http_request = new XMLHttpRequest();
http_request.open("GET", url, true);
http_request.onreadystatechange = function () {
  var done = 4, ok = 200;
  if (http_request.readyState == done && http_request.status == ok) {
      my_JSON_object = JSON.parse(http_request.responseText);
  }
};
http_request.send(null);
Example
…
"location" : { "city" : "San Francisco",
    "country" : "US",
    "country_iso3166" : "US",
    "country_name" : "USA",
    "l" : "/q/zmw:94101.1.99999",
    "lat" : "37.77500916",
    "lon" : "-122.41825867",
    "magic" : "1",
    "nearby_weather_stations" : { "airport" : { "station" : [ { "city" : "San Francisco",
…

var myObject = JSON.parse(httpReq.responseText);
var city = myObject.location.city;
…

More Related Content

What's hot

Using Webservice in iOS
Using Webservice  in iOS Using Webservice  in iOS
Using Webservice in iOS Mahboob Nur
 
Javascript in C# for Lightweight Applications
Javascript in C# for Lightweight ApplicationsJavascript in C# for Lightweight Applications
Javascript in C# for Lightweight ApplicationsVelanSalis
 
Introduction about-ajax-framework
Introduction about-ajax-frameworkIntroduction about-ajax-framework
Introduction about-ajax-frameworkSakthi Bro
 
mobile in the cloud with diamonds. improved.
mobile in the cloud with diamonds. improved.mobile in the cloud with diamonds. improved.
mobile in the cloud with diamonds. improved.Oleg Shanyuk
 
Data normalization weaknesses
Data normalization weaknessesData normalization weaknesses
Data normalization weaknessesIvan Novikov
 
Synapseindia dot net development web applications with ajax
Synapseindia dot net development  web applications with ajaxSynapseindia dot net development  web applications with ajax
Synapseindia dot net development web applications with ajaxSynapseindiappsdevelopment
 
Updates to the java api for json processing for java ee 8
Updates to the java api for json processing for java ee 8Updates to the java api for json processing for java ee 8
Updates to the java api for json processing for java ee 8Alex Soto
 
Difference between xml and json
Difference between xml and jsonDifference between xml and json
Difference between xml and jsonUmar Ali
 
Distributed computing in browsers as client side attack
Distributed computing in browsers as client side attackDistributed computing in browsers as client side attack
Distributed computing in browsers as client side attackIvan Novikov
 
Web Services with Objective-C
Web Services with Objective-CWeb Services with Objective-C
Web Services with Objective-CJuio Barros
 
Mastering the MongoDB Shell
Mastering the MongoDB ShellMastering the MongoDB Shell
Mastering the MongoDB ShellMongoDB
 

What's hot (19)

Lec 7
Lec 7Lec 7
Lec 7
 
Json tutorial, a beguiner guide
Json tutorial, a beguiner guideJson tutorial, a beguiner guide
Json tutorial, a beguiner guide
 
Using Webservice in iOS
Using Webservice  in iOS Using Webservice  in iOS
Using Webservice in iOS
 
Javascript in C# for Lightweight Applications
Javascript in C# for Lightweight ApplicationsJavascript in C# for Lightweight Applications
Javascript in C# for Lightweight Applications
 
Introduction about-ajax-framework
Introduction about-ajax-frameworkIntroduction about-ajax-framework
Introduction about-ajax-framework
 
mobile in the cloud with diamonds. improved.
mobile in the cloud with diamonds. improved.mobile in the cloud with diamonds. improved.
mobile in the cloud with diamonds. improved.
 
Data normalization weaknesses
Data normalization weaknessesData normalization weaknesses
Data normalization weaknesses
 
Synapseindia dot net development web applications with ajax
Synapseindia dot net development  web applications with ajaxSynapseindia dot net development  web applications with ajax
Synapseindia dot net development web applications with ajax
 
phptut4
phptut4phptut4
phptut4
 
Updates to the java api for json processing for java ee 8
Updates to the java api for json processing for java ee 8Updates to the java api for json processing for java ee 8
Updates to the java api for json processing for java ee 8
 
Difference between xml and json
Difference between xml and jsonDifference between xml and json
Difference between xml and json
 
Distributed computing in browsers as client side attack
Distributed computing in browsers as client side attackDistributed computing in browsers as client side attack
Distributed computing in browsers as client side attack
 
Web Services with Objective-C
Web Services with Objective-CWeb Services with Objective-C
Web Services with Objective-C
 
Xml parsing
Xml parsingXml parsing
Xml parsing
 
Mastering the MongoDB Shell
Mastering the MongoDB ShellMastering the MongoDB Shell
Mastering the MongoDB Shell
 
MongoDB
MongoDBMongoDB
MongoDB
 
JSON
JSONJSON
JSON
 
Java XML Parsing
Java XML ParsingJava XML Parsing
Java XML Parsing
 
Introduction to JSON
Introduction to JSONIntroduction to JSON
Introduction to JSON
 

Similar to AJAX (20)

Web technologies-course 10.pptx
Web technologies-course 10.pptxWeb technologies-course 10.pptx
Web technologies-course 10.pptx
 
Introduction to AJAX
Introduction to AJAXIntroduction to AJAX
Introduction to AJAX
 
AJAX.pptx
AJAX.pptxAJAX.pptx
AJAX.pptx
 
AJAX.ppt
AJAX.pptAJAX.ppt
AJAX.ppt
 
JSON
JSONJSON
JSON
 
Json
JsonJson
Json
 
Ajax Tuturial
Ajax TuturialAjax Tuturial
Ajax Tuturial
 
Ajax
AjaxAjax
Ajax
 
Ajax
AjaxAjax
Ajax
 
Web Development Course - AJAX & JSON by RSOLUTIONS
Web Development Course - AJAX & JSON by RSOLUTIONSWeb Development Course - AJAX & JSON by RSOLUTIONS
Web Development Course - AJAX & JSON by RSOLUTIONS
 
Ajaxtechnicalworkshopshortversion 1224845432835700-8
Ajaxtechnicalworkshopshortversion 1224845432835700-8Ajaxtechnicalworkshopshortversion 1224845432835700-8
Ajaxtechnicalworkshopshortversion 1224845432835700-8
 
Unit-5.pptx
Unit-5.pptxUnit-5.pptx
Unit-5.pptx
 
PHP - Introduction to PHP AJAX
PHP -  Introduction to PHP AJAXPHP -  Introduction to PHP AJAX
PHP - Introduction to PHP AJAX
 
Learn AJAX at ASIT
Learn AJAX at ASITLearn AJAX at ASIT
Learn AJAX at ASIT
 
Ajax Technology
Ajax TechnologyAjax Technology
Ajax Technology
 
Xml http request
Xml http requestXml http request
Xml http request
 
Ajax
AjaxAjax
Ajax
 
AJAX.pptx
AJAX.pptxAJAX.pptx
AJAX.pptx
 
Json
JsonJson
Json
 
Ajax
AjaxAjax
Ajax
 

More from Jussi Pohjolainen

libGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and PreferenceslibGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and PreferencesJussi Pohjolainen
 
libGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame AnimationlibGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame AnimationJussi Pohjolainen
 
Intro to Building Android Games using libGDX
Intro to Building Android Games using libGDXIntro to Building Android Games using libGDX
Intro to Building Android Games using libGDXJussi Pohjolainen
 
Advanced JavaScript Development
Advanced JavaScript DevelopmentAdvanced JavaScript Development
Advanced JavaScript DevelopmentJussi Pohjolainen
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame AnimationJussi Pohjolainen
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame AnimationJussi Pohjolainen
 
Implementing a Simple Game using libGDX
Implementing a Simple Game using libGDXImplementing a Simple Game using libGDX
Implementing a Simple Game using libGDXJussi Pohjolainen
 
Building Android games using LibGDX
Building Android games using LibGDXBuilding Android games using LibGDX
Building Android games using LibGDXJussi Pohjolainen
 
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and GesturesCreating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and GesturesJussi Pohjolainen
 
Creating Games for Asha - platform
Creating Games for Asha - platformCreating Games for Asha - platform
Creating Games for Asha - platformJussi Pohjolainen
 

More from Jussi Pohjolainen (20)

Moved to Speakerdeck
Moved to SpeakerdeckMoved to Speakerdeck
Moved to Speakerdeck
 
Java Web Services
Java Web ServicesJava Web Services
Java Web Services
 
Box2D and libGDX
Box2D and libGDXBox2D and libGDX
Box2D and libGDX
 
libGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and PreferenceslibGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and Preferences
 
libGDX: Tiled Maps
libGDX: Tiled MapslibGDX: Tiled Maps
libGDX: Tiled Maps
 
libGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame AnimationlibGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame Animation
 
Intro to Building Android Games using libGDX
Intro to Building Android Games using libGDXIntro to Building Android Games using libGDX
Intro to Building Android Games using libGDX
 
Advanced JavaScript Development
Advanced JavaScript DevelopmentAdvanced JavaScript Development
Advanced JavaScript Development
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 
libGDX: Scene2D
libGDX: Scene2DlibGDX: Scene2D
libGDX: Scene2D
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame Animation
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame Animation
 
libGDX: User Input
libGDX: User InputlibGDX: User Input
libGDX: User Input
 
Implementing a Simple Game using libGDX
Implementing a Simple Game using libGDXImplementing a Simple Game using libGDX
Implementing a Simple Game using libGDX
 
Building Android games using LibGDX
Building Android games using LibGDXBuilding Android games using LibGDX
Building Android games using LibGDX
 
Android Threading
Android ThreadingAndroid Threading
Android Threading
 
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and GesturesCreating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
 
Creating Games for Asha - platform
Creating Games for Asha - platformCreating Games for Asha - platform
Creating Games for Asha - platform
 
Intro to Asha UI
Intro to Asha UIIntro to Asha UI
Intro to Asha UI
 

Recently uploaded

Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 

Recently uploaded (20)

Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 

AJAX

  • 1. AJAX Jussi Pohjolainen Tampere University of Applied Sciences
  • 2. AJAX • Asynchronous JavaScript and XML • AJAX is about updating parts of web page without reloading the whole page • Google Maps, Gmail, Youtube…
  • 3. How AJAX works? (W3schools)
  • 4. Support – Firefox 1.0 and newer – Opera 8 and newer including Opera mini – Safari 1.2 and newer – Internet Explorer 7 and newer
  • 5. Techniques • XMLHttpRequest object • JavaScript and DOM • CSS and some dataformat (XML, JSON, HTML, text..)
  • 6. XMLHttpRequest • Modern browsers support built-in XMLHttpRequest object • All about sending and receiving data from server. • Instantiate in normal fashion: – var xmlobj = new XMLHttpRequest();
  • 7. Send Request to Server var xmlobj = new XMLHttpRequest(); xmlobj.open(“GET”, // POST or GET? “somefile.txt”, // URL true); // async or not? xmlobj.send(); // Send it
  • 8. Using POST var xmlobj = new XMLHttpRequest(); xmlobj.open(“POST”, // POST or GET? “somescript.php”, // URL true); // async or not? // Specify the data you want to send via POST xmlhttp.setRequestHeader("Content-type","application/x-www-form- urlencoded"); // Send data xmlobj.send(“name=Kalle”);
  • 9. Asynchronous? • When setting the async parameter to true, the server side script is run in background. • Javascript does not have to wait for the server response.. You can – Execute other scripts while waiting server response – Deal with the response when ready • Specify a function that is called when response is ready!
  • 11. State of the Request • 0: Not initialized • 1: Server connection established • 2: Request received • 3: Processing request • 4: Request Finished and Response Ready
  • 12.
  • 13. Status of the Request • Also HTTP Status is received – 200: “Ok” – 404: “Page not found” –… • if(xmlobj.status == 200 && xmlobj.readyState == 4) { .. }
  • 14. Server Response • XMLHttpRequest has two attributes for the response – DOMString responseText – Document responseXML
  • 16. Pattern for several callbacks • Implement method like: – loadSomeXML(“url-here”, functionNameHere);
  • 18. HTML • Very simple way to do AJAX • Server has fragments of HTML • No parsing or converting • Easy to update UI: use can use innerHTML or standard DOM
  • 19. XML • Static XML Data on server or generated XML • XML must be parsed: use DOM scripting • Example of PHP -> XML -> AJAX
  • 20. Example function showResponse(req) { // if the request is ready if (req.readyState == 4 && req.status == 200) { var data = req.responseXML; // here we have to process XML data } } }
  • 21. JSON • JavaScript Object Notation • Storing and exchanging text • Smaller than XML, faster and easier to parse! • Language Independent
  • 22. Example { "employees": [ { "firstName": "John", "lastName" : "Doe" }, { "firstName": "Anna", "lastName" : "Smith" }, { "firstName": "Peter", "lastName": "Jones" } ] }
  • 23. Parsing JSON in JS • You can convert JSON text to Object using eval – function: – var myObject = eval(„(„ + JSONText + „)‟); • You should NOT use eval for security issues! Eval executes also any js program… • Use JSON Parses instead! It recognizes only JSON text
  • 24. Example (wikipedia) var my_JSON_object = {}; var http_request = new XMLHttpRequest(); http_request.open("GET", url, true); http_request.onreadystatechange = function () { var done = 4, ok = 200; if (http_request.readyState == done && http_request.status == ok) { my_JSON_object = JSON.parse(http_request.responseText); } }; http_request.send(null);
  • 25. Example … "location" : { "city" : "San Francisco", "country" : "US", "country_iso3166" : "US", "country_name" : "USA", "l" : "/q/zmw:94101.1.99999", "lat" : "37.77500916", "lon" : "-122.41825867", "magic" : "1", "nearby_weather_stations" : { "airport" : { "station" : [ { "city" : "San Francisco", … var myObject = JSON.parse(httpReq.responseText); var city = myObject.location.city; …

Editor's Notes

  1. Sniff capabilities:if (window.XMLHttpRequest) {varoReq = new XMLHttpRequest();}
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head> <title>Ajax Example</title> <meta http-equiv="content-type" content="application/xhtml+xml; charset=utf-8"/> <script type="text/javascript">varxmlobj; function retrieveFromServer() {xmlobj = new XMLHttpRequest();xmlobj.onreadystatechange = changesHappening;xmlobj.open("GET", // POST or GET? "somefile.txt", // URL true); // async or not?xmlobj.send(); // Send it } function changesHappening() {varmyarray = new Array("UNSENT", "OPENED", "HEADERS RECEIVED", "LOADING", "DONE"); alert( myarray[ xmlobj.readyState ] ); } </script> </head><body><p> <button type="button" onclick="retrieveFromServer()">Change Content</button></p><p id="here"></p></body></html>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head> <title>Ajax Example</title> <meta http-equiv="content-type" content="application/xhtml+xml; charset=utf-8"/> <script type="text/javascript">varxmlobj; function retrieveFromServer() {xmlobj = new XMLHttpRequest();xmlobj.onreadystatechange = changesHappening;xmlobj.open("GET", // POST or GET? "somefile.txt", // URL true); // async or not?xmlobj.send(); // Send it } function changesHappening() { if(xmlobj.readyState == 4) {document.getElementById("text").innerHTML = xmlobj.responseText; } } </script> </head><body><p> <button type="button" onclick="retrieveFromServer()">Change Content</button></p><p id="text"></p></body></html>
  4. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head> <title>Ajax Example</title> <meta http-equiv="content-type" content="application/xhtml+xml; charset=utf-8"/> <script type="text/javascript">varxmlobj;varfinnkinoURL = "http://www.finnkino.fi/xml/Schedule/?area=1021&dt=" + getDate(); function getDate() {varcurrentTime = new Date()var day = currentTime.getDate();var month = currentTime.getMonth();var year = currentTime.getYear(); return day + "." + month + "." + year; } function retrieveFromServer() {xmlobj = new XMLHttpRequest();xmlobj.onreadystatechange = changesHappening;xmlobj.open("GET", // POST or GET? finnkinoURL, // URL true); // async or not?xmlobj.send(); // Send it } function changesHappening() { if(xmlobj.readyState == 4) {varxmlDoc = xmlobj.responseXML;var titles = xmlDoc.getElementsByTagName("Title");var result = ""; for (i=0; i<titles.length; i++) { result = result + titles[i].childNodes[0].nodeValue + "<br />"; }document.getElementById("text").innerHTML = result; } } </script> </head><body><p> <button type="button" onclick="retrieveFromServer()">Change Content</button></p><p id="text"></p></body></html>
  5. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head> <title>Ajax Example</title> <meta http-equiv="content-type" content="application/xhtml+xml; charset=utf-8"/> <script type="text/javascript">varxmlobj; function getDate() {varcurrentTime = new Date()var day = currentTime.getDate();var month = currentTime.getMonth();var year = currentTime.getYear(); return day + "." + month + "." + year; } function retrieveFromServer(url, callBackFunction) {xmlobj = new XMLHttpRequest();xmlobj.onreadystatechange = callBackFunction;xmlobj.open("GET", // POST or GET? url, // URL true); // async or not?xmlobj.send(); // Send it } function parseMovieTitles() { if(xmlobj.readyState == 4 && xmlobj.status == 200) {varxmlDoc = xmlobj.responseXML;var titles = xmlDoc.getElementsByTagName("Title");var result = ""; for (i=0; i<titles.length; i++) { result = result + titles[i].childNodes[0].nodeValue + "<br />"; }document.getElementById("titles").innerHTML = result; } } function parseMovieImages() { if(xmlobj.readyState == 4 && xmlobj.status == 200) {varxmlDoc = xmlobj.responseXML;varimageURLs = xmlDoc.getElementsByTagName("EventSmallImagePortrait");var result = ""; for (i=0; i<imageURLs.length; i++) { result = result + "<imgsrc=\\"" + imageURLs[i].childNodes[0].nodeValue + "\\" alt=\\"\\" /><br />"; }document.getElementById("images").innerHTML = result; } } function showMovieTitles() {varfinnkinoURL = "http://www.finnkino.fi/xml/Schedule/?area=1021&dt=" + getDate();retrieveFromServer(finnkinoURL, parseMovieTitles); } function showMovieImages() {varfinnkinoURL = "http://www.finnkino.fi/xml/Schedule/?area=1021&dt=" + getDate();retrieveFromServer(finnkinoURL, parseMovieImages); } </script> </head><body><p> <button type="button" onclick="showMovieTitles()">Show Movie Titles</button> <button type="button" onclick="showMovieImages()">Show Movie Images</button></p><p id="titles"></p><div id="images"></div></body></html>