JavaScript + Ajax + Jquery
JavaScript + Ajax + Jquery
JavaScript + Ajax + Jquery
http://www.w3schools.com/js/default.asp
https://developer.mozilla.org/en-US/Learn/Getting_started_with_the_web/JavaScript_basics
http://www.learn-js.org/
http://www.tutorialspoint.com/javascript/
http://www.w3schools.com/ajax/
https://api.jquery.com/
http://www.w3schools.com/jquery/
JavaScript
1. What is JavaScript
JavaScript is a dynamic programming language, most commonly used as part of web browsers,
whose implementations allow client-side scripts to interact with the user, control the browser,
communicate asynchronously, and alter the document content that is displayed. It is also used
in server-side network programming with runtime environments such as Node.js, game
development and the creation of desktop and mobile applications. With the rise of the singlepage web app and JavaScript-heavy sites, it is increasingly being used as a compile target for
source-to-source compilers from both dynamic languages and static languages.
JavaScript is classified as a prototype-based scripting language with dynamic typing and firstclass functions. This mix of features makes it a multi-paradigm language, supporting objectoriented, imperative, and functional programming styles. Despite some naming, syntactic, and
standard library similarities, JavaScript and Java are otherwise unrelated and have very
different semantics. The syntax of JavaScript is actually derived from C, while the semantics
and design are influenced by the Self and Scheme programming languages.
Advantages of JavaScript
The merits of using JavaScript are:
Less server interaction: You can validate user input before sending the page off to the
server. This saves server traffic, which means less load on your server.
Immediate feedback to the visitors: They don't have to wait for a page reload to see if
they have forgotten to enter something.
Increased interactivity: You can create interfaces that react when the user hovers over
them with a mouse or activates them via the keyboard.
Richer interfaces: You can use JavaScript to include such items as drag-and-drop
components and sliders to give a Rich Interface to your site visitors.
JavaScript can not be used for Networking applications because there is no such
support available.
JavaScript doesn't have any multithreading or multiprocess capabilities.
Once again, JavaScript is a lightweight, interpreted programming language that allows you to
build interactivity into otherwise static HTML pages.
2.
JavaScript where to
JavaScript can be placed in the <head> and the <body> sections of an HTML page. In HTML,
JavaScript code must be inserted between <script> and </script> tags.
<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>
JavaScript in <head> - Try it yourself
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>
<h1>My Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
</body>
</html>
JavaScript in <body> - Try it yourself
<!DOCTYPE html>
<html>
<body>
<h1>My Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction() {
3.
JavaScript output
JavaScript does not have any built-in print or display functions. JavaScript can "display" data in
different ways:
Writing into an alert box, using window.alert().
Writing into the HTML output using document.write().
Writing into an HTML element, using innerHTML.
Writing into the browser console, using console.log().
Using window.alert() - Try it yourself
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
window.alert(5 + 6);
</script>
</body>
</html>
Using document.write() - Try it yourself
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
document.write(5 + 6);
</script>
</body>
</html>
Using innerHTML - Try it yourself
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My First Paragraph</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
</body>
</html>
Using console.log() - Try it yourself
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
console.log(5 + 6);
</script>
</body>
</html>
4.
JavaScript variables are containers for storing data values. JavaScript variables can hold many
data types: numbers, strings, arrays, objects and more:
var
var
var
var
length = 16;
lastName = "Johnson";
cars = ["Saab", "Volvo", "BMW"];
x = {firstName:"John", lastName:"Doe"};
//
//
//
//
Number
String
Array
Object
JavaScript has dynamic types. This means that the same variable can be used as different
types:
var x;
var x = 5;
var x = "John";
// Now x is undefined
// Now x is a Number
// Now x is a String
JavaScript strings
A string (or a text string) is a series of characters like "John Doe". Strings are written with
quotes. You can use single or double quotes:
var carName = "Volvo XC60";
var carName = 'Volvo XC60';
You can use quotes inside a string, as long as they don't match the quotes surrounding the
string:
var answer = "It's alright"; // Single quote inside double quotes
var answer = "He is called 'Johnny'"; // Single quotes inside double
quotes
var answer = 'He is called "Johnny"'; // Double quotes inside single
quotes
More about strings
JavaScript numbers
JavaScript has only one type of numbers. Numbers can be written with, or without decimals:
var x1 = 34.00;
var x2 = 34;
Extra large or extra small numbers can be written with scientific (exponential) notation:
var y = 123e5;
var z = 123e-5;
// 12300000
// 0.00123
"John"
3.14
false
[1,2,3,4]
{name:'John', age:34}
//
//
//
//
//
Returns
Returns
Returns
Returns
Returns
string
number
boolean
object
object
Undefined
In JavaScript, a variable without a value, has the value undefined. The typeof is also
undefined.
var person;
Any variable can be emptied, by setting the value to undefined. The type will also be
undefined.
person = undefined;
Empty values
An empty value has nothing to do with undefined. An empty string variable has both a value and
a type.
var car = "";
Null
In JavaScript null is "nothing". It is supposed to be something that doesn't exist. Unfortunately,
in JavaScript, the data type of null is an object.
var person = null;
object
5.
//
//
//
//
undefined
object
false
true
JavaScript operators
Addition
Subtraction
Multiplication
Division
Modulus
++
Increment
--
Decrement
x=y
x=y
+=
x += y
x=x+y
-=
x -= y
x=x-y
*=
x *= y
x=x*y
/=
x /= y
x=x/y
%=
x %= y
x=x%y
Operator Description
==
equal to
===
!=
not equal
!==
>
greater than
<
less than
>=
<=
6.
JavaScript functions
A JavaScript function is defined with the function keyword, followed by a name, followed by
parentheses (). Function names can contain letters, digits, underscores, and dollar signs (same
rules as variables). The parentheses may include parameter names separated by commas:
(parameter1, parameter2, ...). The code to be executed, by the function, is placed inside curly
brackets: {}
When JavaScript reaches a return statement, the function will stop executing. If the function was
invoked from a statement, JavaScript will "return" to execute the code after the invoking
statement. Functions often compute a return value. The return value is "returned" back to the
"caller":
var x = myFunction(4, 3);
will end up in x
function myFunction(a, b) {
return a * b;
and b
}
The result in x will be: 12.
Why functions?
You can reuse code: Define the code once, and use it many times. You can use the same code
many times with different arguments, to produce different results.
Convert Fahrenheit to Celsius:
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
document.getElementById("demo").innerHTML = toCelsius(32);
In JavaScript, you can use functions the same way as you use variables.
var text = "The temperature is " + toCelsius(32) + " Centigrade";
instead of:
var x = toCelsius(32);
var text = "The temperature is " + x + " Centigrade";
7.
Declaring a class
When creating a script to use objects, you need to design a composite of data and code called a
class. Each new object based on this class is called an instance of that class. The data
associated with an object are called its properties, while the functions it uses are called
methods.
Lets look at how to declare the class for an object called User that will contain details about the
current user. To create the class, just write a function named after the class. This function can
accept arguments and can create properties and methods for the objects in that class. The
function is called a constructor.
<script>
function User(forename, username, password) {
this.forename = forename;
this.username = username;
this.password = password;
this.showUser = function() {
document.write("Forename: " + this.forename + "<br />");
document.write("Username: " + this.username + "<br />");
document.write("Password: " + this.password + "<br />");
}
}
</script>
Creating an object
To create an instance of the class User, you can use a statement such as the following:
details = new User("Wolfgang", "w.a.mozart", "composer");
Or you can create an empty object, like this:
details = new User();
and then populate it later, like this:
details.forename = "Wolfgang";
details.username = "w.a.mozart";
details.password = "composer";
You can also add new properties to an object, like this:
details.greeting = "Hello";
Accessing objects
To access an object, you can refer to its properties, as in the following two unrelated example
statements:
name = details.forename;
if (details.username == "Admin") loginAsAdmin();
So to access the showUser method of an object of class User, you would use the following
syntax, in which the object details has already been created and populated with data:
details.showUser();
Assuming the data supplied earlier, this code would display:
Forename: Wolfgang
Username: w.a.mozart
Password: composer
8.
JavaScript events
HTML events are "things" that happen to HTML elements. When JavaScript is used in HTML
pages, JavaScript can "react" on these events. Often, when events happen, you may want to do
something. JavaScript lets you execute code when events are detected. HTML allows event
handler attributes, with JavaScript code, to be added to HTML elements.
In the following example, an onclick attribute (with code), is added to a button element:
<button onclick='getElementById("demo").innerHTML=Date()'>The time
is?</button>
Here is a list of some common HTML events:
Event
Description
onchange
onclick
onkeydown
onload
Event handlers can be used to handle, and verify, user input, user actions, and browser actions:
Things that should be done every time a page loads
Things that should be done when the page is closed
Action that should be performed when a user clicks a button
Content that should be verified when a user inputs data
And more ...
9.
A regular expression is a sequence of characters that forms a search pattern. When you search
for data in a text, you can use this search pattern to describe what you are searching for. A
regular expression can be a single character, or a more complicated pattern. Regular
expressions can be used to perform all types of text search and text replace operations.
var patt = /javascript/i
Example explained:
/javascript/i is a regular expression.
javascript is a pattern (to be used in a search).
i is a modifier (modifies the search to be case-insensitive).
In JavaScript, regular expressions are often used with the two string methods: search() and
replace().
The search() method uses an expression to search for a match, and returns the position of the
match.
The replace() method returns a modified string where the pattern is replaced.
Use a regular expression to do a case-insensitive search for "javascript" in a string:
var str = "I am learning JavaScript.";
var n = str.search(/javascript/i);
The result will be: 14.
Use a string to do a search for "JavaScript" in a string:
var str = "I am learning JavaScript.";
var n = str.search("JavaScript");
Use a case insensitive regular expression to replace PHP with JavaScript in a string:
var str = "I am learning PHP.";
var res = str.replace(/php/i, "JavaScript");
Perform a global match (find all matches rather than stopping after the first match)
[0-9]
(x|y)
Find a digit
\s
\b
\uxxxx
Quantifier Description
n+
n*
n?
10.
JavaScript errors
When executing JavaScript code, different errors can occur. Errors can be coding errors made
by the programmer, errors due to wrong input, and other unforeseeable things. To handle these
errors use throw and try to catch:
the try statement lets you test a block of code for errors;
the catch statement lets you handle the error;
the throw statement lets you create custom errors;
the finally statement lets you execute code, after try and catch, regardless of the result.
try {
Block of code to try
}
catch(err) {
11.
JSON is an open standard format that uses human-readable text to transmit data objects
consisting of attributevalue pairs. It is used primarily to transmit data between a server and
web application, as an alternative to XML.
The following JSON syntax defines an employees object: an array of 3 employee records
(objects):
{"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]}
The JSON format is syntactically identical to the code for creating JavaScript objects. Because
of this similarity, a JavaScript program can easily convert JSON data into native JavaScript
objects.
12.
With the HTML DOM, JavaScript can access and change all the elements of an HTML
document. When a web page is loaded, the browser creates a Document Object Model of the
page. The HTML DOM model is constructed as a tree of Objects:
With the object model, JavaScript gets all the power it needs to create dynamic HTML:
can change all the HTML elements in the page
can change all the HTML attributes in the page
can change all the CSS styles in the page
can remove existing HTML elements and attributes
can add new HTML elements and attributes
can react to all existing HTML events in the page
can create new HTML events in the page
Description
document.getElementById()
document.getElementsByTagName()
Description
element.innerHTML=
element.attribute=
Description
document.appendChild()
document.replaceChild()
document.write(text)
Description
<body>
<script>
document.write(Date());
</script>
</body>
</html>
This example changes the content of a <p> element:
<html>
<body>
<p id="p1">Hello World!</p>
<script>
document.getElementById("p1").innerHTML = "New text!";
</script>
</body>
</html>
This example changes the value of the src attribute of an <img> element:
<!DOCTYPE html>
<html>
<body>
<img id="myImage" src="smiley.gif">
<script>
document.getElementById("myImage").src = "landscape.jpg";
</script>
</body>
</html>
To change the value of an HTML attribute, use this syntax:
document.getElementById(id).attribute=new value
<script>
document.getElementById("p2").style.color = "blue";
</script>
<p>The paragraph above was changed by a script.</p>
</body>
</html>
To change the style of an HTML element, use this syntax:
document.getElementById(id).style.property=new style
How it works
AJAX cannot work independently, it is based on internet standards, and uses a combination of:
XMLHttpRequest object (to exchange data asynchronously with a server)
JavaScript/DOM (to display/interact with the information)
CSS (to style the data)
XML (often used as the format for transferring data)
2.
All modern browsers support the XMLHttpRequest object (IE5 and IE6 use an ActiveXObject).
The XMLHttpRequest object is used to exchange data with a server behind the scenes.
All modern browsers (IE7+, Firefox, Chrome, Safari, and Opera) have a built-in
XMLHttpRequest object. To handle all modern browsers, including IE5 and IE6, check if the
browser supports the XMLHttpRequest object. If it does, create an XMLHttpRequest object, if
not, create an ActiveXObject:
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
3.
AJAX request
To send a request to a server, we use the open() and send() methods of the XMLHttpRequest
object:
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
Method
Description
open(method,url,async) Specifies the type of request, the URL, and if the request should be
handled asynchronously or not.
method: the type of request: GET or POST
url: the location of the file on the server
async: true (asynchronous) or false (synchronous)
send(string)
GET or POST?
GET is simpler and faster than POST, and can be used in most cases.
However, always use POST requests when:
A cached file is not an option (update a file or database on the server)
Sending a large amount of data to the server (POST has no size limitations)
Sending user input (which can contain unknown characters), POST is more robust and
secure than GET
GET requests
A simple GET request:
xmlhttp.open("GET","demo_get.asp",true);
xmlhttp.send();
In the example above, you may get a cached result. To avoid this, add a unique ID to the URL:
xmlhttp.open("GET","demo_get.asp?t=" + Math.random(),true);
xmlhttp.send();
If you want to send information with the GET method, add the information to the URL:
xmlhttp.open("GET","demo_get2.asp?fname=Henry&lname=Ford",true);
xmlhttp.send();
POST requests
A simple POST request:
xmlhttp.open("POST","demo_post.asp",true);
xmlhttp.send();
To POST data like an HTML form, add an HTTP header with setRequestHeader(). Specify the
data you want to send in the send() method:
xmlhttp.open("POST","ajax_test.asp",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-formurlencoded");
xmlhttp.send("fname=Henry&lname=Ford");
Method
Description
xmlhttp.open("GET","ajax_test.asp",true);
The file can be any kind of file, like .txt and .xml, or server scripting files like .asp and .php
(which can perform actions on the server before sending the response back).
Server response
To get the response from a server, use the responseText or responseXML property of the
XMLHttpRequest object.
Property
Description
responseText
jQuery
1. What is jQuery
jQuery is a lightweight, "write less, do more", JavaScript library. The purpose of jQuery is to
make it much easier to use JavaScript on your website. jQuery takes a lot of common tasks that
require many lines of JavaScript code to accomplish, and wraps them into methods that you can
call with a single line of code. jQuery also simplifies a lot of the complicated things from
JavaScript, like AJAX calls and DOM manipulation.
The jQuery library contains the following features:
HTML/DOM manipulation
CSS manipulation
HTML event methods
Effects and animations
AJAX
Utilities
Why jQuery?
There are lots of other JavaScript frameworks out there, but jQuery seems to be the most
popular, and also the most extendable.
Many of the biggest companies on the Web use jQuery, such as:
Google
Microsoft
IBM
Netflix
2.
There are several ways to start using jQuery on your web site. You can:
Downloading jQuery
There are two versions of jQuery available for downloading:
Production version - this is for your live website because it has been minified and
compressed
Development version - this is for testing and development (uncompressed and readable
code)
Both versions can be downloaded from jQuery.com.
The jQuery library is a single JavaScript file, and you reference it with the HTML <script> tag
(notice that the <script> tag should be inside the <head> section):
<head>
<script src="jquery-1.11.2.min.js"></script>
</head>
jQuery CDN
If you don't want to download and host jQuery yourself, you can include it from a CDN (Content
Delivery Network).
Both Google and Microsoft host jQuery.
To use jQuery from Google or Microsoft, use one of the following:
Google CDN:
<head>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"
></script>
</head>
Microsoft CDN:
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery1.11.2.min.js"></script>
</head>
3.
jQuery syntax
The jQuery syntax is tailor made for selecting HTML elements and performing some action on
the element(s).
4.
jQuery Selectors
});
});
Description
$("*")
$(this)
$("p.intro")
$("p:first")
$("ul li:first")
$("ul li:first-child")
$("[href]")
$("a[target='_blank']")
Selects all <a> elements with a target attribute value equal to "_blank"
$("a[target!='_blank']") Selects all <a> elements with a target attribute value NOT equal to
"_blank"
$(":button")
$("tr:even")
$("tr:odd")
5.
All the different visitor's actions that a web page can respond to are called events. An event
represents the precise moment when something happens.
Examples:
moving a mouse over an element
selecting a radio button
clicking on an element
Here are some common DOM events:
Mouse events Keyboard events Form events Document/Window Events
click
keypress
submit
load
dblclick
keydown
change
resize
mouseenter
keyup
focus
scroll
blur
unload
mouseleave
In jQuery, most DOM events have an equivalent jQuery method. To assign a click event to all
paragraphs on a page, you can do this:
$("p").click(function(){
// action goes here!!
});
The dblclick() method attaches an event handler function to an HTML element. The function is
executed when the user double-clicks on the HTML element:
$("p").dblclick(function(){
$(this).hide();
});
The mouseenter() method attaches an event handler function to an HTML element. The
function is executed when the mouse pointer enters the HTML element:
$("#p1").mouseenter(function(){
alert("You entered p1!");
});
The mouseleave() method attaches an event handler function to an HTML element. The
function is executed when the mouse pointer leaves the HTML element:
$("#p1").mouseleave(function(){
alert("Bye! You now leave p1!");
});
The mousedown() method attaches an event handler function to an HTML element. The
function is executed, when the left mouse button is pressed down, while the mouse is over the
HTML element:
$("#p1").mousedown(function(){
alert("Mouse down over p1!");
});
The mouseup() method attaches an event handler function to an HTML element. The function
is executed, when the left mouse button is released, while the mouse is over the HTML element:
$("#p1").mouseup(function(){
alert("Mouse up over p1!");
});
The hover() method takes two functions and is a combination of the mouseenter() and
mouseleave() methods. The first function is executed when the mouse enters the HTML
element, and the second function is executed when the mouse leaves the HTML element:
$("#p1").hover(function(){
alert("You entered p1!");
},
function(){
alert("Bye! You now leave p1!");
});
The focus() method attaches an event handler function to an HTML form field. The function is
executed when the form field gets focus:
$("input").focus(function(){
$(this).css("background-color", "#cccccc");
});
The blur() method attaches an event handler function to an HTML form field. The function is
executed when the form field loses focus:
$("input").blur(function(){
$(this).css("background-color", "#ffffff");
});
$("p").on("click", function(){
$(this).hide();
});
Attach multiple event handlers to a <p> element:
$("p").on({
mouseenter: function(){
$(this).css("background-color", "lightgray");
},
mouseleave: function(){
$(this).css("background-color", "lightblue");
},
click: function(){
$(this).css("background-color", "yellow");
}
});