SlideShare uma empresa Scribd logo
1 de 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;
…

Mais conteúdo relacionado

Mais procurados

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
 

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

Semelhante a 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
 

Mais de 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
 

Mais de 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
 

Último

SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
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
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
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
 
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
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
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
 
"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
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
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
 
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
 

Último (20)

SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
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
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
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
 
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
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 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
 
"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
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
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
 
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!
 

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; …

Notas do Editor

  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>