The Javascript Language

and ECMAScript

History

  • Designed in 10 days in 1995
  • By Brendan Eich, who later co-founded Mozilla
  • For Netscape Navigator web browser
  • In all browsers
  • Very popular as server-side language

Data and Types

Variable Declarations

  • no declaration
    • Not recommended
  • var
    • Global or function scoped variable; Warning! See hoisting
  • let
    • Block scoped variable; ES6
    • "Let is the new Var"
  • const
    • Block scoped constant, ES6
  • Variables do not have a type
  • No type checking, can reassign to different types
  • Could even re-declare some variables
  • Object types are references

Primitive Data Types

  • Number (64 bit floating point)
  • String (16 bit Unicode)
  • Boolean
  • BigInt
  • Symbol
  • undefined
  • null (sort of)

Structural Types

  • Object
  • Function

Built-in Object Types

  • Object
  • Array, Map, Set, WeakMap, WeakSet, ArrayBuffer, ...
  • Date
  • RegExp
  • Error
  • JSON
  • ... 
  • More information

Other Objects Provided by

  • Window object (in all browsers)
  • Node.js (on the server)
  • Other runtimes, libraries

Examples

var a;    // a is undefined
a = 20;

var b = 420;
let c = 6.022e23;
const PI = 3.14159      // semicolons are optional
                        // but you should use them

// e is hoisted to the top 


     


let hi;     // initialization is optional
carName = "Volvo";   
let carName; // produces ReferenceError

carName = "Volvo";   
const carName; // this code will not run

// null acts as 0 or false
let myObject = null;
e = 5; // Assign 5 to e
elem = document.getElementById("main"); // Find an element
elem.innerHTML = e;                     // Display e in the element
var e; // Declare e
/* variables as references */
var x = 45;
x = "forty-five";
x = /ab*c/;
x = ['Apple','Banana','Orange'];

console.log("Type of x is " + typeof x);
/* Unicode strings, immutable */
let firstName = "Dorothy";
let lastName = 'Din\u0BD0y'; //Din  y
let someʘther = "I see you";
let combined = firstName + lastName;

let x = 2, y = 4;
let template = `The sum is ${x+y}`;
console.log(template);

/* Boolean */
let ok = true;
/* Objects have properties and "methods" */
let car = {
    doors: 4,
    make: "Tesla",
    model: "Model 3",
    drive: function() { console.log("Driving my " + this.make); } 
};
/*Functions are first class objects */

let obj1 = { id: 2394340, name: "Bob", aliases: ["Robert","Jake"] };
let obj2 = {};
obj2.name = "Carol"; 
obj2["age"] = 5;

let obj3 = new Object();
/* Objects have properties and "methods" */
let car = {
    doors: 4,
    make: "Tesla",
    model: "Model 3",
    drive: function() { console.log("Driving my " + this.make); } 
};
/*Functions are first class objects -> car.drive()*/

let obj1 = { id: 2394340, name: "Bob", aliases: ["Robert","Jake"] };
let obj2 = {};
obj2.name = "Carol"; 
obj2["age"] = 5;

let obj3 = new Object();
// Array -- variable length, heterogenous list
let colors = ["Red", "Orange", "Yellow"];
let sizes = ["Small", "Medium", 27];
let x = colors[0];
let y = colors[55];  //undefined(not range checked)
console.log("Num sizes = " + sizes.length); // Date let now = new Date(); // Math let num = Math.random(); // RegExp let patt = /#[a-fA-F0-9]{6}/
// Remember Javascript is dynamic and allows first //class functions
							
// Function 
let adder = new Function("a","b","return a + b");
let ans = adder(4,7);

Expressions and operators

Expressions and Operators

Note:

  • the "in" operator
  • strict equal and strict not equal
  • Lack of integer division

Control Structures

Very standard Java, C, C++ like

for(let i = 0; i < 5; i++)
{
    if(i % 2 == 0)
    {
        console.log(`${i} is even`);
    }
    else
    {
        console.log(`${i} is odd`);
    }
}

And of course

  • while
  • do-while
  • break and continue
  • switch-case
  • try-catch-finally, throw

for - in

/*Iterate over enumerable properties */
let person = { id: 2394340, name: "Bob", aliases: ["Robert","Jake"] };
for(let i in person)
{
    console.log(i);         //returns properties
    console.log(person[i]); //returns values
}

/*First statement produces:
id
name
aliases
 Second statement produces:
2394340
Bob
Robert Jake  
*/

for - of

/*Iterate over an iterable object (Array, Set, Map, ...)*/
let colors = ["Red", "Orange", "Yellow"];
for(let i of colors)
{
    console.log(i);
}

/*Produces:
Red
Orange
Yellow
*/

Arrays also have

.forEach()

let colors = ["Red", "Orange", "Yellow"];
colors.forEach(c => console.log(c));

/*Produces:
Red
Orange
Yellow
*/

No type checking and implicit type coercion

1 == "1"      // true
1 == "2"      // false
0 == false    // true
3 === 3       // true   (true if operands are equal and of the same type)
3 === "3"     // false  ("strict equality" operator)

if(4)
    console.log("Yup");
let price = 101.0;
let tax = "0.04";

let taxAmt = price * tax;
console.log("Total tax is $" + taxAmt);

// Total tax is $4.04

let A = 5, B = "20";
console.log("A + B = " + (A + B));
console.log("B + A = " + (B + A));

/*
A + B = 520
B + A = 205
*/
If Type(lprim) is String or Type(rprim) is String, then
     Return the String that is the result of concatenating 
     ToString(lprim) followed by ToString(rprim)

Functions/Methods

  • Primitives are passed by value (e.g. number, boolean and string)
  • Objects are passed as a copy of the reference
  • If a function is declared inside an object, then it's a method. "this" is then a reference to the enclosing object
  • Functions can be declared inside other functions, enabling closures
  • Functions are first-class objects

Function Patterns

Plain old function

// example from rosettacode.org
function insertionSort (a) {
    for (let i = 0; i < a.length; i++) {
        let k = a[i];
        for (var j = i; j > 0 && k < a[j - 1]; j--) {
            a[j] = a[j - 1];
        }
        a[j] = k;
    }
    return a;
}
    
let b = [...Array(8)].map(() => Math.floor((Math.random()-0.5) * 100))
console.log(b.join(","));
insertionSort(b);
console.log(b.join(","));

Function expression (anonymous function) &
Arrow function

let cube = function(x) { return x**3; };

let pow = (x,n) => x**n;

console.log(cube(7));
console.log(pow(7,2));
button.addEventListener('click',function(event)
                        {console.log('button is clicked!')}) 
//Basic Syntax Arrow Functions

param => expression

(param1, paramN) => expression

param => {
  let a = 1;
  return a + param;
}

(param1, paramN) => {
   let a = 1;
   return a + param1 + paramN;
}
// Traditional Function
function (a){
  return a + 100;
}
// Arrow Function Break Down
//1. Remove the word "function" and place arrow between the argument and opening body bracket
(a) => {
  return a + 100;
}
// 2. Remove the body brackets and word "return" -- the return is implied.
(a) => a + 100;
// 3. Remove the argument parentheses
a => a + 100;

Immediately invoked function expression (IIFE or "iffy")

// Self-Executing Anonymous Function, runs as soon as defined

let area = (function(w,h) {
    return w * h; 
}(5,2));

console.log(area);
​area; /* 10 */ /* Pattern is: (function () { statements })(); or (() => {statements})() */

IIFE

  • Variables in function have function scope (even var)
  • So wrap code in an IIFE to prevent polluting global scope names
  • Very common idiom
  • Largely (to-be) replaced by ES 6 blocks

// ES6
{
    statements
}
                        

Lot's more

  • How to define your own Object "types"
  • Using Promises for asynchronous work
  • Iterators and generators
  • Strict mode
  • JQuery Video Tutorial

Javascript in the Browser

Browser Object Model

Window object has:

  • Document (DOM)
  • History
  • Location
  • Screen
  • Storage
  • Console
  • GlobalEventHandlers
  • ...

Run in browsers dev tools console

let dim = [window.screen.width, window.screen.height];
window.console.log("Your screen is set to " + dim);

console.log("This window could go back " + (window.history.length - 1) + " pages");

window.onload = function() {console.log("Your DOM is ready!");}

window.onmousedown = function() {console.log("hi");};

Accessing Elements

// Select individual elements
let node = document.getElementById("mainContent");
node     = document.querySelector("div.questions");

// Select multiple elements (returns a NodeList collection object)
let nodes = document.querySelectorAll("div.row");
nodes     = document.getElementsByClassName("row");
nodes     = document.getElementsByTagName("li");

// Traverse let node2 = node.parentNode;
node2     = node.previousSibling;
node2     = node.nextSibling;
node2     = node.firstChild;
node2     = node.lastChild;

Modifying Elements

// Set class attribute
let node = document.getElementById("mainContent");
node.className = "big";

// Access text only
console.log(node.textContent);

// Change the contents of an element
node.innerHTML = "Some <em>good</em> stuff here!";

// Get/Set an attribute value
let nodes = document.getElementsByTagName("a");
nodes[0].getAttribute("href");

/* See also: hasAttribute(), removeAttribute(), setAttribute() and the id property */
The h2 at the top has id="me"

Adding Elements

// Add a new list item
let newItem = document.createElement("li");
let newText = document.createTextNode("Product Name Here");
newItem.appendChild(newText);

let listNode = document.querySelector("ul#products");
listNode.appendChild(newItem);

/* See also: removeChild() */
This section element has id="ae"

Events

function validateUsername(fld) {
    var error = "";
    var illegalChars = /\W/; // allow letters, numbers, and underscores
 
    if (fld.value == "") {
        fld.style.background = 'Yellow';
        error = "You didn't enter a username.\n";
        alert(error);
        return false;
 
    } else if ((fld.value.length < 5) || (fld.value.length > 15)) {
        fld.style.background = 'Yellow';
        error = "The username is the wrong length.\n";
		alert(error);
		return false;
 
    } else if (illegalChars.test(fld.value)) {
        fld.style.background = 'Yellow';
        error = "The username contains illegal characters.\n";
		alert(error);
		return false;
 
    } else {
        fld.style.background = 'White';
    }
    return true;
}

Events

Javascript can

  • Create new content
  • Modify or remove content
  • Get context information: location, history, cookies, ...
  • Make and respond to requests from servers
  • Draw, animate, create games...
  • ...

jQuery

A DOM manipulation library

  • Easier to access elements (re-using CSS Selectors)
  • Uses a productive programming style
  • Don't re-invent the wheel
  • Manage compatibility issues
  • Led to the addition of W3C's Selectors API
  • Provides effects, animations and other things if desired

jQuery API

Where to Start

Files

 

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Starting with HTML, CSS and JS</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <h1>Start with HTML, CSS and Javascript</h1>

    <!--Use a CDN for jQuery to make it easy right now-->
    <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.5.1.min.js"></script>
    <script src="main.js"></script>
</body>
</html>

styles.css

body {
    margin: 5%;
    font-family: Verdana, sans-serif;
}

h1 {
    border-bottom: 2px solid #CCC;
    text-align: center;
}

main.js

console.log("Hello World");

// If we're using jQuery
$("<p>").text("Hello World").appendTo("body");

// If we're using plain JS
let messageNode = document.createElement("p");
let messageText = document.createTextNode("Hello World");
messageNode.appendChild(messageText);
document.body.appendChild(messageNode);

AJAX

  • Asynchronous
  • HTML, XML or JSON
  • Web API's
  • Implement with:
    • Basic Javascript: XHR object or
    • built-in Request object of the new Fetch API
    • JQuery wraps it in ajax() or getJSON()

JSON

json.org

{
    "menu": {
            "id": "file",
            "value": "File",
            "popup": {
            "menuitem": [
                {"value": "New", "onclick": "CreateNewDoc()"},
                {"value": "Open", "onclick": "OpenDoc()"},
                {"value": "Close", "onclick": "CloseDoc()"}
            ]
            }
        }
}

curl https://api.github.com/search/repositories?q=tetris+language:assembly&sort=stars&order=desc GitHub API

{
"total_count": 2085,
"incomplete_results": false,
"items": [
    {
        "id": 68911683,
        "node_id": "MDEwOlJlcG9zaXRvcnk2ODkxMTY4Mw==",
        "name": "tetros",
        "full_name": "daniel-e/tetros",
        "private": false,
        "owner": {
            "login": "daniel-e",
            "id": 5294331,
            "node_id": "MDQ6VXNlcjUyOTQzMzE=",
            "avatar_url": "https://avatars2.githubusercontent.com/u/5294331?v=4",
            "gravatar_id": "",
            "url": "https://api.github.com/users/daniel-e",
            "html_url": "https://github.com/daniel-e",
            "followers_url": "https://api.github.com/users/daniel-e/followers",
            "following_url": "https://api.github.com/users/daniel-e/following{/other_user}",
            "gists_url": "https://api.github.com/users/daniel-e/gists{/gist_id}",
            "starred_url": "https://api.github.com/users/daniel-e/starred{/owner}{/repo}",
            "subscriptions_url": "https://api.github.com/users/daniel-e/subscriptions",
            "organizations_url": "https://api.github.com/users/daniel-e/orgs",
            "repos_url": "https://api.github.com/users/daniel-e/repos",
            "events_url": "https://api.github.com/users/daniel-e/events{/privacy}",
            "received_events_url": "https://api.github.com/users/daniel-e/received_events",
            "type": "User",
            "site_admin": false
        },
        "html_url": "https://github.com/daniel-e/tetros",
        "description": "Tetris that fits into the boot sector.",
        "fork": false,
        "url": "https://api.github.com/repos/daniel-e/tetros",
        "forks_url": "https://api.github.com/repos/daniel-e/tetros/forks",
        "keys_url": "https://api.github.com/repos/daniel-e/tetros/keys{/key_id}",
        "collaborators_url": "https://api.github.com/repos/daniel-e/tetros/collaborators{/collaborator}",
        "teams_url": "https://api.github.com/repos/daniel-e/tetros/teams",
        "hooks_url": "https://api.github.com/repos/daniel-e/tetros/hooks",
        "issue_events_url": "https://api.github.com/repos/daniel-e/tetros/issues/events{/number}",
        "events_url": "https://api.github.com/repos/daniel-e/tetros/events",
        "assignees_url": "https://api.github.com/repos/daniel-e/tetros/assignees{/user}",
        "branches_url": "https://api.github.com/repos/daniel-e/tetros/branches{/branch}",
        "tags_url": "https://api.github.com/repos/daniel-e/tetros/tags",
        "blobs_url": "https://api.github.com/repos/daniel-e/tetros/git/blobs{/sha}",
        "git_tags_url": "https://api.github.com/repos/daniel-e/tetros/git/tags{/sha}",
        "git_refs_url": "https://api.github.com/repos/daniel-e/tetros/git/refs{/sha}",
        "trees_url": "https://api.github.com/repos/daniel-e/tetros/git/trees{/sha}",
        "statuses_url": "https://api.github.com/repos/daniel-e/tetros/statuses/{sha}",
        "languages_url": "https://api.github.com/repos/daniel-e/tetros/languages",
        "stargazers_url": "https://api.github.com/repos/daniel-e/tetros/stargazers",
        "contributors_url": "https://api.github.com/repos/daniel-e/tetros/contributors",
        "subscribers_url": "https://api.github.com/repos/daniel-e/tetros/subscribers",
        "subscription_url": "https://api.github.com/repos/daniel-e/tetros/subscription",
        "commits_url": "https://api.github.com/repos/daniel-e/tetros/commits{/sha}",
        "git_commits_url": "https://api.github.com/repos/daniel-e/tetros/git/commits{/sha}",
        "comments_url": "https://api.github.com/repos/daniel-e/tetros/comments{/number}",
        "issue_comment_url": "https://api.github.com/repos/daniel-e/tetros/issues/comments{/number}",
        "contents_url": "https://api.github.com/repos/daniel-e/tetros/contents/{+path}",
        "compare_url": "https://api.github.com/repos/daniel-e/tetros/compare/{base}...{head}",
        "merges_url": "https://api.github.com/repos/daniel-e/tetros/merges",
        "archive_url": "https://api.github.com/repos/daniel-e/tetros/{archive_format}{/ref}",
        "downloads_url": "https://api.github.com/repos/daniel-e/tetros/downloads",
        "issues_url": "https://api.github.com/repos/daniel-e/tetros/issues{/number}",
        "pulls_url": "https://api.github.com/repos/daniel-e/tetros/pulls{/number}",
        "milestones_url": "https://api.github.com/repos/daniel-e/tetros/milestones{/number}",
        "notifications_url": "https://api.github.com/repos/daniel-e/tetros/notifications{?since,all,participating}",
        "labels_url": "https://api.github.com/repos/daniel-e/tetros/labels{/name}",
        "releases_url": "https://api.github.com/repos/daniel-e/tetros/releases{/id}",
        "deployments_url": "https://api.github.com/repos/daniel-e/tetros/deployments",
        "created_at": "2016-09-22T10:42:55Z",
        "updated_at": "2020-11-04T01:10:47Z",
        "pushed_at": "2016-12-18T13:32:27Z",
        "git_url": "git://github.com/daniel-e/tetros.git",
        "ssh_url": "git@github.com:daniel-e/tetros.git",
        "clone_url": "https://github.com/daniel-e/tetros.git",
        "svn_url": "https://github.com/daniel-e/tetros",
        "homepage": "",
        "size": 171,
        "stargazers_count": 704,
        "watchers_count": 704,
        "language": "Assembly",
        "has_issues": true,
        "has_projects": true,
        "has_downloads": true,
        "has_wiki": true,
        "has_pages": false,
        "forks_count": 40,
        "mirror_url": null,
        "archived": false,
        "disabled": false,
        "open_issues_count": 0,
        "license": {
            "key": "mit",
            "name": "MIT License",
            "spdx_id": "MIT",
            "url": "https://api.github.com/licenses/mit",
            "node_id": "MDc6TGljZW5zZTEz"
        },
        "forks": 40,
        "open_issues": 0,
        "watchers": 704,
        "default_branch": "master",
        "score": 1.0
    },
    {
        "id": 8688362,
        "node_id": "MDEwOlJlcG9zaXRvcnk4Njg4MzYy",
        "name": "Nand2Tetris",
        "full_name": "havivha/Nand2Tetris",
        "private": false,
        "owner": {
            "login": "havivha",
            "id": 2629901,
            "node_id": "MDQ6VXNlcjI2Mjk5MDE=",
            "avatar_url": "https://avatars3.githubusercontent.com/u/2629901?v=4",
            "gravatar_id": "",
            "url": "https://api.github.com/users/havivha",
            "html_url": "https://github.com/havivha",
            "followers_url": "https://api.github.com/users/havivha/followers",
            "following_url": "https://api.github.com/users/havivha/following{/other_user}",
            "gists_url": "https://api.github.com/users/havivha/gists{/gist_id}",
            "starred_url": "https://api.github.com/users/havivha/starred{/owner}{/repo}",
            "subscriptions_url": "https://api.github.com/users/havivha/subscriptions",
            "organizations_url": "https://api.github.com/users/havivha/orgs",
            "repos_url": "https://api.github.com/users/havivha/repos",
            "events_url": "https://api.github.com/users/havivha/events{/privacy}",
            "received_events_url": "https://api.github.com/users/havivha/received_events",
            "type": "User",
            "site_admin": false
        },
        "html_url": "https://github.com/havivha/Nand2Tetris",
        "description": "Computer implementation as described in \"The Elements of Computing Systems\"",
        "fork": false,
        "url": "https://api.github.com/repos/havivha/Nand2Tetris",
        "forks_url": "https://api.github.com/repos/havivha/Nand2Tetris/forks",
        "keys_url": "https://api.github.com/repos/havivha/Nand2Tetris/keys{/key_id}",
        "collaborators_url": "https://api.github.com/repos/havivha/Nand2Tetris/collaborators{/collaborator}",
        "teams_url": "https://api.github.com/repos/havivha/Nand2Tetris/teams",
        "hooks_url": "https://api.github.com/repos/havivha/Nand2Tetris/hooks",
        "issue_events_url": "https://api.github.com/repos/havivha/Nand2Tetris/issues/events{/number}",
        "events_url": "https://api.github.com/repos/havivha/Nand2Tetris/events",
        "assignees_url": "https://api.github.com/repos/havivha/Nand2Tetris/assignees{/user}",
        "branches_url": "https://api.github.com/repos/havivha/Nand2Tetris/branches{/branch}",
        "tags_url": "https://api.github.com/repos/havivha/Nand2Tetris/tags",
        "blobs_url": "https://api.github.com/repos/havivha/Nand2Tetris/git/blobs{/sha}",
        "git_tags_url": "https://api.github.com/repos/havivha/Nand2Tetris/git/tags{/sha}",
        "git_refs_url": "https://api.github.com/repos/havivha/Nand2Tetris/git/refs{/sha}",
        "trees_url": "https://api.github.com/repos/havivha/Nand2Tetris/git/trees{/sha}",
        "statuses_url": "https://api.github.com/repos/havivha/Nand2Tetris/statuses/{sha}",
        "languages_url": "https://api.github.com/repos/havivha/Nand2Tetris/languages",
        "stargazers_url": "https://api.github.com/repos/havivha/Nand2Tetris/stargazers",
        "contributors_url": "https://api.github.com/repos/havivha/Nand2Tetris/contributors",
        "subscribers_url": "https://api.github.com/repos/havivha/Nand2Tetris/subscribers",
        "subscription_url": "https://api.github.com/repos/havivha/Nand2Tetris/subscription",
        "commits_url": "https://api.github.com/repos/havivha/Nand2Tetris/commits{/sha}",
        "git_commits_url": "https://api.github.com/repos/havivha/Nand2Tetris/git/commits{/sha}",
        "comments_url": "https://api.github.com/repos/havivha/Nand2Tetris/comments{/number}",
        "issue_comment_url": "https://api.github.com/repos/havivha/Nand2Tetris/issues/comments{/number}",
        "contents_url": "https://api.github.com/repos/havivha/Nand2Tetris/contents/{+path}",
        "compare_url": "https://api.github.com/repos/havivha/Nand2Tetris/compare/{base}...{head}",
        "merges_url": "https://api.github.com/repos/havivha/Nand2Tetris/merges",
        "archive_url": "https://api.github.com/repos/havivha/Nand2Tetris/{archive_format}{/ref}",
        "downloads_url": "https://api.github.com/repos/havivha/Nand2Tetris/downloads",
        "issues_url": "https://api.github.com/repos/havivha/Nand2Tetris/issues{/number}",
        "pulls_url": "https://api.github.com/repos/havivha/Nand2Tetris/pulls{/number}",
        "milestones_url": "https://api.github.com/repos/havivha/Nand2Tetris/milestones{/number}",
        "notifications_url": "https://api.github.com/repos/havivha/Nand2Tetris/notifications{?since,all,participating}",
        "labels_url": "https://api.github.com/repos/havivha/Nand2Tetris/labels{/name}",
        "releases_url": "https://api.github.com/repos/havivha/Nand2Tetris/releases{/id}",
        "deployments_url": "https://api.github.com/repos/havivha/Nand2Tetris/deployments",
        "created_at": "2013-03-10T17:04:20Z",
        "updated_at": "2020-11-03T11:42:59Z",
        "pushed_at": "2019-05-29T23:41:28Z",
        "git_url": "git://github.com/havivha/Nand2Tetris.git",
        "ssh_url": "git@github.com:havivha/Nand2Tetris.git",
        "clone_url": "https://github.com/havivha/Nand2Tetris.git",
        "svn_url": "https://github.com/havivha/Nand2Tetris",
        "homepage": null,
        "size": 474,
        "stargazers_count": 225,
        "watchers_count": 225,
        "language": "Assembly",
        "has_issues": false,
        "has_projects": true,
        "has_downloads": true,
        "has_wiki": true,
        "has_pages": false,
        "forks_count": 126,
        "mirror_url": null,
        "archived": false,
        "disabled": false,
        "open_issues_count": 2,
        "license": null,
        "forks": 126,
        "open_issues": 2,
        "watchers": 225,
        "default_branch": "master",
        "score": 1.0
    },
    {
        "id": 37400358,
        "node_id": "MDEwOlJlcG9zaXRvcnkzNzQwMDM1OA==",
        "name": "tetrasm",
        "full_name": "causal-agent/tetrasm",
        "private": false,
        "owner": {
            "login": "causal-agent",
            "id": 166462,
            "node_id": "MDQ6VXNlcjE2NjQ2Mg==",
            "avatar_url": "https://avatars2.githubusercontent.com/u/166462?v=4",
            "gravatar_id": "",
            "url": "https://api.github.com/users/causal-agent",
            "html_url": "https://github.com/causal-agent",
            "followers_url": "https://api.github.com/users/causal-agent/followers",
            "following_url": "https://api.github.com/users/causal-agent/following{/other_user}",
            "gists_url": "https://api.github.com/users/causal-agent/gists{/gist_id}",
            "starred_url": "https://api.github.com/users/causal-agent/starred{/owner}{/repo}",
            "subscriptions_url": "https://api.github.com/users/causal-agent/subscriptions",
            "organizations_url": "https://api.github.com/users/causal-agent/orgs",
            "repos_url": "https://api.github.com/users/causal-agent/repos",
            "events_url": "https://api.github.com/users/causal-agent/events{/privacy}",
            "received_events_url": "https://api.github.com/users/causal-agent/received_events",
            "type": "User",
            "site_admin": false
        },
        "html_url": "https://github.com/causal-agent/tetrasm",
        "description": "Tetris for x86 in NASM",
        "fork": false,
        "url": "https://api.github.com/repos/causal-agent/tetrasm",
        "forks_url": "https://api.github.com/repos/causal-agent/tetrasm/forks",
        "keys_url": "https://api.github.com/repos/causal-agent/tetrasm/keys{/key_id}",
        "collaborators_url": "https://api.github.com/repos/causal-agent/tetrasm/collaborators{/collaborator}",
        "teams_url": "https://api.github.com/repos/causal-agent/tetrasm/teams",
        "hooks_url": "https://api.github.com/repos/causal-agent/tetrasm/hooks",
        "issue_events_url": "https://api.github.com/repos/causal-agent/tetrasm/issues/events{/number}",
        "events_url": "https://api.github.com/repos/causal-agent/tetrasm/events",
        "assignees_url": "https://api.github.com/repos/causal-agent/tetrasm/assignees{/user}",
        "branches_url": "https://api.github.com/repos/causal-agent/tetrasm/branches{/branch}",
        "tags_url": "https://api.github.com/repos/causal-agent/tetrasm/tags",
        "blobs_url": "https://api.github.com/repos/causal-agent/tetrasm/git/blobs{/sha}",
        "git_tags_url": "https://api.github.com/repos/causal-agent/tetrasm/git/tags{/sha}",
        "git_refs_url": "https://api.github.com/repos/causal-agent/tetrasm/git/refs{/sha}",
        "trees_url": "https://api.github.com/repos/causal-agent/tetrasm/git/trees{/sha}",
        "statuses_url": "https://api.github.com/repos/causal-agent/tetrasm/statuses/{sha}",
        "languages_url": "https://api.github.com/repos/causal-agent/tetrasm/languages",
        "stargazers_url": "https://api.github.com/repos/causal-agent/tetrasm/stargazers",
        "contributors_url": "https://api.github.com/repos/causal-agent/tetrasm/contributors",
        "subscribers_url": "https://api.github.com/repos/causal-agent/tetrasm/subscribers",
        "subscription_url": "https://api.github.com/repos/causal-agent/tetrasm/subscription",
        "commits_url": "https://api.github.com/repos/causal-agent/tetrasm/commits{/sha}",
        "git_commits_url": "https://api.github.com/repos/causal-agent/tetrasm/git/commits{/sha}",
        "comments_url": "https://api.github.com/repos/causal-agent/tetrasm/comments{/number}",
        "issue_comment_url": "https://api.github.com/repos/causal-agent/tetrasm/issues/comments{/number}",
        "contents_url": "https://api.github.com/repos/causal-agent/tetrasm/contents/{+path}",
        "compare_url": "https://api.github.com/repos/causal-agent/tetrasm/compare/{base}...{head}",
        "merges_url": "https://api.github.com/repos/causal-agent/tetrasm/merges",
        "archive_url": "https://api.github.com/repos/causal-agent/tetrasm/{archive_format}{/ref}",
        "downloads_url": "https://api.github.com/repos/causal-agent/tetrasm/downloads",
        "issues_url": "https://api.github.com/repos/causal-agent/tetrasm/issues{/number}",
        "pulls_url": "https://api.github.com/repos/causal-agent/tetrasm/pulls{/number}",
        "milestones_url": "https://api.github.com/repos/causal-agent/tetrasm/milestones{/number}",
        "notifications_url": "https://api.github.com/repos/causal-agent/tetrasm/notifications{?since,all,participating}",
        "labels_url": "https://api.github.com/repos/causal-agent/tetrasm/labels{/name}",
        "releases_url": "https://api.github.com/repos/causal-agent/tetrasm/releases{/id}",
        "deployments_url": "https://api.github.com/repos/causal-agent/tetrasm/deployments",
        "created_at": "2015-06-14T05:26:28Z",
        "updated_at": "2020-11-06T15:13:54Z",
        "pushed_at": "2018-09-21T18:19:02Z",
        "git_url": "git://github.com/causal-agent/tetrasm.git",
        "ssh_url": "git@github.com:causal-agent/tetrasm.git",
        "clone_url": "https://github.com/causal-agent/tetrasm.git",
        "svn_url": "https://github.com/causal-agent/tetrasm",
        "homepage": null,
        "size": 420,
        "stargazers_count": 111,
        "watchers_count": 111,
        "language": "Assembly",
        "has_issues": true,
        "has_projects": true,
        "has_downloads": true,
        "has_wiki": true,
        "has_pages": false,
        "forks_count": 9,
        "mirror_url": null,
        "archived": true,
        "disabled": false,
        "open_issues_count": 2,
        "license": null,
        "forks": 9,
        "open_issues": 2,
        "watchers": 111,
        "default_branch": "master",
        "score": 1.0
    }
]
                                }

jQuery AJAX Setup

jQuery.getJSON()

var jqxhr = $.getJSON( "api/endpoint", function(data) {
      // use returned data
      console.log( "success" );
      })
      .done(function() {
        console.log( "second success" );
      })
      .fail(function() {
        console.log( "error" );
      })
      .always(function() {
        console.log( "complete" );
      });

jQuery.ajax()

$.ajax({
    dataType: "json",
    url: url,
    data: dataToSendWithRequest,
    success: successFunction
});

Use the JSON directly ( jQuery )

/* Returned JSON:
{
    "one": "Singular sensation",
    "two": "Beady little eyes",
    "three": "Little birds pitch by my doorstep"
} */
$.getJSON( "ajax/test.json", function( data ) {
    var items = [];
    $.each( data, function( key, val ) {
      items.push( "<li id='" + key + "'>" + val + "</li>" );
    });
   
    $( "<ul/>", {
      "class": "my-new-list",
      html: items.join( "" )
    }).appendTo( "body" );
  });

Copy of JavaScript

By drmorgan

Copy of JavaScript

  • 2