chapter 12 jquery, ajax, json -...

65
Web programming Networking Laboratory 1/65 Sungkyunkwan University Copyright 2000-2012 Networking Laboratory Copyright 2000-2016 Networking Laboratory Chapter 12 JQUERY, AJAX, JSON Prepared by Vi Van Vo and H. Choo

Upload: others

Post on 05-Sep-2019

8 views

Category:

Documents


0 download

TRANSCRIPT

Web programming Networking Laboratory 1/65

Sungkyunkwan University

Copyright 2000-2012 Networking LaboratoryCopyright 2000-2016 Networking Laboratory

Chapter 12

JQUERY, AJAX, JSON

Prepared by Vi Van Vo and H. Choo

Web programming Networking Laboratory 2/65

jQuery

jQuery is a JavaScript Library.

It greatly simplifies JavaScript programming.

It is easy to learn.

JavaScript jQuery

document.getElementsByClassName(“Hello”); $(“Hello”);

Web programming Networking Laboratory 3/65

jQuery – How to use

Local Installation: Download jQuery library on your local machine and

include it in your HTML code

CDN Based Version: Include jQuery library into your HTML code

directly from Content Delivery Network (CDN)

Web programming Networking Laboratory 4/65

jQuery – How to useLocal Installation

Download the jQuery library from https://jquery.com/download/

Put downloaded jquery-3.3.1.min.js file in a directory of your

website, and you reference it with the HTML <script> tag

<head>

<script src=“jquery-3.3.1.min.js"></script>

</head>

Web programming Networking Laboratory 5/65

jQuery – How to useLocal Installation - Example

“Hello World”

<html>

<head>

<title>The jQuery Example</title>

<script type = "text/javascript" src =

"jquery-3.3.1.min.js">

</script>

<script type = "text/javascript">

$(document).ready(function() {

document.write("Hello World!");

});

</script>

</head>

<body>

<h1>Hello</h1>

</body>

</html>

Web programming Networking Laboratory 6/65

jQuery – How to useCDN Based Version

Include jQuery library into your HTML code directly from a Content

Delivery Network, such as Google, Microsoft

<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquer

y/3.3.1/jquery.min.js"></script>

</head>

Web programming Networking Laboratory 7/65

jQuery – How to useCDN Based Version - Example

Web_jQuery.html

<!DOCTYPE html>

<html>

<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3

.1/jquery.min.js"></script>

<script>

$(document).ready(function(){

$("p").click(function(){

$("p").hide();

});

});

</script>

</head>

<body>

<p>Click me to disappear.</p>

</body>

</html>

Web programming Networking Laboratory 8/65

jQuery – How to use

CDN Based Version - Example

Result

Web programming Networking Laboratory 9/65

jQuery syntax

Tailor-made for selecting HTML elements and performing some

actions on the element(s).

$(selector).action();

Define/Access jQuery

To "query (or find)" HTML elements

Be performed on the element(s)

Web programming Networking Laboratory 10/65

jQuery syntax

Example:

$(this).hide() - hides the current element.

$("p").hide() - hides all <p> elements.

$(".test").hide() - hides all elements with class="test".

$("#test").hide() - hides the element with id="test".

Web programming Networking Laboratory 11/65

jQuery Selector

Allow to select and manipulate HTML element(s).

Used to select HTML elements based on their name, id, classes,

types, attributes, values of attributes and much more.

Start with the dollar sign and parentheses: $().

Syntax Description

$("p") Selects elements based on the element name.

$("#id") Selects the element with the ID attribute

$(".class") Selects elements with a specific class.

$("*") Selects all elements

$(this) Selects the current HTML element

$(":button") Selects all <button> elements and <input> elements of

type="button"

Web programming Networking Laboratory 12/65

jQuery Selector - Exercise (1/3)

jQuery_selector.html

<!DOCTYPE html>

<html>

<head>

<script

src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jqu

ery.min.js"></script>

<script src = "jQuery_selector_function"></script>

</head>

<body>

<h1>This is a heading</h2>

<h2 class="test">This is another heading</h2>

<p class="test">This is a paragraph.</p>

<p>This is a second paragraph.</p>

<p>This is another paragraph.</p>

<a href="https://skku.edu/">SKKU Homepage</a>

<a href="https://http://ice.skku.edu/eng_ice/">CICE</a>

Web programming Networking Laboratory 13/65

jQuery Selector - Exercise (2/3) jQuery_selector.html (Cont)

jQuery_selector_function.js

Use the correct selector to hide

All <p> elements.

The element with id="test".

All elements with class="test".

All elements in the document.

All elements with an href attribute. (hint: $("[href]"))

$(document).ready(function(){

$("selector").hide();

});

<button>This is a button</button>

<p id="test">This is a paragraph with id="test".</p>

</body>

</html>

Web programming Networking Laboratory 14/65

jQuery Selector - Exercise (3/3)

All <p> elements.

$("p").hide();

The element with id="test".

$("#test").hide();

All elements with class="test".

$(".test").hide();

All elements in the document.

$("*").hide();

All elements with an href attribute. ($("[href]"))

$("[href]").hide();

Web programming Networking Laboratory 15/65

jQuery Events (1/3)

Tailor-made to respond to events in an HTML page.

What are events?

All the different visitor's actions that a web page can respond to.

An event represents the precise moment when something happens.

Examples:

Moving a mouse over an element

Selecting a button

Clicking on an element

Web programming Networking Laboratory 16/65

jQuery Events (2/3)

Here are some common DOM (Document Object Model) Events:

Mouse Events Keyboard Events Form EventsDocument/Window

Events

click keypress submit load

dblclick keydown change resize

mouseenter keyup focus scroll

mouseleave blur unload

Web programming Networking Laboratory 17/65

jQuery Events (3/3)

If you want an events to work on your page, you should call it inside

the function:

$(document).ready(function) {

// jQuery methods go here...

});

Everything inside this function will load as soon as the DOM is loaded

and before the page contents are loaded

Web programming Networking Laboratory 18/65

How to use Custom Scripts?

It is better to write our custom code in the custom JavaScript file as

follow:

/* Filename: custom.js */

$(document).ready(function() {

$("div").click(function() {

alert("Hello, world!");

});

});

Web programming Networking Laboratory 19/65

How to use Custom Scripts?

Then, we can include the custom file in our HTML file:

<html>

<head>

<script type = "text/javascript" src =

"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jque

ry.min.js">

</script>

<script src = "/jquery/custom.js">

</script>

</head>

<body>

….

</body>

</html>

Web programming Networking Laboratory 20/65

jQuery Events - click() (1/3)

Web_jQuery.html

<!DOCTYPE html>

<html>

<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.

1/jquery.min.js"></script>

<script src="function.js"></script>

</head>

<body>

<p>If you click on me, I will disappear.</p>

<p>Click me too!</p>

</body>

</html>

Web programming Networking Laboratory 21/65

jQuery Events - click() (2/3)

Function.js

$(document).ready(function(){

$("p").click(function(){

$(this).hide();

});

});

Web programming Networking Laboratory 22/65

jQuery Events - click() (3/3)

Result

Web programming Networking Laboratory 23/65

jQuery Events - mouseenter() (1/3)

Web_jQuery.html

<!DOCTYPE html>

<html>

<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3

.1/jquery.min.js"></script>

<script src="function.js"> </script>

</head>

<body>

<p id="p1">Enter this paragraph.</p>

</body>

</html>

Web programming Networking Laboratory 24/65

jQuery Events - mouseenter() (2/3)

Function.js

$(document).ready(function(){

$("#p1").mouseenter(function(){

alert("You entered p1!");

});

});

Web programming Networking Laboratory 25/65

jQuery Events - mouseenter() (3/3)

Result

Web programming Networking Laboratory 26/65

jQuery Events - hover() (1/3)

Web_jQuery.html

<!DOCTYPE html>

<html>

<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.

3.1/jquery.min.js"></script>

<script src="function.js"></script>

</head>

<body> <p id="p1">This is a paragraph.</p>

</body>

</html>

Web programming Networking Laboratory 27/65

jQuery Events - hover() (2/3)

Function.js

$(document).ready(function(){

$("#p1").hover(function(){

alert("You entered p1!");

},

function(){

alert("Bye! You now leave p1!");

});

});

Web programming Networking Laboratory 28/65

jQuery Events - hover() (3/3)

Result

Web programming Networking Laboratory 29/65

jQuery Events - focus() & blur() (1/3)

Web_jQuery.html

<!DOCTYPE html><html><head><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><script src="function.js"></script></head><body>Name: <input type="text" name="fullname"><br>Email: <input type="text" name="email"></body></html>

Web programming Networking Laboratory 30/65

jQuery Events - focus() & blur() (2/3)

Function.js

$(document).ready(function(){$("input").focus(function(){

$(this).css("background-color", "#cccccc");});$("input").blur(function(){

$(this).css("background-color", "#ffffff");});

});

Web programming Networking Laboratory 31/65

jQuery Events - focus() & blur() (3/3)

Result

Web programming Networking Laboratory 32/65

jQuery Events – Exercise (1/3)

jQuery_event.html

<!DOCTYPE html>

<html>

<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3

.1/jquery.min.js"></script>

<script src =" jQuery_event_function.js" ></script>

</head>

<body>

<input type="text" value="Press any key inside me to hide me"

size="40">

</body>

</html>

Web programming Networking Laboratory 33/65

jQuery Events – Exercise (2/3)

jQuery_event_function.js

Use the correct event to:

If you press a keyboard key inside the <input> element, it should be

hidden.

$(document).ready(function(){

$("selector").event(function(){

$(this).hide();

});

});

Web programming Networking Laboratory 34/65

jQuery Events – Exercise (3/3)

Solution

$(document).ready(function(){

$("input").keypress(function(){

$(this).hide();

});

});

Web programming Networking Laboratory 35/65

jQuery Effects

There are some jQuery methods for creating animation effects.

Hide()/Show()

Fade()

Animate()

Chaining()

Web programming Networking Laboratory 36/65

jQuery EffectsHide()/Show()

Hide and show HTML elements

Syntax:

$(selector).hide();

$(selector).show();

jQuery toggle()

Toggle method helps toggle between the hide() and show() methods

Syntax:

$(selector).toggle();

Web programming Networking Laboratory 37/65

jQuery EffectsHide()/Show() – Example (1/3)

jQuery_toggle.html

<!DOCTYPE html>

<html>

<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3

.1/jquery.min.js"></script>

<script src =" function.js"></script>

</head>

<body>

<button>Toggle between hiding and showing the paragraphs</but

ton>

<p>This is a paragraph with little content.</p>

<p>This is another small paragraph.</p>

</body>

</html>

Web programming Networking Laboratory 38/65

jQuery EffectsHide()/Show() – Example (2/3)

function.js

$(document).ready(function(){

$("button").click(function(){

$("p").toggle();

});

});

Web programming Networking Laboratory 39/65

jQuery EffectsHide()/Show() – Example (3/3)

Result

Web programming Networking Laboratory 40/65

jQuery EffectsFade()

Fade elements in and out of visibility.

fadeIn():

Fade in a hidden element.

Syntax: $(selector).fadeIn();

fadeOut():

Fade out a visible element.

Syntax: $(selector).fadeOut();

fadeToggle():

Toggles between the fadeIn() and fadeOut() methods.

Syntax: $(selector).fadeToggle();

fadeTo():

Allows fading to a given opacity (value between 0 and 1).

Syntax: $(selector).fadeTo();

Web programming Networking Laboratory 41/65

jQuery Effects Animate()

Used to create custom animations.

Syntax:

$(selector).animate({params}, speed, callback);

params parameter defines the CSS properties to be animated.

speed parameter specifies the duration of the effect.

callback parameter is a function to be executed after the animation completes

Web programming Networking Laboratory 42/65

jQuery Effects Chaining (1/3)

Allows us to run multiple jQuery methods (on the same element) within

a single statement.

Web_jQuery.html

<!DOCTYPE html>

<html>

<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.

3.1/jquery.min.js"></script>

<script src ="function.js"></script>

</head>

<body>

<p id="p1">jQuery is fun!!</p>

<button>Click me</button>

</body>

</html>

Web programming Networking Laboratory 43/65

jQuery Effects Chaining (2/3)

Function.js

$(document).ready(function(){

$("button").click(function(){

$("#p1").css("color", "red").fadeOut("slow").fadeIn("

slow");

});

});

Web programming Networking Laboratory 44/65

jQuery Effects Chaining (3/3)

Result

Web programming Networking Laboratory 45/65

jQuery HTML

Change Content and Attributes:

text(), html(), val()

attr()

Add elements

Add new HTML content: append(), prepend(), after(), before()

Add several new Elements

Remove Elements/Content: remove(), empty()

Get and Set CSS classes: addClass(), removeClass(), toggleClass()

Work with Dimensions: width(), height()

Web programming Networking Laboratory 46/65

jQuery HTMLGet/Set Content and Attributes

text() - Sets or returns the text content of selected elements

html() - Sets or returns the content of selected elements

val() - Sets or returns the value of form fields

attr() – Get/Change attribute values.

Web programming Networking Laboratory 47/65

jQuery HTMLGet Content and Attributes – Example (1/3)

jQuery_html_Content.html

<!DOCTYPE html>

<html>

<head>

<script

src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.

min.js"></script>

<script src ="function.js" ></script>

</head>

<body>

<p id="test">This is some <i>italic</i> text in a para.</p>

<button id="btn1">Show Text</button>

<button id="btn2">Show HTML</button>

<p><a href="https://www.skku.edu" id="w3s">SKKU

Homepage</a></p>

<button id="btn3">Show href Value</button>

</body>

</html>

Web programming Networking Laboratory 48/65

jQuery HTMLGet Content and Attributes – Example (2/3)

function.js

$(document).ready(function(){

$("#btn1").click(function(){

alert("Text: " + $("#test").text());

});

$("#btn2").click(function(){

alert("HTML: " + $("#test").html());

});

$("#btn3").click(function(){

alert($("#w3s").attr("href"));

});

});

Web programming Networking Laboratory 49/65

jQuery HTMLGet Content and Attributes – Example (3/3)

Result

Web programming Networking Laboratory 50/65

jQuery HTMLGet and Set CSS Classes

addClass() - Adds one or more classes to the selected elements

removeClass() - Removes one or more classes from the selected elem

ents

toggleClass() - Toggles between adding/removing classes from the sel

ected elements

css() - Sets or returns the style attribute

Web programming Networking Laboratory 51/65

jQuery HTMLGet and Set CSS Classes – Example (1/3)

jQuery_html_css.html

<!DOCTYPE html>

<html>

<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.

3.1/jquery.min.js"></script>

<script src="function.js"></script>

<style>.blue {color: blue;} </style>

</head>

<body>

<h1>Heading 1</h1>

<h2>Heading 2</h2>

<p>This is a paragraph.</p>

<p>This is another paragraph.</p>

<button>Toggle class</button>

</body>

</html>

Web programming Networking Laboratory 52/65

jQuery HTMLGet and Set CSS Classes – Example (2/3)

function.js

$(document).ready(function(){

$("button").click(function(){

$("h1, h2, p").toggleClass("blue");

});

});

Web programming Networking Laboratory 53/65

jQuery HTMLGet and Set CSS Classes – Example (3/3)

Result

Web programming Networking Laboratory 54/65

jQuery HTMLDimensions

There are several important methods for working with dimensions:

width()

height()

innerWidth()

innerHeight()

outerWidth()

outerHeight()

Web programming Networking Laboratory 55/65

AJAX Introduction

AJAX stands for Asynchronous JavaScript And XML.

This is not a programming language. AJAX is a web development

technique for creating better, faster and more interactive web

applications of XML, HTML, CSS, and JavaScript

AJAX uses HTML for content, CSS for presentation, along with Document

Object Model and JavaScript for dynamic content display.

With AJAX, when you hit submit, JavaScript will make a request to the

server, interpret the results, and update the current screen. The user would

never know that anything was even transmitted to the server.

A user can continue to use the application while the client program

requests information from the server in the background.

Web programming Networking Laboratory 56/65

AJAX – Browser support

All the available browsers cannot support AJAX. Here is a list of major

browsers that support AJAX.

Mozilla Firefox 1.0 and above.

Netscape version 7.1 and above.

Apple Safari 1.2 and above.

Microsoft Internet Explorer 5 and above.

Konqueror.

Opera 7.6 and above.

NOTE − When we say that a browser does not support AJAX, it simply

means that the browser does not support the creation of JavaScript

object – XMLHttpRequest object.

Web programming Networking Laboratory 57/65

How AJAX Works

An event occurs in a web

page (the page is loaded, a

button is clicked)

An XMLHttpRequest object

is created by JavaScript

The XMLHttpRequest

object sends a request to a

web server

The server processes the

request

The server sends a response back to the web page

The response is read by JavaScript

Proper action (like page update) is performed by JavaScript

Web programming Networking Laboratory 58/65

AJAX - Examples

Examples of applications using AJAX:

Gmail: A webmail built on the idea that emails can be more intuitive,

efficient, and useful.

Google Maps: A user can drag an entire map by using the mouse, rather

than clicking on a button.

Google: As you type, Google offers suggestions. Use the arrow keys to

navigate the results.

YouTube: Offers suggestions when we type.

Difference between AJAX and Conventional CGI Program

https://www.tutorialspoint.com/ajax/ajax_examples.htm

Web programming Networking Laboratory 59/65

AJAX with jQuery

jQuery provides several methods for AJAX functionality.

With the jQuery - AJAX methods, we can

Request text, HTML, XML, or JSON from a remote server using both

HTTP Get and HTTP Post

Load the external data directly into the selected HTML elements of your

web page

Web programming Networking Laboratory 60/65

JSON Introduction

JSON stands for JavaScript Object Notation.

It was designed for human-readable data interchange.

It has been extended from the JavaScript scripting language.

The filename extension is .json.

JSON is language independent

Uses JavaScript syntax, but the JSON format is text only.

Text can be read and used as a data format by any programming

language.

Web programming Networking Laboratory 61/65

The uses of JSON

Exchanging between a server and web applications,

When exchanging data between a browser and a server, the data can be text.

JSON is text, we can convert any JavaScript object into JSON, and vice

verse.

Storing Data

When storing data, the data has to be a certain format, and regardless of

where you choose to store it, text is always one of the legal formats.

It can be used with modern programming languages, which include C,

C++, Java, Python, etc…

Web programming Networking Laboratory 62/65

JSON Basic Syntax Rules

Data is in name/value pairs – {“name” : ”ABC”}

Uses double quotes (“”) around NAME and VALUE

Data is separated by commas (,)

Curly braces ({}) hold objects, each name is followed by colon (:)

Square brackets ([]) hold arrays

File type is “.json”

Web programming Networking Laboratory 63/65

JSON – Data Types

Number: Can be an Integer/Float, Fraction, Exponent

String: String of Unicode character. Use double quotes

Boolean: True or False values

Array: An ordered collection of values. The values are separated by

comma and these are enclosed in square brackets

Object: Unordered collection of key/values pairs. Objects are enclosed

in curly braces. Each name is followed by colon and the key/value

pairs are separated by comma.

Null: Empty value

Web programming Networking Laboratory 64/65

JSON – Example

{

“name”:”Kim”

“age”:40

“address”:{

“city”:”Seoul”

“country”: “Korea”

}

“children”:[“Anna”,”Bell”]

}

Web programming Networking Laboratory 65/65

Q & A