Classes
Classes Example
Always add a method named constructor() to classes. A JavaScript class is not an object. It is a template for JavaScript objects.
- class Person {
- constructor(name, birthYear) {
- this.name = name;
- this.birthYear = birthYear;
- }
- age(currentYear) {
- return currentYear - this.year;
- }
- }
- -
- class Student extends Person {
- static counter = 0; // Static property
constructor(name, birthYear, id) { - Student.counter += 1
super(name, birthYear); // methods and properties/attributes from parent method can be used in this class
this.id = id;
}
info() { - // year = new Date(); // This will not work
let year = new Date(); // This will work - because classes follow strict mode rules - return 'Name: ' + this.name + ', age: ' + this.age(year) + ', student ID: ' + this.id;
} - -
- // Getters and Setters
- get sname() { // even if the getter is a method, you don't use parentheses when you want to get the property value
return this.name;
}
set sname(x) {
this.name = x;
}
} - -
- // Static method - defined on the class itself. Cannot call a static method on an object, only on an object class.
- static getTotal() {
return "Total Students: " + Student.counter;
} - let date = new Date();
- let year = date.getFullYear();
- let kan = new Person("Kannika", 2023);
- document.getElementById("demo").innerHTML= "Hi, I am " + kan.age(year) + " years old.";
- document.getElementById("demo2").innerHTML= Student.getTotal();
HTTP Services / API (Application Programming Interface) - Endpoints that are accessible via the HTTP protocol
- Sending HTTP requests and receiving HTTP response via API keys and using it to display info on your application
Web API
- A Browser API can extend the functionality of a web browser - (built-in the browser)
- A Server API can extend the functionality of a web server.
- YouTube API - Allows you to display videos on a web site.
- Twitter API - Allows you to display Tweets on a web site.
Validation API
Validation API - validates an input field based on the constraint
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Validation</h2>
<p>Enter a number and click OK:</p>
<input id="id1" type="number" min="100" max="300" required>
<button onclick="myFunction()">OK</button>
<p>If the number is less than 100 or greater than 300, an error message will be displayed.</p>
<p id="demo"></p>
<script>
function myFunction() {
const inpObj = document.getElementById("id1");
if (!inpObj.checkValidity()) {
document.getElementById("demo").innerHTML = inpObj.validationMessage;
} else {
document.getElementById("demo").innerHTML = "Input OK";
}
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Validation</h2>
<p>Enter a number and click OK:</p>
<input id="id1" type="number" min="100" max="300" required>
<button onclick="myFunction()">OK</button>
<p>If the number is less than 100 or greater than 300, an error message will be displayed.</p>
<p id="demo"></p>
<script>
function myFunction() {
const inpObj = document.getElementById("id1");
if (!inpObj.checkValidity()) {
document.getElementById("demo").innerHTML = inpObj.validationMessage;
} else {
document.getElementById("demo").innerHTML = "Input OK";
}
}
</script>
</body>
</html>
Web History API
Web History API
<button onclick="myFunction()">Go Back</button>
<button onclick="myFunction2()">Go Back 2 Pages</button>
<script>
function myFunction() {
window.history.back(); // should only go back 1 page - same as clicking back arrow in browser
}
function myFunction2() {
window.history.go(-2); // goes back 2 pages
}
</script>
Some other methods & property:
<button onclick="myFunction()">Go Back</button>
<button onclick="myFunction2()">Go Back 2 Pages</button>
<script>
function myFunction() {
window.history.back(); // should only go back 1 page - same as clicking back arrow in browser
}
function myFunction2() {
window.history.go(-2); // goes back 2 pages
}
</script>
Some other methods & property:
- forward() - Loads the next URL in the history list
- go() - Loads a specific URL from the history list
- length - (property) Returns the number of URLs in the history list
Web Storage API
Web Storage API - Syntax for storing and retrieving data in the browser
<p id="demo"></p>
<script>
sessionStorage.setItem("name","Asuka Kazama"); // It takes a key and a value as parameters and keeps in storage
document.getElementById("demo").innerHTML = sessionStorage.getItem("name"); // uses key to get the value
</script>
The sessionStorage object is identical to the localStorage object. The difference is that the sessionStorage object stores data for one session. The data is deleted when the browser is closed. The localStorage data is kept forever even after closing browser, unless clear() or removeItem(key) methods are called.
<p id="demo"></p>
<script>
sessionStorage.setItem("name","Asuka Kazama"); // It takes a key and a value as parameters and keeps in storage
document.getElementById("demo").innerHTML = sessionStorage.getItem("name"); // uses key to get the value
</script>
The sessionStorage object is identical to the localStorage object. The difference is that the sessionStorage object stores data for one session. The data is deleted when the browser is closed. The localStorage data is kept forever even after closing browser, unless clear() or removeItem(key) methods are called.
WeB Worker API
Web Worker API - Some JavaScript (file/method) running in the background, without affecting the performance of the page.
When executing scripts in an HTML page, the page becomes unresponsive until the script is finished. But through, Web Worker API, you can continue to do whatever you want: clicking, selecting things, etc., while the web worker runs in the background.
<!DOCTYPE html>
<html>
<body>
<p>Count numbers: <output id="result"></output></p>
<button onclick="startWorker()">Start Worker</button>
<button onclick="stopWorker()">Stop Worker</button>
<script>
let w;
function startWorker() {
if (typeof(w) == "undefined") {
w = new Worker("demo_workers.js"); // Creates a new web worker object
}
w.onmessage = function(event) {
document.getElementById("result").innerHTML = event.data;
};
}
function stopWorker() {
w.terminate(); // terminates web worker once complete
w = undefined;
}
</script>
</body>
</html>
*Note: Normally web workers are not used for such simple scripts, but for more CPU intensive tasks.
When executing scripts in an HTML page, the page becomes unresponsive until the script is finished. But through, Web Worker API, you can continue to do whatever you want: clicking, selecting things, etc., while the web worker runs in the background.
<!DOCTYPE html>
<html>
<body>
<p>Count numbers: <output id="result"></output></p>
<button onclick="startWorker()">Start Worker</button>
<button onclick="stopWorker()">Stop Worker</button>
<script>
let w;
function startWorker() {
if (typeof(w) == "undefined") {
w = new Worker("demo_workers.js"); // Creates a new web worker object
}
w.onmessage = function(event) {
document.getElementById("result").innerHTML = event.data;
};
}
function stopWorker() {
w.terminate(); // terminates web worker once complete
w = undefined;
}
</script>
</body>
</html>
*Note: Normally web workers are not used for such simple scripts, but for more CPU intensive tasks.
Fetch API
Fetch API - allows web browser to make HTTP requests to web servers. No need for XMLHttpRequest anymore.
<!DOCTYPE html>
<html>
<body>
<p id="demo">Fetch a file to change this text.</p>
<script>
getText("fetch_info.txt"); // Calls the function and sends in a file name
async function getText(file) {
let myObject = await fetch(file); // fetches this mentioned file
let myText = await myObject.text(); // reads and stores the text from the file
document.getElementById("demo").innerHTML = myText; // displays the text file in the HTML tag
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<p id="demo">Fetch a file to change this text.</p>
<script>
getText("fetch_info.txt"); // Calls the function and sends in a file name
async function getText(file) {
let myObject = await fetch(file); // fetches this mentioned file
let myText = await myObject.text(); // reads and stores the text from the file
document.getElementById("demo").innerHTML = myText; // displays the text file in the HTML tag
}
</script>
</body>
</html>
Web Geolocation API
Web Geolocation API - The HTML Geolocation API is used to get the geographical position of a user.
<script>
const x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) { // Checks if Geolocation is supported
// run getCurrentPosition() method and return coordinates object to the function specified in the parameter (showPosition)
navigator.geolocation.getCurrentPosition(showPosition);
// watchPosition() - Returns current position and continues to update position as the user moves (like the GPS in a car)
// navigator.geolocation.watchPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
function showPosition2(position) { // Display the position on a map
let latlon = position.coords.latitude + "," + position.coords.longitude; // There are also other coords.property - look them up
let img_url = "https://maps.googleapis.com/maps/api/staticmap?center=
"+latlon+"&zoom=14&size=400x300&sensor=false&key=YOUR_KEY";
document.getElementById("mapholder").innerHTML = "<img src='"+img_url+"'>";
}
</script>
<script>
const x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) { // Checks if Geolocation is supported
// run getCurrentPosition() method and return coordinates object to the function specified in the parameter (showPosition)
navigator.geolocation.getCurrentPosition(showPosition);
// watchPosition() - Returns current position and continues to update position as the user moves (like the GPS in a car)
// navigator.geolocation.watchPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
function showPosition2(position) { // Display the position on a map
let latlon = position.coords.latitude + "," + position.coords.longitude; // There are also other coords.property - look them up
let img_url = "https://maps.googleapis.com/maps/api/staticmap?center=
"+latlon+"&zoom=14&size=400x300&sensor=false&key=YOUR_KEY";
document.getElementById("mapholder").innerHTML = "<img src='"+img_url+"'>";
}
</script>
Ajax
With Ajax (Asynchronous JavaScript And XML), you can:
AJAX just uses a combination of:
How AJAX works:
- Read data from a web server - after the page has loaded
- Update a web page without reloading the page
- Send data to a web server - in the background
AJAX just uses a combination of:
- A browser built-in XMLHttpRequest object (to request data from a web server)
- JavaScript and HTML DOM (to display or use the data)
How AJAX works:
- 1. An event occurs in a web page (the page is loaded, a button is clicked)
- 2. An XMLHttpRequest object is created by JavaScript
- 3. The XMLHttpRequest object sends a request to a web server
- 4. The server processes the request
- 5. The server sends a response back to the web page
- 6. The response is read by JavaScript
- 7. Proper action (like page update) is performed by JavaScript
AJAX xmlhttp
<!DOCTYPE html>
<html>
<body>
<div id="demo">
<h2>The XMLHttpRequest Object</h2>
<button type="button" onclick="loadDoc()">Change Content</button>
</div>
<script>
function loadDoc() {
const xhttp = new XMLHttpRequest(); // 1) Create an XMLHttpRequest object
// 2) Define a callback function - should contain the code to execute when the response is ready
xhttp.onreadystatechange = function() { // The onreadystatechange function is called every time the readyState changes
if (this.readyState == 4 && this.status == 200) { // Check below this code section to understand status codes
document.getElementById("demo").innerHTML =
this.responseText;
}
};
// !Note: both the web page and the XML file it tries to load, must be located on the same server (domain) for security
xhttp.open("GET", "ajax_info.txt"); // 3) Open the XMLHttpRequest object
xhttp.send(); // 4) Send a Request to a server
}
</script>
</body>
</html>
READYSTATE and STATUS CODES
HAVING MULTIPLE CALLBAC FUNCTIONS FOR MANY AJAX TASKS ON A WEBSITE
loadDoc("url-1", myFunction1);
loadDoc("url-2", myFunction2);
function loadDoc(url, cFunction) {
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {cFunction(this);}
xhttp.open("GET", url);
xhttp.send();
}
function myFunction1(xhttp) {
// action goes here
}
function myFunction2(xhttp) {
// action goes here
}
<html>
<body>
<div id="demo">
<h2>The XMLHttpRequest Object</h2>
<button type="button" onclick="loadDoc()">Change Content</button>
</div>
<script>
function loadDoc() {
const xhttp = new XMLHttpRequest(); // 1) Create an XMLHttpRequest object
// 2) Define a callback function - should contain the code to execute when the response is ready
xhttp.onreadystatechange = function() { // The onreadystatechange function is called every time the readyState changes
if (this.readyState == 4 && this.status == 200) { // Check below this code section to understand status codes
document.getElementById("demo").innerHTML =
this.responseText;
}
};
// !Note: both the web page and the XML file it tries to load, must be located on the same server (domain) for security
xhttp.open("GET", "ajax_info.txt"); // 3) Open the XMLHttpRequest object
xhttp.send(); // 4) Send a Request to a server
}
</script>
</body>
</html>
READYSTATE and STATUS CODES
- readyState Holds the status of the XMLHttpRequest.
- 0: request not initialized
- 1: server connection established
- 2: request received
- 3: processing request
- 4: request finished and response is ready
- status
- 200: "OK"
- 403: "Forbidden"
- 404: "Page not found"
HAVING MULTIPLE CALLBAC FUNCTIONS FOR MANY AJAX TASKS ON A WEBSITE
loadDoc("url-1", myFunction1);
loadDoc("url-2", myFunction2);
function loadDoc(url, cFunction) {
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {cFunction(this);}
xhttp.open("GET", url);
xhttp.send();
}
function myFunction1(xhttp) {
// action goes here
}
function myFunction2(xhttp) {
// action goes here
}
Handling xhttp requests in AJAX
Ajax Requests & Response
GET Request
xhttp.open("GET", "demo_get.asp?t=" + Math.random()); // To avoid getting a cached result, add a unique id
xhttp.open("GET", "demo_get2.asp?fname=Kannika&lname=Kabilar"); // Add info to the url to send info with the GET method
xhttp.send();
POST Request
/* To POST data like an HTML form, add an HTTP header with setRequestHeader(). Specify the data you want to send in the send() method */
xhttp.open("POST", "ajax_test.asp");
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("fname=Kannika&lname=Kabilar");
AJAX Response
<script>
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
document.getElementById("demo").innerHTML =
this.getAllResponseHeaders(); // returns all header information from the server response
}
xhttp.open("GET", "ajax_info.txt");
xhttp.send();
</script>
<script>
const xhttp=new XMLHttpRequest();
xhttp.onload = function() {
document.getElementById("demo").innerHTML =
this.getResponseHeader("Last-modified"); // get the specific info that we're looking for
}
xhttp.open("GET", "ajax_info.txt");
xhttp.send();
</script>
xhttp.open("GET", "demo_get.asp?t=" + Math.random()); // To avoid getting a cached result, add a unique id
xhttp.open("GET", "demo_get2.asp?fname=Kannika&lname=Kabilar"); // Add info to the url to send info with the GET method
xhttp.send();
POST Request
/* To POST data like an HTML form, add an HTTP header with setRequestHeader(). Specify the data you want to send in the send() method */
xhttp.open("POST", "ajax_test.asp");
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("fname=Kannika&lname=Kabilar");
AJAX Response
- Example 1
<script>
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
document.getElementById("demo").innerHTML =
this.getAllResponseHeaders(); // returns all header information from the server response
}
xhttp.open("GET", "ajax_info.txt");
xhttp.send();
</script>
- Output:
- Example 2
<script>
const xhttp=new XMLHttpRequest();
xhttp.onload = function() {
document.getElementById("demo").innerHTML =
this.getResponseHeader("Last-modified"); // get the specific info that we're looking for
}
xhttp.open("GET", "ajax_info.txt");
xhttp.send();
</script>
- Output:
Using AJAX to access data from an XML file
Ajax XML
<script> const xhttp = new XMLHttpRequest(); xhttp.onload = function() { const xmlDoc = this.responseXML; // Gets all text in the ARTIST tag const x = xmlDoc.getElementsByTagName("ARTIST"); let txt = ""; for (let i = 0; i < x.length; i++) { txt = txt + x[i].childNodes[0].nodeValue + "<br>"; } document.getElementById("demo").innerHTML = txt; } xhttp.open("GET", "cd_catalog.xml"); xhttp.send(); </script>
Bonnie Tyler Dolly Parton |
<CD> <TITLE>Empire Burlesque</TITLE> <ARTIST>Bob Dylan</ARTIST> <COUNTRY>USA</COUNTRY> <COMPANY>Columbia</COMPANY> <PRICE>10.90</PRICE> <YEAR>1985</YEAR> </CD> <CD> <TITLE>Hide your heart</TITLE> <ARTIST>Bonnie Tyler</ARTIST> <COUNTRY>UK</COUNTRY> <COMPANY>CBS Records</COMPANY> <PRICE>9.90</PRICE> <YEAR>1988</YEAR> </CD> <CD> <TITLE>Greatest Hits</TITLE> <ARTIST>Dolly Parton</ARTIST> <COUNTRY>USA</COUNTRY> <COMPANY>RCA</COMPANY> <PRICE>9.90</PRICE> <YEAR>1982</YEAR> </CD> </CATALOG> |
<br><br> <table id="demo"></table> <script> function loadDoc() { const xhttp = new XMLHttpRequest(); xhttp.onload = function() { myFunction(this); } xhttp.open("GET", "cd_catalog.xml"); xhttp.send(); } function myFunction(xml) { const xmlDoc = xml.responseXML; const x = xmlDoc.getElementsByTagName("CD"); let table="<tr><th>Artist</th><th>Title</th></tr>"; for (let i = 0; i <x.length; i++) { table += "<tr><td>" + x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue + "</td><td>" + x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue + "</td></tr>"; } document.getElementById("demo").innerHTML = table; } </script> |
Bob Dylan Empire Burlesque Bonnie Tyler Hide your heart Dolly Parton Greatest Hits |
AJAX w/ PHP or ASP - Helps in creating a more interactive application
AJAX W/ PHP & ASP
<h3>Start typing a name in the input field below:</h3>
<p>Suggestions: <span id="txtHint"></span></p>
<p>First name: <input type="text" id="txt1" onkeyup="showHint(this.value)"></p>
<script>
function showHint(str) {
if (str.length == 0) { // Check if input field empty => clear the content of the txtHint placeholder and exit the function
document.getElementById("txtHint").innerHTML = "";
return;
}
const xhttp = new XMLHttpRequest(); // Create an XMLHttpRequest object
xhttp.onload = function() { // Create the function to be executed when the server response is ready
document.getElementById("txtHint").innerHTML =
this.responseText;
}
xhttp.open("GET", "gethint.php?q="+str); // q parameter is added gethint.php?q="+str and str contains text of input field
// xhttp.open("GET", "gethint.asp?q="+str); // The same as above but with asp file
xhttp.send(); // Send the request off to a PHP file (gethint.php) on the server
}
</script>
<p>Suggestions: <span id="txtHint"></span></p>
<p>First name: <input type="text" id="txt1" onkeyup="showHint(this.value)"></p>
<script>
function showHint(str) {
if (str.length == 0) { // Check if input field empty => clear the content of the txtHint placeholder and exit the function
document.getElementById("txtHint").innerHTML = "";
return;
}
const xhttp = new XMLHttpRequest(); // Create an XMLHttpRequest object
xhttp.onload = function() { // Create the function to be executed when the server response is ready
document.getElementById("txtHint").innerHTML =
this.responseText;
}
xhttp.open("GET", "gethint.php?q="+str); // q parameter is added gethint.php?q="+str and str contains text of input field
// xhttp.open("GET", "gethint.asp?q="+str); // The same as above but with asp file
xhttp.send(); // Send the request off to a PHP file (gethint.php) on the server
}
</script>
// Array with names $a[] = "Anna"; $a[] = "Kitty"; $a[] = "Linda"; $a[] = "Nina"; $a[] = "Doris"; $a[] = "Eve"; $a[] = "Evita"; $a[] = "Sunniva"; $a[] = "Tove"; $a[] = "Unni"; $a[] = "Violet"; $a[] = "Liza"; $a[] = "Elizabeth"; $a[] = "Ellen"; $a[] = "Wenche"; $a[] = "Vicky"; // get the q parameter from URL $q = $_REQUEST["q"]; $hint = ""; // lookup all hints from array if $q is different from "" if ($q !== "") { $q = strtolower($q); $len=strlen($q); foreach($a as $name) { if (stristr($q, substr($name, 0, $len))) { if ($hint === "") { $hint = $name; } else { $hint .= ", $name"; } } } } // Output "no suggestion" if no hint was found or output correct values echo $hint === "" ? "no suggestion" : $hint; ?> |
response.expires=-1 dim a(16) 'Fill up array with names a(1)="Anna" a(2)="Kitty" a(3)="Linda" a(4)="Nina" a(5)="Doris" a(6)="Eve" a(7)="Evita" a(8)="Sunniva" a(9)="Tove" a(10)="Unni" a(11)="Violet" a(12)="Liza" a(13)="Elizabeth" a(14)="Ellen" a(15)="Wenche" a(16)="Vicky" 'get the q parameter from URL q=ucase(request.querystring("q")) 'lookup all hints from array if length of q>0 if len(q)>0 then hint="" for i=1 to 30 if q=ucase(mid(a(i),1,len(q))) then if hint="" then hint=a(i) else hint=hint & " , " & a(i) end if end if next end if 'Output "no suggestion" if no hint were found 'or output the correct values if hint="" then response.write("no suggestion") else response.write(hint) end if %> |
AJAX Connecting to Database - AJAX can be used for interactive communication with a database
Ajax connecting to Database
<!DOCTYPE html>
<html>
<style>
th,td {
padding: 5px;
}
</style>
<body>
<h2>The XMLHttpRequest Object</h2>
<form action="">
<select name="customers" onchange="showCustomer(this.value)">
<!-- Following are the customer options available to be selected -->
<option value="">Select a customer:</option>
<option value="ALFKI">Alfreds Futterkiste</option>
<option value="NORTS ">North/South</option>
<option value="WOLZA">Wolski Zajazd</option>
</select>
</form>
<br>
<div id="txtHint">Customer info will be listed here... (The results will be displayed in this tag)</div>
<script>
function showCustomer(str) {
if (str == "") { // Check if a customer option is selected
document.getElementById("txtHint").innerHTML = "";
return;
}
const xhttp = new XMLHttpRequest(); // Create an XMLHttpRequest object
xhttp.onload = function() { // Create the function to be executed when the server response is read
document.getElementById("txtHint").innerHTML = this.responseText;
}
// Send the request off to a file on the server: *the file handles how to query data from database and display result
xhttp.open("GET", "getcustomer.php?q="+str);
xhttp.send();
}
</script>
</body>
</html>
<html>
<style>
th,td {
padding: 5px;
}
</style>
<body>
<h2>The XMLHttpRequest Object</h2>
<form action="">
<select name="customers" onchange="showCustomer(this.value)">
<!-- Following are the customer options available to be selected -->
<option value="">Select a customer:</option>
<option value="ALFKI">Alfreds Futterkiste</option>
<option value="NORTS ">North/South</option>
<option value="WOLZA">Wolski Zajazd</option>
</select>
</form>
<br>
<div id="txtHint">Customer info will be listed here... (The results will be displayed in this tag)</div>
<script>
function showCustomer(str) {
if (str == "") { // Check if a customer option is selected
document.getElementById("txtHint").innerHTML = "";
return;
}
const xhttp = new XMLHttpRequest(); // Create an XMLHttpRequest object
xhttp.onload = function() { // Create the function to be executed when the server response is read
document.getElementById("txtHint").innerHTML = this.responseText;
}
// Send the request off to a file on the server: *the file handles how to query data from database and display result
xhttp.open("GET", "getcustomer.php?q="+str);
xhttp.send();
}
</script>
</body>
</html>
- getcustomer.php
$mysqli = new mysqli("servername", "username", "password", "dbname");
if($mysqli->connect_error) {
exit('Could not connect');
}
$sql = "SELECT customerid, companyname, contactname, address, city, postalcode, country
FROM customers WHERE customerid = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s", $_GET['q']);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($cid, $cname, $name, $adr, $city, $pcode, $country);
$stmt->fetch();
$stmt->close();
echo "<table>";
echo "<tr>";
echo "<th>CustomerID</th>";
echo "<td>" . $cid . "</td>";
echo "<th>CompanyName</th>";
echo "<td>" . $cname . "</td>";
echo "<th>ContactName</th>";
echo "<td>" . $name . "</td>";
echo "<th>Address</th>";
echo "<td>" . $adr . "</td>";
echo "<th>City</th>";
echo "<td>" . $city . "</td>";
echo "<th>PostalCode</th>";
echo "<td>" . $pcode . "</td>";
echo "<th>Country</th>";
echo "<td>" . $country . "</td>";
echo "</tr>";
echo "</table>";
?>
JSON
JSON (JavaScript Object Notation) is a format for storing and transporting data especially when sending from a server to a web page. JSON makes it possible to store JavaScript objects as text.
*Language Independent: The JSON syntax is derived from JavaScript object notation syntax, but the JSON format is text only. Code for reading and generating JSON data can be written in any programming language.
Syntax Rules:
"employees":[
{"firstName":"Steve", "lastName":"Fox"},
{"firstName":"Anna", "lastName":"Williams"},
{"firstName":"Julia", "lastName":"Chang"}
]
*Language Independent: The JSON syntax is derived from JavaScript object notation syntax, but the JSON format is text only. Code for reading and generating JSON data can be written in any programming language.
Syntax Rules:
- Data is in name/value pairs
- Data is separated by commas
- Curly braces hold objects
- Square brackets hold arrays
- Example: - object employees is an array and it contains 3 person object
"employees":[
{"firstName":"Steve", "lastName":"Fox"},
{"firstName":"Anna", "lastName":"Williams"},
{"firstName":"Julia", "lastName":"Chang"}
]
Converting JSON String to JAvaScript
- Converting JSON String to JavaScript
<script>
// jsonText contains a string of how objects are stored in JSON
let jsonText = '{"employees":[' +
'{"firstName":"Steve","lastName":"Fox" },' +
'{"firstName":"Anna","lastName":"Williams" },' +
'{"firstName":"Julia","lastName":"Chang" }]}';
const obj = JSON.parse(jsonText); // Convert the json formatted string into a JavaScript object
document.getElementById("demo").innerHTML =
obj.employees[1].firstName + " " + obj.employees[1].lastName;
</script>
- JSON.parse() - JavaScript's built in function for converting JSON strings into JavaScript objects
- // parse is used when receiving data from a web server
- JSON.stringify() - JavaScript's built in function for converting an object into a JSON string
- // stringify is used when sending data to a web server to be stored
JSON values cannot be: function, date, undefined ; but it can be string, number, object, array ...
JSON and XML are kinda similar. But JSON can use arrays and it much easier to parse than XML
Using JSON and AJAX, JavaScript objects/values can be converted into a JSON string and sent through a xhttp GET request to another JavaScript file - and this other JavaScript file can parse the JSON string to retrieve the stored JavaScript object/value for its own use.
Exchanging Data Between a Client and a PHP Server. PHP has some built-in functions to handle JSON.
JSON PHP
$myObj->name = "Kannika"; $myObj->age = 17; $myObj->city = "New York"; $myJSON = json_encode($myObj); echo $myJSON; ?>
|
<script> const xmlhttp = new XMLHttpRequest(); xmlhttp.onload = function() { const myObj = JSON.parse(this.responseText); document.getElementById("demo").innerHTML = myObj.name; } xmlhttp.open("GET", "demo_file.php"); xmlhttp.send(); </script>
|
Similarly PHP can send over arrays through JSON
$myArr = array("Asuka", "Julia", "Zafina", "Nina"); $myJSON = json_encode($myArr); echo $myJSON; ?>
|
xmlhttp.onload = function() { const myObj = JSON.parse(this.responseText); document.getElementById("demo").innerHTML = myObj[2]; } xmlhttp.open("GET", "demo_file_array.php", true); xmlhttp.send(); |
PHP is a server side programming language, and can be used to access a database.
When sending data to the server, it is often best to use the HTTP POST method. To send AJAX requests using the POST method, specify the method, and the correct header. The data sent to the server must now be an argument to the send() method.
When sending data to the server, it is often best to use the HTTP POST method. To send AJAX requests using the POST method, specify the method, and the correct header. The data sent to the server must now be an argument to the send() method.
header("Content-Type: application/json; charset=UTF-8"); // Get obj from JSON which contains limit property $obj = json_decode($_POST["x"], false); // Connect to DB $conn = new mysqli("myServer", "myUser", "myPassword", "Northwind"); $stmt = $conn->prepare("SELECT name FROM customers LIMIT ?"); // execute query with value received from client $stmt->bind_param("s", $obj->limit); $stmt->execute(); $result = $stmt->get_result(); $outp = $result->fetch_all(MYSQLI_ASSOC); echo json_encode($outp); ?>
|
// Sending 10 to fetch 10 records from db const dbParam = JSON.stringify({"limit":10}); const xmlhttp = new XMLHttpRequest(); xmlhttp.onload = function() { myObj = JSON.parse(this.responseText); let text = ""; // For each obj, only print out the name for (let x in myObj) { text += myObj[x].name + "<br>"; } document.getElementById("demo").innerHTML = text; } xmlhttp.open("POST", "json_demo_db_post.php"); // Modify header accordingly xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); // specifying param in send method for POST request xmlhttp.send("x=" + dbParam); </script> |
JSONP (JSON with Padding)
JSONP is a method for sending JSON data without worrying about cross-domain issues. Requesting a file from another domain can cause problems, due to cross-domain policy but requesting an external script from another domain does not have this problem. JSONP uses this advantage, and request files using the <script> tag instead of the XMLHttpRequest object.
JSONP is a method for sending JSON data without worrying about cross-domain issues. Requesting a file from another domain can cause problems, due to cross-domain policy but requesting an external script from another domain does not have this problem. JSONP uses this advantage, and request files using the <script> tag instead of the XMLHttpRequest object.
JSONP Examples
Example 1
$myJSON = '{ "name":"Kannika", "age":17, "city":"New York" }'; // returns a call to a function named "myFunc" with the JSON data as a parameter echo "myFunc(".$myJSON.");"; ?>
|
<script> function myFunc(myObj) { document.getElementById("demo").innerHTML = myObj.name; } </script> <script src="demo_jsonp.php"></script> |
Example 2
header("Content-Type: application/json; charset=UTF-8"); $obj = json_decode($_GET["x"], false); // Connect to DB and execute query $conn = new mysqli("myServer", "myUser", "myPassword", "Northwind"); $result = $conn->query("SELECT name FROM ".$obj->$table." LIMIT ".$obj->$limit); /* Access the database, and fill an array with the requested data */ $outp = array(); $outp = $result->fetch_all(MYSQLI_ASSOC); // call myFunc with encoding array into JSON echo "myFunc(".json_encode($outp).")"; ?>
|
<script> const obj = { table: "customers", limit: 10 }; let s = document.createElement("script"); s.src = "jsonp_demo_db.php?x=" + JSON.stringify(obj); document.body.appendChild(s); /* Below comment code line sends callback function name of which function should be executed when returned back from server */ // s.src = "jsonp_demo_db.php?callback=myOtherFunction"; function myFunc(myObj) { let txt = ""; for (let x in myObj) { txt += myObj[x].name + "<br>"; } document.getElementById("demo").innerHTML = txt; } </script> |
jQuery
jQuery is a javascript library but most of its utilities can be solved with a few lines of standard JavaScript. With jQuery you select (query) HTML elements and perform "actions" on them.
JavaScript |
jQuery |
myElement = document.getElementById("id01"); |
myElement = $("#id01"); |
myElements = document.getElementsByTagName("p"); |
myElements = $("p"); // Return all <p> elements |
myElements = document.querySelectorAll("p.intro"); |
myElements = $("p.intro"); // Return a list of all <p> elements with class="intro" |
But still there are more where jQuery can help simplify JavaScript. jQuery can be added to your web page through 2 ways:
- Download the jQuery library from jQuery.com
- <head><script src="jquery-3.6.1.min.js"></script></head>
- Note: The downloaded file should be in the same directory
- Include jQuery from a CDN (Content Delivery Network), like Google
- <head><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script></head>
Simple Example
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("p").click(function(){
$(this).hide();
});
});
</script>
<p>If you click on me, I will disappear.</p>
<p>Click me away! I will disappear too because I am a 'p' tag</p>
<p>Click me too! </p>
<script>
$(document).ready(function(){
$("p").click(function(){
$(this).hide();
});
});
</script>
<p>If you click on me, I will disappear.</p>
<p>Click me away! I will disappear too because I am a 'p' tag</p>
<p>Click me too! </p>
jQuery can:
- be used to manipulate (set/get value of) HTML elements and its CSS
- traverse/filter through HTML elements within each other (example not added here)
- be used with AJAX to perform GET and POST requests (example not added here)
- use noConflict() method so that other JS frameworks (ie: Angular) can also be used w/ jQuery
Very Cool Accordion Example w/ jQuery
Very Cool Accordion Example w/ jQuery
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideToggle("slow");
});
});
</script>
<style>
#panel, #flip {
padding: 5px;
text-align: center;
background-color: #e5eecc;
border: solid 1px #c3c3c3;
}
#panel {
padding: 50px;
display: none;
}
</style>
</head>
<body>
<div id="flip">Click to slide the panel down or up</div>
<div id="panel">Hello world!</div>
<div>Hi Kan</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideToggle("slow");
});
});
</script>
<style>
#panel, #flip {
padding: 5px;
text-align: center;
background-color: #e5eecc;
border: solid 1px #c3c3c3;
}
#panel {
padding: 50px;
display: none;
}
</style>
</head>
<body>
<div id="flip">Click to slide the panel down or up</div>
<div id="panel">Hello world!</div>
<div>Hi Kan</div>
</body>
</html>
Animating w/ jQuery (Very Cool!)
Animating w/ jQuery (Very Cool!)
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
var div = $("div");
div.animate({height: '300px', opacity: '0.4'}, "slow");
div.animate({width: '300px', opacity: '0.8'}, "slow");
div.animate({height: '100px', opacity: '0.4'}, "slow");
div.animate({width: '100px', opacity: '0.8'}, "slow");
div.animate({left: '100px'}, "slow");
div.animate({height: '80px'}, "slow");
div.animate({width: '110px'}, "slow");
div.animate({fontSize: '3.4em'}, "slow");
});
});
</script>
</head>
<body>
<button>Start Animation</button>
<p>By default, all HTML elements have a static position, and cannot be moved. To manipulate the position, remember to first set the CSS position property of the element to relative, fixed, or absolute!</p>
<div style="background:#f0d1ff;height:100px;width:100px;position:absolute;text-align:center;color:#0015ff">KK</div>
</body>
</html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
var div = $("div");
div.animate({height: '300px', opacity: '0.4'}, "slow");
div.animate({width: '300px', opacity: '0.8'}, "slow");
div.animate({height: '100px', opacity: '0.4'}, "slow");
div.animate({width: '100px', opacity: '0.8'}, "slow");
div.animate({left: '100px'}, "slow");
div.animate({height: '80px'}, "slow");
div.animate({width: '110px'}, "slow");
div.animate({fontSize: '3.4em'}, "slow");
});
});
</script>
</head>
<body>
<button>Start Animation</button>
<p>By default, all HTML elements have a static position, and cannot be moved. To manipulate the position, remember to first set the CSS position property of the element to relative, fixed, or absolute!</p>
<div style="background:#f0d1ff;height:100px;width:100px;position:absolute;text-align:center;color:#0015ff">KK</div>
</body>
</html>
Search bar in jquery
Filtering w/ jQuery
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#myInput").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#myList li").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
</script>
</head>
<body>
<h2>Filterable List</h2>
<p>Type something in the input field to search the list for specific items:</p>
<input id="myInput" type="text" placeholder="Search...">
<br>
<ul id="myList">
<li>First item</li>
<li>Second item</li>
<li>Third item</li>
<li>Fourth</li>
</ul>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#myInput").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#myList li").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
</script>
</head>
<body>
<h2>Filterable List</h2>
<p>Type something in the input field to search the list for specific items:</p>
<input id="myInput" type="text" placeholder="Search...">
<br>
<ul id="myList">
<li>First item</li>
<li>Second item</li>
<li>Third item</li>
<li>Fourth</li>
</ul>
</body>
</html>
HTML DOM
HTML DOM (Document Object Model) defines:
For Ex: -(getElementById is a method, while innerHTML is a property)
- The HTML elements as objects
- The properties of all HTML elements => change the content (text) and style (CSS) of HTML elements
- The methods to access all HTML elements => act when there's HTML DOM events => (event handler)
- The events for all HTML elements => add and delete HTML elements
For Ex: -(getElementById is a method, while innerHTML is a property)
- <html><body>
- <p id="demo"></p>
- <script>
- document.getElementById("demo").innerHTML = "Hello World!";
- </script>
- </body></html>
Some HTML Dom examples - (changing Attribute val, FORM VALIDATION, changing CSs, Animation)
Changing the Value of an Attribute Ex
- <!DOCTYPE html>
- <html><body>
- <img id="myImage" src="smiley.gif">
- <script>
- document.getElementById("myImage").src = "landscape.jpg";
- </script>
- </body></html>
-
Form Validation
- <!DOCTYPE html>
- <html><head>
- <script>
- function validateForm() {
- let x = document.forms["myForm"]["fname"].value;
- if (x == "") {
- alert("Name must be filled out");
- return false;
- }
- }
- </script>
- </head><body>
- <h2>JavaScript Validation</h2>
- <form name="myForm" action="/action_page.php" onsubmit="return validateForm()" method="post">
- Name: <input type="text" name="fname">
- <input type="submit" value="Submit">
- </form>
- </body></html>
-
Changing CSS
- <!DOCTYPE html>
- <html><body>
- <h1 id="id1">My Heading 1</h1>
- <button type="button" onclick="document.getElementById('id1').style.color = 'red'"> Click Me! </button>
- </body></html>
-
Animation Ex
- <!DOCTYPE html><html>
- <style>
- #container {
- width: 400px;
- height: 400px;
- position: relative;
- background: yellow;
- }
- #animate {
- width: 50px;
- height: 50px;
- position: absolute;
- background-color: red;
- }
- </style>
- <body>
- <p><button onclick="myMove()">Click Me</button></p>
- <div id ="container">
- <div id ="animate"></div>
- </div>
- <script>
- function myMove() {
- let id = null;
- const elem = document.getElementById("animate");
- let pos = 0;
- clearInterval(id);
- id = setInterval(frame, 5);
- function frame() {
- if (pos == 350) {
- clearInterval(id);
- } else {
- pos++;
- elem.style.top = pos + "px";
- elem.style.left = pos + "px";
- }
- }
- }
- </script>
- </body></html>
Browser BOM defines working with :
JS can be used to provide: graphics, canvas, plotly, chart/google chart, D3
- window methods. for ex:
- window.open() - open a new window
- window.resizeTo() - resize the current window
- let w = window.innerWidth;
- screen methods
- location methods
- history methods
- navigator methods
- popup methods
- timing methods
- cookie methods
JS can be used to provide: graphics, canvas, plotly, chart/google chart, D3