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 Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 

Recently uploaded (20)

Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 

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