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

SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 

Recently uploaded (20)

SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 

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>