SlideShare a Scribd company logo
1 of 18
Download to read offline
Javascript + Ajax Basics


        Richard Paul
       Kiwiplan NZ Ltd
       30th Jan 2009
Javascript the Language



JavaScript is a scripting language widely used for client-side
web development. ... It is a dynamic, weakly typed, prototype-
based language with first-class functions.

 -- http://en.wikipedia.org/wiki/Javascript
Declaring Variables

var greeting = 'Hello'
var greeting = 'Hello'; // Semicolons are optional
var greeting = quot;Helloquot; // Single & double quotes are
                        // equivalent

var date = new Date()

// Array
var pets = ['cat', 'dog', 'fish']

// Map
var petNames = {cat:'Garfield', dog:'Snoopy', fish:'Nemo'}

// Globally accessible
greeting = 'Hello World'
Functions & Function Scope
Javascript supports function scope, but not block scope.
(Javascript 1.7 introduced 'let' for block scope, not supported in IE)

                                     // This will reassign x to 2, not
// Legal
                                     shadow x (as seen in Java etc).
function funA(num) {                 function funB(num) {
  if (i % 2 == 0) {                      var x = 1
    var x = 10                           if (num < 10) {
  } else {                                 var x = 2
    var x = 20                           }
  }                                  }
  x *= 2
  return x
}
Functions as objects

// Define a function called funA
function funA() {}

// Define a function, assign to variable funB
var funB = function() {}

// Scoped functions
function init() {
  var funC = function() { alert('hi') }
  funC() // OK
}
init()
funC() // => ReferenceError: funC is not defined
Javascript conditionals

                           // Ternery operator
// Javascript truth

                           function doubleOrNothing(x) {
// undefined is false
                             return x % 2 == 0 ? x*=2 : 0
var x
                           }
if (x) {                   doubleOrNothing(2) // => 4
  // Won't reach here      doubleOrNothing(3) // => 0
}

// empty string is false
                           // Default values
var x = ''
                           function X(num) {
if (x) {
                             this.num = num || 0
    // Won't reach here
                           }
}
Optional function arguments

// Adds x, y and an optional z argument
function adder(x, y, z) {
  var value = x + y
  if (z) {
    value += z
  }
  return value
}

adder()             //   =>   undefined + undefined = NaN
adder(2)            //   =>   2 + undefined = NaN
adder(2, 3)         //   =>   5
adder(2, 3, 4)      //   =>   9
adder(2, 3, 4, 5)   //   =>   9, last argument ignored
A better adder
(the arguments keyword)

function adder() {
  var total = 0
  for (var i = 0; i < arguments.length; i++) {
    total += arguments[i]
  }
  return total
}

adder()        // => 0
adder(1)       // => 1
adder(1, 2)    // => 3
Closures
Closures wrap a function, and its environment (variables) to allow it to
be executed later.

function init() {
  var num = 10
  function addNum(myNum) {
    return num + myNum
  }
  return addNum
}

var myAdder = init() // Creates a closure
myAdder(1) // => 11
Defining Objects
function Counter(num) {
  this.num = num || 0
  this.increment = function() {
    this.num++
  }
  this.decrement = function() {
    this.num--
  }
  this.add = function(otherNum) {
    this.num += otherNum
  }
}

While this is simple, it is inefficient as the functions are
defined every time a Counter object is created.
-- https://developer.mozilla.org/.../ClosurePerformance
Exceptions

openMyFile()
try {
   writeMyFile(theData) // This may throw a error
} catch(e) {
   handleError(e) // Handle any errors
} finally {
   closeMyFile() // Always close the resource
}

-- https://developer.mozilla.org/.../try...catch_Statement
Regex
// Literal
var regex = /d+/
// Object
var regex = new Regex('d+')

// Extract hash from a URL
// e.g. http://example.com/#example2
function extractHash(url) {
  var matches = url.match(/#.*/)
  if (matches) {
    return matches[0]
  }
  return '' // Default to empty string if no hash
}

extractHash('http://example.com/#example2')   // =>
#example2
AJAX - Asynchronous Javascript and XML

AJAX is the general term relating to web development
techniques used to update pages dynamically.

Is a misnomer as requests aren't required to be asynchronous
or return XML (any text can be returned).

XmlHttpRequest is the underlying object used to make
requests to a server without requiring a page reload.
AJAX - GET

Retrieve information from a server without a page load.

var request = new XMLHttpRequest()
request.open('GET', 'service/time', true)
request.onreadystatechange = function () {
  if (request.readyState == 4) { // 4 = loaded
    if (request.status == 200) { // 200 = success
      alert(request.responseText) // or responseXML
    }
    else {
      alert('Error loading page: ' + request.status)
    }
  }
}
request.send(null)
AJAX - POST

Send information to a server without a page load.

var url = quot;theUrlquot;
var params = quot;name=Groovy&speaker=Kuganquot;
http.open(quot;POSTquot;, url, true)

http.setRequestHeader(quot;Content-typequot;, quot;application/x-
  www-form-urlencodedquot;)
http.setRequestHeader(quot;Content-lengthquot;, params.length)
http.setRequestHeader(quot;Connectionquot;, quot;closequot;)

http.onreadystatechange = function() {
  // Do something with the response
}
http.send(params)
DOM Manipulation
Document Object Model - The object representation of an XML
page (the structure of a web page).
document.getElementById('myTextbox').value = 'new value'

var content = document.getElementById('myContent')
content.innerHTML = 'new content'

// Get elements for a certain tag, change link name.
var links = document.getElementsByTagName('a')
for (var i = 0; i < links.length; i++) {
  links[i].innerHTML += ' :-)' // Appends a smiley
}

// Add element to page
var div = document.createElement('div')
div.innerHTML = 'This is some content'
document.body.appendChild(div)
Javascript isn't just for web browsers

While Javascript is most widly used for client side scipting in a
browser, it is a fully fledged language and can be used
anywhere.

   Rhino - Open source Javascript engine.
   AppJet - 'Instant web programming', server side javascript
   Jaxer - Server side javascript
Useful Resources

 Javascript Console (live demo)
    http://nzrichardp:9090/AjaxServer/ (session 1)
    http://nzrichardp:9091/AjaxServer/ (session 2)
 Live Demo source (grails app, Kiwiplan CVS)
    Install Java + Grails
    Launch with 'grails run-app'
 Mozilla Javascript Reference
 W3 Spec for XmlHttpRequest
 Learning Advanced Javascript
 Javascript Closures
    Mozilla Developer
    Stack Overflow

More Related Content

What's hot

Object-Oriented Javascript
Object-Oriented JavascriptObject-Oriented Javascript
Object-Oriented Javascriptkvangork
 
Lexical environment in ecma 262 5
Lexical environment in ecma 262 5Lexical environment in ecma 262 5
Lexical environment in ecma 262 5Kim Hunmin
 
Swiftの関数型っぽい部分
Swiftの関数型っぽい部分Swiftの関数型っぽい部分
Swiftの関数型っぽい部分bob_is_strange
 
Advanced javascript
Advanced javascriptAdvanced javascript
Advanced javascriptDoeun KOCH
 
NativeBoost
NativeBoostNativeBoost
NativeBoostESUG
 
Алексей Кутумов, Вектор с нуля
Алексей Кутумов, Вектор с нуляАлексей Кутумов, Вектор с нуля
Алексей Кутумов, Вектор с нуляSergey Platonov
 
Operator overloading2
Operator overloading2Operator overloading2
Operator overloading2zindadili
 
JavaScript - i och utanför webbläsaren (2010-03-03)
JavaScript - i och utanför webbläsaren (2010-03-03)JavaScript - i och utanför webbläsaren (2010-03-03)
JavaScript - i och utanför webbläsaren (2010-03-03)Anders Jönsson
 
jrubykaigi2010-lt-rubeus
jrubykaigi2010-lt-rubeusjrubykaigi2010-lt-rubeus
jrubykaigi2010-lt-rubeusTakeshi AKIMA
 
Swift - Krzysztof Skarupa
Swift -  Krzysztof SkarupaSwift -  Krzysztof Skarupa
Swift - Krzysztof SkarupaSunscrapers
 

What's hot (20)

JavaScript ES6
JavaScript ES6JavaScript ES6
JavaScript ES6
 
Object-Oriented Javascript
Object-Oriented JavascriptObject-Oriented Javascript
Object-Oriented Javascript
 
Bind me if you can
Bind me if you canBind me if you can
Bind me if you can
 
Day 1
Day 1Day 1
Day 1
 
Lexical environment in ecma 262 5
Lexical environment in ecma 262 5Lexical environment in ecma 262 5
Lexical environment in ecma 262 5
 
Swiftの関数型っぽい部分
Swiftの関数型っぽい部分Swiftの関数型っぽい部分
Swiftの関数型っぽい部分
 
Advanced javascript
Advanced javascriptAdvanced javascript
Advanced javascript
 
The State of JavaScript
The State of JavaScriptThe State of JavaScript
The State of JavaScript
 
NativeBoost
NativeBoostNativeBoost
NativeBoost
 
Алексей Кутумов, Вектор с нуля
Алексей Кутумов, Вектор с нуляАлексей Кутумов, Вектор с нуля
Алексей Кутумов, Вектор с нуля
 
ES6 is Nigh
ES6 is NighES6 is Nigh
ES6 is Nigh
 
Operator overloading2
Operator overloading2Operator overloading2
Operator overloading2
 
JavaScript - i och utanför webbläsaren (2010-03-03)
JavaScript - i och utanför webbläsaren (2010-03-03)JavaScript - i och utanför webbläsaren (2010-03-03)
JavaScript - i och utanför webbläsaren (2010-03-03)
 
Academy PRO: ES2015
Academy PRO: ES2015Academy PRO: ES2015
Academy PRO: ES2015
 
Oojs 1.1
Oojs 1.1Oojs 1.1
Oojs 1.1
 
jrubykaigi2010-lt-rubeus
jrubykaigi2010-lt-rubeusjrubykaigi2010-lt-rubeus
jrubykaigi2010-lt-rubeus
 
Groovy
GroovyGroovy
Groovy
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
C++ L08-Classes Part1
C++ L08-Classes Part1C++ L08-Classes Part1
C++ L08-Classes Part1
 
Swift - Krzysztof Skarupa
Swift -  Krzysztof SkarupaSwift -  Krzysztof Skarupa
Swift - Krzysztof Skarupa
 

Viewers also liked

Introduction to Spring's Dependency Injection
Introduction to Spring's Dependency InjectionIntroduction to Spring's Dependency Injection
Introduction to Spring's Dependency InjectionRichard Paul
 
Workshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptWorkshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptVisual Engineering
 
Dependency Injection And Ioc Containers
Dependency Injection And Ioc ContainersDependency Injection And Ioc Containers
Dependency Injection And Ioc ContainersTim Murphy
 
Javascript The Good Parts v2
Javascript The Good Parts v2Javascript The Good Parts v2
Javascript The Good Parts v2Federico Galassi
 
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of ControlJava Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of ControlArjun Thakur
 
Javascript ajax tutorial
Javascript ajax tutorialJavascript ajax tutorial
Javascript ajax tutorialVlad Posea
 
Understanding Javascript AJAX - Imrokraft
Understanding Javascript AJAX - ImrokraftUnderstanding Javascript AJAX - Imrokraft
Understanding Javascript AJAX - Imrokraftimrokraft
 
Dependency injection - the right way
Dependency injection - the right wayDependency injection - the right way
Dependency injection - the right wayThibaud Desodt
 
Clean Code II - Dependency Injection
Clean Code II - Dependency InjectionClean Code II - Dependency Injection
Clean Code II - Dependency InjectionTheo Jungeblut
 
An Introduction to Ajax Programming
An Introduction to Ajax ProgrammingAn Introduction to Ajax Programming
An Introduction to Ajax Programminghchen1
 
Introduction to ajax
Introduction to ajaxIntroduction to ajax
Introduction to ajaxNir Elbaz
 
JSON: The Basics
JSON: The BasicsJSON: The Basics
JSON: The BasicsJeff Fox
 
Ajax ppt - 32 slides
Ajax ppt - 32 slidesAjax ppt - 32 slides
Ajax ppt - 32 slidesSmithss25
 
Introduction to ajax
Introduction to ajaxIntroduction to ajax
Introduction to ajaxRaja V
 

Viewers also liked (17)

Introduction to Spring's Dependency Injection
Introduction to Spring's Dependency InjectionIntroduction to Spring's Dependency Injection
Introduction to Spring's Dependency Injection
 
Workshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptWorkshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScript
 
Dependency Injection And Ioc Containers
Dependency Injection And Ioc ContainersDependency Injection And Ioc Containers
Dependency Injection And Ioc Containers
 
Javascript The Good Parts v2
Javascript The Good Parts v2Javascript The Good Parts v2
Javascript The Good Parts v2
 
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of ControlJava Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
 
Javascript ajax tutorial
Javascript ajax tutorialJavascript ajax tutorial
Javascript ajax tutorial
 
Understanding Javascript AJAX - Imrokraft
Understanding Javascript AJAX - ImrokraftUnderstanding Javascript AJAX - Imrokraft
Understanding Javascript AJAX - Imrokraft
 
JavaScript JQUERY AJAX
JavaScript JQUERY AJAXJavaScript JQUERY AJAX
JavaScript JQUERY AJAX
 
Dependency injection - the right way
Dependency injection - the right wayDependency injection - the right way
Dependency injection - the right way
 
Clean Code II - Dependency Injection
Clean Code II - Dependency InjectionClean Code II - Dependency Injection
Clean Code II - Dependency Injection
 
An Introduction to Ajax Programming
An Introduction to Ajax ProgrammingAn Introduction to Ajax Programming
An Introduction to Ajax Programming
 
IoC and Mapper in C#
IoC and Mapper in C#IoC and Mapper in C#
IoC and Mapper in C#
 
Ajax Ppt
Ajax PptAjax Ppt
Ajax Ppt
 
Introduction to ajax
Introduction to ajaxIntroduction to ajax
Introduction to ajax
 
JSON: The Basics
JSON: The BasicsJSON: The Basics
JSON: The Basics
 
Ajax ppt - 32 slides
Ajax ppt - 32 slidesAjax ppt - 32 slides
Ajax ppt - 32 slides
 
Introduction to ajax
Introduction to ajaxIntroduction to ajax
Introduction to ajax
 

Similar to Javascript & Ajax Basics

ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016Manoj Kumar
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5arajivmordani
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6Dmitry Soshnikov
 
Object-Oriented JavaScript
Object-Oriented JavaScriptObject-Oriented JavaScript
Object-Oriented JavaScriptkvangork
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the mastersAra Pehlivanian
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs偉格 高
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesAnkit Rastogi
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to JavascriptAnjan Banda
 
What's new in jQuery 1.5
What's new in jQuery 1.5What's new in jQuery 1.5
What's new in jQuery 1.5Martin Kleppe
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6Dmitry Soshnikov
 
GPars For Beginners
GPars For BeginnersGPars For Beginners
GPars For BeginnersMatt Passell
 

Similar to Javascript & Ajax Basics (20)

ES6: The Awesome Parts
ES6: The Awesome PartsES6: The Awesome Parts
ES6: The Awesome Parts
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
The Beauty of Java Script
The Beauty of Java ScriptThe Beauty of Java Script
The Beauty of Java Script
 
Wakanday JS201 Best Practices
Wakanday JS201 Best PracticesWakanday JS201 Best Practices
Wakanday JS201 Best Practices
 
JavaScript Core
JavaScript CoreJavaScript Core
JavaScript Core
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6
 
Object-Oriented JavaScript
Object-Oriented JavaScriptObject-Oriented JavaScript
Object-Oriented JavaScript
 
Java script for web developer
Java script for web developerJava script for web developer
Java script for web developer
 
JavaScript Neednt Hurt - JavaBin talk
JavaScript Neednt Hurt - JavaBin talkJavaScript Neednt Hurt - JavaBin talk
JavaScript Neednt Hurt - JavaBin talk
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the masters
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practices
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
 
Unittests für Dummies
Unittests für DummiesUnittests für Dummies
Unittests für Dummies
 
Txjs
TxjsTxjs
Txjs
 
What's new in jQuery 1.5
What's new in jQuery 1.5What's new in jQuery 1.5
What's new in jQuery 1.5
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
 
GPars For Beginners
GPars For BeginnersGPars For Beginners
GPars For Beginners
 

More from Richard Paul

Cucumber on the JVM with Groovy
Cucumber on the JVM with GroovyCucumber on the JVM with Groovy
Cucumber on the JVM with GroovyRichard Paul
 
Acceptance testing with Geb
Acceptance testing with GebAcceptance testing with Geb
Acceptance testing with GebRichard Paul
 
Introduction to Spring MVC
Introduction to Spring MVCIntroduction to Spring MVC
Introduction to Spring MVCRichard Paul
 
Unit Testing Fundamentals
Unit Testing FundamentalsUnit Testing Fundamentals
Unit Testing FundamentalsRichard Paul
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with MockitoRichard Paul
 

More from Richard Paul (8)

Cucumber on the JVM with Groovy
Cucumber on the JVM with GroovyCucumber on the JVM with Groovy
Cucumber on the JVM with Groovy
 
Acceptance testing with Geb
Acceptance testing with GebAcceptance testing with Geb
Acceptance testing with Geb
 
Acceptance tests
Acceptance testsAcceptance tests
Acceptance tests
 
jQuery Behaviours
jQuery BehavioursjQuery Behaviours
jQuery Behaviours
 
Introduction to Spring MVC
Introduction to Spring MVCIntroduction to Spring MVC
Introduction to Spring MVC
 
Unit Testing Fundamentals
Unit Testing FundamentalsUnit Testing Fundamentals
Unit Testing Fundamentals
 
Using Dojo
Using DojoUsing Dojo
Using Dojo
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with Mockito
 

Recently uploaded

Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Bhuvaneswari Subramani
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 

Recently uploaded (20)

Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 

Javascript & Ajax Basics

  • 1. Javascript + Ajax Basics Richard Paul Kiwiplan NZ Ltd 30th Jan 2009
  • 2. Javascript the Language JavaScript is a scripting language widely used for client-side web development. ... It is a dynamic, weakly typed, prototype- based language with first-class functions. -- http://en.wikipedia.org/wiki/Javascript
  • 3. Declaring Variables var greeting = 'Hello' var greeting = 'Hello'; // Semicolons are optional var greeting = quot;Helloquot; // Single & double quotes are // equivalent var date = new Date() // Array var pets = ['cat', 'dog', 'fish'] // Map var petNames = {cat:'Garfield', dog:'Snoopy', fish:'Nemo'} // Globally accessible greeting = 'Hello World'
  • 4. Functions & Function Scope Javascript supports function scope, but not block scope. (Javascript 1.7 introduced 'let' for block scope, not supported in IE) // This will reassign x to 2, not // Legal shadow x (as seen in Java etc). function funA(num) { function funB(num) { if (i % 2 == 0) { var x = 1 var x = 10 if (num < 10) { } else { var x = 2 var x = 20 } } } x *= 2 return x }
  • 5. Functions as objects // Define a function called funA function funA() {} // Define a function, assign to variable funB var funB = function() {} // Scoped functions function init() { var funC = function() { alert('hi') } funC() // OK } init() funC() // => ReferenceError: funC is not defined
  • 6. Javascript conditionals // Ternery operator // Javascript truth function doubleOrNothing(x) { // undefined is false return x % 2 == 0 ? x*=2 : 0 var x } if (x) { doubleOrNothing(2) // => 4 // Won't reach here doubleOrNothing(3) // => 0 } // empty string is false // Default values var x = '' function X(num) { if (x) { this.num = num || 0 // Won't reach here } }
  • 7. Optional function arguments // Adds x, y and an optional z argument function adder(x, y, z) { var value = x + y if (z) { value += z } return value } adder() // => undefined + undefined = NaN adder(2) // => 2 + undefined = NaN adder(2, 3) // => 5 adder(2, 3, 4) // => 9 adder(2, 3, 4, 5) // => 9, last argument ignored
  • 8. A better adder (the arguments keyword) function adder() { var total = 0 for (var i = 0; i < arguments.length; i++) { total += arguments[i] } return total } adder() // => 0 adder(1) // => 1 adder(1, 2) // => 3
  • 9. Closures Closures wrap a function, and its environment (variables) to allow it to be executed later. function init() { var num = 10 function addNum(myNum) { return num + myNum } return addNum } var myAdder = init() // Creates a closure myAdder(1) // => 11
  • 10. Defining Objects function Counter(num) { this.num = num || 0 this.increment = function() { this.num++ } this.decrement = function() { this.num-- } this.add = function(otherNum) { this.num += otherNum } } While this is simple, it is inefficient as the functions are defined every time a Counter object is created. -- https://developer.mozilla.org/.../ClosurePerformance
  • 11. Exceptions openMyFile() try { writeMyFile(theData) // This may throw a error } catch(e) { handleError(e) // Handle any errors } finally { closeMyFile() // Always close the resource } -- https://developer.mozilla.org/.../try...catch_Statement
  • 12. Regex // Literal var regex = /d+/ // Object var regex = new Regex('d+') // Extract hash from a URL // e.g. http://example.com/#example2 function extractHash(url) { var matches = url.match(/#.*/) if (matches) { return matches[0] } return '' // Default to empty string if no hash } extractHash('http://example.com/#example2') // => #example2
  • 13. AJAX - Asynchronous Javascript and XML AJAX is the general term relating to web development techniques used to update pages dynamically. Is a misnomer as requests aren't required to be asynchronous or return XML (any text can be returned). XmlHttpRequest is the underlying object used to make requests to a server without requiring a page reload.
  • 14. AJAX - GET Retrieve information from a server without a page load. var request = new XMLHttpRequest() request.open('GET', 'service/time', true) request.onreadystatechange = function () { if (request.readyState == 4) { // 4 = loaded if (request.status == 200) { // 200 = success alert(request.responseText) // or responseXML } else { alert('Error loading page: ' + request.status) } } } request.send(null)
  • 15. AJAX - POST Send information to a server without a page load. var url = quot;theUrlquot; var params = quot;name=Groovy&speaker=Kuganquot; http.open(quot;POSTquot;, url, true) http.setRequestHeader(quot;Content-typequot;, quot;application/x- www-form-urlencodedquot;) http.setRequestHeader(quot;Content-lengthquot;, params.length) http.setRequestHeader(quot;Connectionquot;, quot;closequot;) http.onreadystatechange = function() { // Do something with the response } http.send(params)
  • 16. DOM Manipulation Document Object Model - The object representation of an XML page (the structure of a web page). document.getElementById('myTextbox').value = 'new value' var content = document.getElementById('myContent') content.innerHTML = 'new content' // Get elements for a certain tag, change link name. var links = document.getElementsByTagName('a') for (var i = 0; i < links.length; i++) { links[i].innerHTML += ' :-)' // Appends a smiley } // Add element to page var div = document.createElement('div') div.innerHTML = 'This is some content' document.body.appendChild(div)
  • 17. Javascript isn't just for web browsers While Javascript is most widly used for client side scipting in a browser, it is a fully fledged language and can be used anywhere. Rhino - Open source Javascript engine. AppJet - 'Instant web programming', server side javascript Jaxer - Server side javascript
  • 18. Useful Resources Javascript Console (live demo) http://nzrichardp:9090/AjaxServer/ (session 1) http://nzrichardp:9091/AjaxServer/ (session 2) Live Demo source (grails app, Kiwiplan CVS) Install Java + Grails Launch with 'grails run-app' Mozilla Javascript Reference W3 Spec for XmlHttpRequest Learning Advanced Javascript Javascript Closures Mozilla Developer Stack Overflow