JQUERY AND AJAX

Slides:



Advertisements
Similar presentations
JQuery MessageBoard. Lets use jQuery and AJAX in combination with a database to update and retrieve information without refreshing the page. Here we will.
Advertisements

JavaScript and AJAX Jonathan Foss University of Warwick
JavaScript Part 6. Calling JavaScript functions on an event JavaScript doesn’t have a main function like other programming languages but we can imitate.
HTML 5 and CSS 3, Illustrated Complete Unit L: Programming Web Pages with JavaScript.
Lesson 12- Unit L Programming Web Pages with JavaScript.
11 Getting Started with ASP.NET Beginning ASP.NET 4.0 in C# 2010 Chapters 5 and 6.
Introduction to JavaScript Module 1 Client Side JS Programming M-GO Sponsored By
AJAX & By – Anupama Sharma. Defining Ajax Ajax isn’t a technology. It’s really several technologies, each flourishing in its own right, coming together.
Chapter 9 Introduction to the Document Object Model (DOM) JavaScript, Third Edition.
JQuery. What is jQuery? jQuery is a fast, small, and feature-rich JavaScript library that simplifies HTML document traversing and manipulation event handling.
1 Using jQuery JavaScript & jQuery the missing manual (Second Edition)
Introduction to scripting
Chapter 6 DOJO TOOLKITS. Objectives Discuss XML DOM Discuss JSON Discuss Ajax Response in XML, HTML, JSON, and Other Data Type.
Definition from Wikipedia.  The Prototype JavaScript Framework  implemented as a single file of JavaScript code  named prototype.js (
JQuery CS 268. What is jQuery? From their web site:
The Document Object Model (DOM) & Asynchronous Javascript And XML (AJAX) : an introduction UFCEKG-20-2 : Data, Schemas and Applications.
DHTML. What is DHTML?  DHTML is the combination of several built-in browser features in fourth generation browsers that enable a web page to be more.
4.1 JavaScript Introduction
JavaScript & jQuery the missing manual Chapter 11
JavaScript, Fifth Edition Chapter 1 Introduction to JavaScript.
XP New Perspectives on XML, 2 nd Edition Tutorial 10 1 WORKING WITH THE DOCUMENT OBJECT MODEL TUTORIAL 10.
CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Environment.
DOM and JavaScript Aryo Pinandito.
Interacting with a Web Page using JavaScript Mat Kelly GTAI Presentation January 10, 2014.
Review IDIA 619 Spring 2013 Bridget M. Blodgett. HTML A basic HTML document looks like this: Sample page Sample page This is a simple sample. HTML user.
CITS1231 Web Technologies JavaScript and Document Object Model.
HTML5 Communication. The Setup Somewhere on the web, a server makes a ”service” available, that we wish to use in a web application The service may offer.
Lesson13. JavaScript JavaScript is an interpreted language, designed to function within a web browser. It can also be used on the server.
JavaScript, Fourth Edition
INTRODUCTION TO JAVASCRIPT AND DOM Internet Engineering Spring 2012.
INTRODUCTION TO HTML5 Using jQuery with HTML5. Introducing jQuery  Although it is not a part of any W3C or WHATWG specification, jQuery performs an important.
Extending HTML CPSC 120 Principles of Computer Science April 9, 2012.
Javascript II DOM & JSON. In an effort to create increasingly interactive experiences on the web, programmers wanted access to the functionality of browsers.
JavaScript - A Web Script Language Fred Durao
Lecture 9: AJAX, Javascript review..  AJAX  Synchronous vs. asynchronous browsing.  Refreshing only “part of a page” from a URL.  Frameworks: Prototype,
JQuery Introduction © Copyright 2014, Fred McClurg All Rights Reserved.
Asynchronous Javascript And XML AJAX : an introduction UFCEUS-20-2 : Web Programming.
1 Javascript DOM Peter Atkinson. 2 Objectives Understand the nature and structure of the DOM Add and remove content from the page Access and change element.
JQuery JavaScript is a powerful language but it is not always easy to work with. jQuery is a JavaScript library that helps with: – HTML document traversal.
INT222 - Internet Fundamentals Shi, Yue (Sunny) Office: T2095 SENECA COLLEGE.
AJAX James Kahng. Congrats Jack Guo for Angular entryentry This week’s coding challenge at end of talk.
Welcome to jQuery jQuery is one of many available libraries that – Provide functions for manipulating the web page With fairly good performance – Help.
Rich Internet Applications 3. Client JavaScript. Document Object Model (DOM) The DOM, is an interface that allows scripts or programs to access and manipulate.
IS2802 Introduction to Multimedia Applications for Business Lecture 07: Introduction to jQuery Rob Gleasure
Unit 13 –JQuery Basics Instructor: Brent Presley.
Event Handling & AJAX IT210 Web Systems. Question How do we enable users to dynamically interact with a website? Answer: Use mouse and keyboard to trigger.
Basic HTML swap with AJAX. Lets get our beloved html for our llama site. Open the index.html page and add a class to our navigation links. Then lets add.
AJAX – Asynchronous JavaScript And XML By Kranthi Kiran Nuthi CIS 764 Kansas State University.
Chapter 6 Murach's JavaScript and jQuery, C6© 2012, Mike Murach & Associates, Inc.Slide 1.
Web Technology (NCS-504) Prepared By Mr. Abhishek Kesharwani Assistant Professor,UCER Naini,Allahabad.
JavaScript Events Java 4 Understanding Events Events add interactivity between the web page and the user You can think of an event as a trigger that.
Introduction to JavaScript MIS 3502, Spring 2016 Jeremy Shafer Department of MIS Fox School of Business Temple University 2/2/2016.
Introduction to JavaScript LIS390W1A Web Technologies and Techniques 24 Oct M. Cameron Jones.
JavaScript Events. Understanding Events Events add interactivity between the web page and the user Events add interactivity between the web page and the.
XML DOM Week 11 Web site:
1 Using jQuery JavaScript & jQuery the missing manual (Second Edition)
Net-centric Computing Document Object Model (DOM).
Web Programming Java Script-Introduction. What is Javascript? JavaScript is a scripting language using for the Web. JavaScript is a programming language.
11 jQuery Web Service Client. 22 Objectives You will be able to Use JSON (JavaScript Object Notation) for communcations between browser and server methods.
Introduction to.
Javascript and Dynamic Web Pages: Client Side Processing
CSE 154 Lecture 11: AJAx.
Not a Language but a series of techniques
HTML.
CSE 154 Lecture 11: AJAx.
DHTML Javascript Internet Technology.
A second look at JavaScript
CSE 154 Lecture 22: AJAX.
DHTML Javascript Internet Technology.
Presentation transcript:

JQUERY AND AJAX

Dynamic HTML (DHTML) Manipulating the web page's structure is essential for creating a highly responsive UI Two main approaches – Manipulate page via plain JS – Manipulate page using JS + library (e.g., jQuery)

Document Object Model (DOM) Fancy name for the web page's structure Web page is basically a tree structure – One node per HTML element – Each node can have attributes

Rewriting using innerHTML attribute function doit() { document.getElementById("stuff").innerHTML = document.getElementById("inpt").value; } Rewriting the contents of a span. NOTE: There is a security problem in the code above. See next slide.

Assigning the.innerText instead function doit() { document.getElementById("stuff").innerText = document.getElementById("inpt").value; } Rewriting the contents of a span. NOTE: There is a browser- compatibility problem in the code above. See next slides.

Welcome to jQuery jQuery is one of many available libraries that – Provide functions for manipulating the web page With fairly good performance – Help to keep your JS code clean Indirectly help to protect security (somewhat) Those are the benefits of using such a library The downside is that you have an extra dependency and need to learn a new library

Getting started with jQuery Download a copy of the jquery JS file and store it on your hard drive Reference the JS file in your HTML Access the jQuery functions via the $ object

Simple example function doit() { $("#stuff").text($("#inpt").val()); } Rewriting the contents of a span. No security problems or cross-browser compatibility problems.

Warning: You need clean HTML If you want jQuery to perform reliably… – Always include tag – Always put this line before your tag This tells the browser to operate in "standards" mode. – Always include "" around your attribute values blah blah

Examples of things you can do with jQuery Read the contents of DOM nodes (tag) Modify the contents of DOM nodes Modify the appearance of DOM nodes Create and attach new DOM nodes Remove DOM nodes Run a function right when the page is ready Add and remove event handlers Retrieve content from a web server Send content to a web server

Example: Modifying DOM appearance.nice {background-color: orange; color: white;} Click me! function toggle() { var els = $("#clickme"); if (!els.hasClass('nice')) els.addClass('nice'); else els.removeClass('nice'); }

Example: Creating new nodes Add stuff function addstuff() { for (var i = 0; i < 10; i++) { $('#mydiv').append(' '+i+' '); }

Example: Removing nodes Add stuff function addstuff() { var kids = $(".kid"); // this creates a "wrapped set" around all nodes with class=kid if (!kids.length) { for (var i = 0; i < 10; i++) $('#mydiv').append(' '+i+' '); } else { kids.remove(); }

Example: Running code on page ready Add stuff function addstuff() { var kids = $(".kid"); if (!kids.length) { for (var i = 0; i < 10; i++) $('#mydiv').append(' '+i+' '); } else { kids.remove(); } $(addstuff);

Example: Manipulating event handlers.nice {background-color: orange; color: white;} Click me! function toggle() { var els = $("#clickme"); if (!els.hasClass('nice')) els.addClass('nice'); else els.removeClass('nice'); } $("#clickme").click(toggle);

Coolest part of jQuery: Simplifies AJAX Old school (synchronous full page refresh) – Click a link, wait for page to load, submit a form, wait for page to load, click a link, wait for page… New school (asynchronous partial refresh) – Click a link, part of page quickly changes, fill out a form, page immediately responds while server gets data, etc. More complicated, but much more usable

How asynchronous partial refresh works Web page UI Your AJAX code Web server Type or click Request action Send message to server Server sends back some data Update UI User sees the action is done User sees the action started

How it works in detail User types or clicks: need an event handler UI requests some action: need a JS function UI shows it started: need a DIV to update – Should be clear, so user sees it started Send message to server: need AJAX code Server eventually replies: need callback JS UI shows it finished: need a DIV to update – Should show the result to the user

A very simple web page and XML Click me function startAjax() { $("#clickme").text("Calling server"); $.ajax({url:"somefile.xml", success:callbackFunction, error:errorFunction} ); } function callbackFunction(data,info) { $("#clickme").text("result:"+data); } function errorFunction(data,info) { $("#clickme").text("error occurred:"+info); } somefile.xml ok

Key things to note There's an element with an onclick handler And the onclick handler calls $.ajax({url:myurl, success:jsFn, error:jsFn}); And each JS function looks like function myjsfunction(data, info) {…} Inside the JS function, update the UI using $("#myelementid").text("whatever");

So where can you load data from? In general, you can only load data from the same web site that your main html came from – This is called the "same origin policy" When you're working from the file system… – Firefox 13 & Internet Explorer 9 let you load files – Chrome 22 does not let you load other files – Other versions & other browsers may vary!

So what is this XML you speak of? Basically a tree-like structure, similar to the document object model you get from HTML – In fact, some of the same W3C official standards apply to both XML-based and HTML-based DOMs – There is an XML-based HTML standard called XHTML, which is basically well-formed HTML. First you have the XML declaration And then you have the tree of tags.

Another example of XML Books I Love Gosh, I sure love books The $100 Startup The Art of Non-Conformity

Once you have XML, what can you do? $(data) gives you a wrapped set You can select nodes within the set with –.find("tagname") –.find("tagname:first") to get just the first –.find("#myid") to get an XML node by id –.find("tag1 tag2") to get tags inside tags And then get the text inside nodes using –.text()

For example, to grab and concatenate all the title elements in the document… Click me function startAjax() { $("#clickme").text("Calling server"); $.ajax({url:"somefile.xml", success:callbackFunction, error:errorFunction} } function callbackFunction(data,info) { var titles = $(data).find("title"); if (titles && titles.length) $("#clickme").text("result:"+titles.text()); else errorFunction(data, "No titles"); } function errorFunction(data,info) { $("#clickme").text("error occurred:"+info); }

XML is kind of wordy, though Books I Love Gosh, I sure love books The $100 Startup The Art of Non-Conformity

What if we could just use JS notation? {"version":"0.92", "channels":[ { "title":"Books I Love", "link":" "description":"Gosh, I sure love books", "items":[ { "title":"The $100 Startup", "link":" }, { "title":"The Art of Non-Conformity", "link":" } }] }

Well, that is what we call JavaScript Object Notation (JSON) Essentially identical to declaring JS arrays – Either associative arrays or sequential arrays – Except that you have to be sure to quote the property names {"name":"Jimmy", "age":54, "son":{"name":"Sam", "age":20} }

A very simple web page and JSON Click me function startAjax() { $("#clickme").text("Calling server"); $.ajax({url:"somefile.json", success:callbackFunction,error:errorFunction, dataType: 'json'} /* request json -> JS object */ ); } function callbackFunction(data,info) { $("#clickme").text("result:"+data); /*data is JS object */ } function errorFunction(data,info) { $("#clickme").text("error occurred:"+info); } somefile.json {"name":"Jimmy", "age":54, "son":{"name":"Sam", "age":20} }

What if the server sends garbage? Be sure to provide $.ajax() an error handler. Be sure to check for null before using data. You probably should even use try/catch function callbackFunction(data,info) { try { if (!data || !data.name) errorFunction(data, "no data"); else $("#clickme").text("result:"+data.name); } catch (someException) { errorFunction(data, someException+""); }

How to send data to the server (or use GET for idempotent requests) $.ajax({type:'POST', url:"blahblahblah.php", success:callbackFunction,error:errorFunction, dataType: 'json', data:{name1:value1,name2:value2} });

Side comments about JSON… There are also libraries for reading and writing objects to/from JavaScript in other languages – For example, for writing Java Objects to JSON In JavaScript, you also can convert strings to/from objects even without hitting a server – var obj = JSON.parse(str) – var str = JSON.stringify(obj)

Walk through another site skeleton Browse at Download at Good points: Demonstrates AJAX data retrieval Bad points: No input validation or data-editing; same page title on every page