Jquery, Ajax, Json
Jquery, Ajax, Json
<head>
<script src="jquery-3.3.1.min.js"></script>
</head>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/
3.3.1/jquery.min.js"></script>
</head>
JQUERY SYNTAX
Basic syntax is: $(selector).action()
A $ sign to define/access jQuery
A (selector) to "query (or find)" HTML elements
A jQuery function action() to be performed on the element(s)
Examples:
$(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".
THE DOCUMENT READY EVENT
You might have noticed that all jQuery methods are inside a document ready event:
This is to prevent any jQuery code from running before the document is finished
loading (is ready).
It is good practice to wait for the document to be fully loaded and ready before
working with it. This also allows you to have your JavaScript code before the body of
your document, in the head section.
$(document).ready(function(){
// jQuery methods go here...
});
$(function(){
// jQuery methods go here...
});
JQUERY SELECTORS
Syntax Description
The element Selector
$("*") Selects all elements
$("p")
$(this) Selects the current HTML element
The #id Selector Selects all <p> elements with class="intro"
$("p.intro")
$("#test")
$("p:first") Selects the first <p> element
The
$("ul .class Selector
li:first") Selects the first <li> element of the first <ul>
$("ul li:first-child")
$(".test") Selects the first <li> element of every <ul>
More ExamplesSelects
$("[href]") all elements
of jQuery with an href attribute
Selectors
$("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") Selects all <button> elements and <input> elements of type="button"
$("tr:even") Selects all even <tr> elements
$("tr:odd") Selects all odd <tr> elements
JQUERY EVENT METHODS
Click, keypress, submit, load, dblclick, keydown, change, resize,
mouseenter, keyup, focus, scroll, mouseleave, blur, unload
$(document).ready(function(){
$("p").click(function(){
// action goes here!!
});
});
JQUERY - GET CONTENT AND ATTRIBUTES
Three simple, but useful, jQuery methods for DOM manipulation are:
text() - Sets or returns the text content of selected elements
html() - Sets or returns the content of selected elements (including HTML
markup)
val() - Sets or returns the value of form fields
$("#btn2").click(function(){
alert("HTML: " + $("#test").html());
});
The jQuery attr() method is used to get attribute values.
$("button").click(function(){
alert($("#w3s").attr("href"));
});
The jQuery data() method is used to get attribute values.
$("button").click(function(){
alert($("#w3s").data(“option"));
});
JQUERY - SET CONTENT AND ATTRIBUTES
We will use the same three methods from the previous page to set content:
text() - Sets or returns the text content of selected elements
html() - Sets or returns the content of selected elements (including HTML markup)
val() - Sets or returns the value of form fields
$("#btn2").click(function(){
$("#test2").html("<b>Hello world!</b>");
});
The jQuery attr() method is also used to set/change attribute values.
$("button").click(function(){
$("#w3s").attr({
"href" : "https://www.w3schools.com/jquery/",
"title" : "W3Schools jQuery Tutorial"
});
});
JQUERY - ADD ELEMENTS
We will look at four jQuery methods that are used to add new
content:
append() - Inserts content at the end of the selected elements
$("table").append("<tr><td>add row append table</td></tr>");
prepend() - Inserts content at the beginning of the selected elements
$("table").append("<tr><td>add row prepend table</td></tr>");
after() - Inserts content after the selected elements
$("p").after("<span>Some text after</span>");
before() - Inserts content before the selected elements
$("p").after("<span>Some text before</span>");
JQUERY - REMOVE ELEMENTS
remove() - Removes the selected element (and its child elements)
$("#div1").remove();
empty() - Removes the child elements from the selected element
$("#div1").empty();
The following example removes all <p> elements with class="test"
and class="demo":
$("p").remove(".test, .demo");
JQUERY - GET AND SET CSS CLASSES
Query has several methods for CSS manipulation. We will look at
the following methods:
addClass() - Adds one or more classes to the selected elements
$("h1, h2, p").addClass("blue");
removeClass() - Removes one or more classes from the selected
elements
$("h1, h2, p").removeClass("blue");
toggleClass() - Toggles between adding/removing classes from the
selected elements
$("h1, h2, p").toggleClass("blue");
css() - Sets or returns the style attribute
$("p").css("background-color", "yellow");
css("propertyname","value");
JQUERY DIMENSION METHODS
jQuery has several important methods for working with
dimensions:
width()
height()
innerWidth()
innerHeight()
outerWidth()
outerHeight()
$("button").click(function(){
var txt = "";
txt += "Width: " + $("#div1").width();
txt += "Height: " + $("#div1").height();
$("#div1").html(txt);
});
LOOPING OVER THE DOM
<ul>
<li>foo</li>
<li>bar</li>
</ul>
$( "li" ).each(function() {
$( this ).addClass( "foo" );
});
UNDERSTANDING SYNCHRONOUS VS ASYNCHRONOUS
AJAX = Asynchronous
JavaScript And XML.
AJAX is about loading data in
the background and display it
on the webpage, without
reloading the whole page.
http://api.jquery.com/jquery.aj
ax/
OPTION DESCRIPTION
url The URL to make a request from
type whether to use POST or GET
data an object literal filled with query parameters and their values
dataType The type of data you are expecting to recieve, one of: "text", "html", "json", "xml"
timeout an amount of time in seconds to wait for the server before giving up
success event: called when the request finishes successfully
error event: called when the request fails
complete event: called when the request finishes successfully or erroneously
The data passed to your success handler will be in whatever format
you specified in the dataType option
a dataType of text returns raw text no matter its apparent data type
a dataType of html returns raw html text
a dataType of xml returns an XML document object
a dataType of json returns a JSON object
DEBUGGING AJAX CODE
Chrome Dev Tool's Network tab shows each request, parameters,
response, errors
Firefox Inspect Element’s Network tab shows each request,
parameters, response, errors
expand a request by clicking on it and look at Response tab to see
Ajax result
check the Console tab for any errors that are thrown by requests
XML
What is XML?
XML stands for eXtensible Markup Language
XML is a markup language much like HTML
XML was designed to store and transport data
XML was designed to be self-descriptive
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
JSON
JSON: JavaScript Object Notation.
JSON is a syntax for storing and exchanging data.
When exchanging data between a browser and a server, the data can only
be text.
JSON is text, and we can convert any JavaScript object into JSON, and
send JSON to the server.
We can also convert any JSON received from the server into JavaScript
objects.
Sending Data
var myObj = { "name":"John", "age":31, "city":"New York" };
var myJSON = JSON.stringify(myObj);
Receiving Data
var myJSON = '{ "name":"John", "age":31, "city":"New York" }';
var myObj = JSON.parse(myJSON);
JSON SYNTAX
JSON data is written as name/value pairs.
"name":"John"
{"employees":[
{ "firstName":"John", "lastName":"Doe" },
{ "firstName":"Anna", "lastName":"Smith" },
{ "firstName":"Peter", "lastName":"Jones" }
]}
JSON VS XML
JSON is Like XML Because
Both JSON and XML are "self describing" (human readable)
Both JSON and XML are hierarchical (values within values)
Both JSON and XML can be parsed and used by lots of programming languages
Both JSON and XML can be fetched with an XMLHttpRequest
Using JSON
Fetch a JSON string
JSON.Parse the JSON string
REFERENCE
http://www.webstepbook.com/supplements-2ed/slides/lectureXX-
jquery.shtml
https://api.jquery.com
https://www.w3schools.com/jquery/