Technologies: HMTL, CSS, JavaScript, jQuery, AJAX, JSON, APIs, client-server architecture

AJAX stands for Asynchronous JavaScript and XML and is a helpful tool to build a XMLHttpRequest Object.

Let's outline how it works:
1. Your program is running on a user's computer.
2. Your program tells the browser what data it needs in a package called a XHLHttpRequest Object.
3. The Request Object tells the user's browser to send a request to a certain location where this data is stored.
4. The internet location that intercepted your request, then determines what information to send back, based on your Request Object.
5. Your program then has to set and wait for the data to be returned from the endpoint (or API). This is called an Asynchronous function.
6. Once returned, the data can now be parsed.
7. We then tell the browser how to utilize and render the data.

AJAX in layman's terms.
Basically it is a script forged on the paradigm of Asynchronous functionality.
A computer program is very linear in nature. Say I'm running a program on Computer A and request data from Computer B. By the time Computer B sent the data back... The program running on computer A would be complete and unable to receive the data from computer B.
AJAX allows a sort of timing protocol to ensure that we can obtain the data and control the flow of our computer program.

Why is AJAX so nice?
Well, imagine if you had 5000 users. Each user has an address, zip, first and last name, nickname, password, email, etc... That would be a lot of data to store on every one of your user's computers.
So Application Program Interfaces, or APIs, do a few things. They provide security, keep your data manageable, and keep your program's footprint small. AJAX is a communication tool that allows your program to talk with APIs, files and other data sources.

How does this work with Javascript?
AJAX is built in to jQuery. Simply include jQuery and AJAX functionality is available in your application or site.

Good things to note:
1. AJAX builds and passes request objects and data very conveniently for us.
2. The request object created by our AJAX call includes the request type, state, headers and many other needed bits of information that we do not have to manually create.
3. Speaking of States, kittens are the best way to memorize your states.

Resources
n/a

Step 1: File Structure

Create a folder structure similar to this.

  • ajax-tut
    • css
      • styles.css
    • js
      • main.js
    • index.html
Step 2: Setup a server

Before we get into the code. We need to setup a few items to ensure we are serving up our website/app correctly. If we do not do this, then our AJAX will not work correctly due to cross-domain header violations.

1. We need to be running Node.js so install Node.js
Mac will show the mac version, windows will show the windows version.
2. Follow the installation instructions.
3. Once Node is installed, you will have access to Node Package Manager (NPM). Open your terminal(Mac) or command prompt(Windows).
4. Type: npm install http-server -g
*Note: If you type --help, you will see -g will install the desired software globally. If you are on a mac, you may need to install this with sudo for permissions.
5. Now in terminal or command prompt, navigate to the root directory of your site. The folder named ajax-tut. The one containing index.html
6. Type: http-server -c-1
The -c will make sure your cache is cleared every time you refresh. This is great because you know you are getting up-to-date versions.

Step 3: Setup our HTML, CSS, JavaScript

1. index.html:


<!DOCTYPE html >
<head>
    <title>Ajax Example</title>
</head>
	
<body>

    <!--HTML CONTENT GOES HERE-->
    <h1>Hello World!</h1>
    
    <script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
    <script type="text/javascript" src="/js/main.js"></script>
</body>

2. /css/styles.css:


h1{
	color: red;
}

3. /js/main.js:


window.onload = function(){
    if (typeof jQuery != 'undefined') {
        alert("jQuery is loaded!");
    }
};//End of window.onload

4. Open a browser window and in the address bar type: localhost:8080
The http-server defaults to 8080. But in some cases that port is being used. If you look in your terminal(command prompt) you will see the http-server running. I will give a read out of the current port settings. If it is other than 8080. Please use the given port in your browser.

5. When the browser window loads:

  • A Red "Hello World!" will indicate your styles.css has loaded correctly.
  • A popup that says "jQuery is loaded!" will indicate your jQuery has loaded correctly.

If you don't see these, please repeat this section. Make sure it works before proceeding.

Step 4: Defining our request object

1. The Uniform Resource Identifier
The OMDb API usage says that we should send all our API requests to: http://www.omdbapi.com/?
That is called the URI or Uniform Resource Identifier.
We are now building the XMLHttpRequest Object.
There are 2 parts:

  • Request - which contains the header info, state, etc... we won't worry about those now
  • URI

The URI is then broken down into 3 parts:

  • Protocol type: http, ftp, etc.
  • URL (location): In this tut it is: www.omdbapi.com
  • Parameters

2. Paramters
These parameters tell the API what data we want to retrieve.
For starters we will use these setting for our parameter:
"?s=frozen&plot=short&r=json"

  • the s is for search
  • Frozen is the the keyword or title we will be searching for.
  • the & tells the API we have another parameter.
  • plot is for... plot. It can be short or long. we want the short version.
  • r is for return, which we want to return a JSON object

Here is our completed URI:
http://www.omdbapi.com/?s=frozen&y=&plot=short&r=json

Want to check it?
Copy and paste that full URL in a new browser tab or click here.

You will receive all the JSON information from the OMDb API endpoint regarding the keyword: "Frozen"

We will be working with the OMDb API. I recommend reviewing their API Usage and Parameters. You will need to learn how to utilize each endpoint you work with. You will possibly need to learn how to write docs for such endpoints as well.

Pro tip:

Need a time saver to test and work with server side endpoints? Check out Postman
You can also get it in your Chrome Extensions Store.

Step 5: Server-Client Endpoint Loop

I think it's vital to at least see the basic server-client architecture. It will help to understand what is happening behind the scenes when you send off your request object as we will do in the next step.

Step 6: Coding the AJAX call

1. In our index.html. Replace the code inside our BODY tags with this:

<h1>AJAX Movie Search</h1>
<input id="movie-title"/>
<button id="do-search">Search</button>
<div id="container"></div>

2. Remove the jQuery confirmation and add this code in your main.js

$("#do-search").on('click',function(){
	//Get data from input box
	var movieTitle = $('#movie-title').val();

	//Build our URI with the movie title
	var sURL = "http://www.omdbapi.com/?s=" + movieTitle + "&plot=short&r=json";

	//Grab our container and assign it to variable for later use
	var container = $('#container');

	$.ajax({
		method: 'GET',
		url: sURL,
		success: function(results){
			console.log("Done: ", results);
		},
		error: function(error){
			console.error('@ERROR', error);
		}
	});

});

3. Viewing the Returned Data

If you are using chrome, you can right click any where on the screen.
Then select "inspect" from the menu.
- If you have Firefox, you can do the same. In the older versions of firefox you had to install the dev tools.

Next, click on the "Console" tab and you should see an object that contains our returned endpoint data. Click on the arrow next to the object to see it's children.

Step 7: Parsing data

1. We need to understand what the AJAX call does when it returns the data.
The structure is pretty straight forward.

  • success - this is returned when the data was successfully retrieved
  • error - this is returned when the data was not successfully retrieved. We console log the error.

When we successfully retrieve our data, then we can begin to parse it.

2. In our main.js we now need to update our success callback function.

$.ajax({
    method: 'GET',
    url: sURL,
    success: function(results){
	//store our search results in a variable called movies
        //the results object needs to be broke down a little bit.
        //We find the needed data in the Search object within the results object
        //So we store the object we need in a temporary variable so we can
        //more easily access it
        var movies = results.Search;
                   
        //Loop through the total number of movies found
        for(var i = 0; i < = movies.length-1; i++){
              console.log(movies[i]);
                
        }
        //Alternatively you can use a for-in loop
        //for (movie in movies){
        //    curMovie = movies[movie]; //store in temp var so we don't have to retype movies[movie]
        //    console.log("Movies: ", movie, " : " curMovie);
        //}
    },
    error: function(error){
	console.error('@ERROR', error);
    }
});

3. Now the data is broken down enough to access the values of each key with dot notation
movies[i].title

Step 8: Rendering the data

Now that we have the information parsed and available. We need to build a string of elements that we will then append to the DOM

1. Inside our success callback function, inside and at the bottom of the for loop. paste this:

var curMovieString = '<li> <img src=' + movies[i].Poster + '/></li>' + '<li>' + movies[i].Title + '</li>' + '<li>' + movies[i].Type + '</li>' + '<li>' + movies[i].Year + '</li>';
container.append(curMovieString);

2. Now, refresh the page. If you type in a movie title, you should return the data and have it listed on your website.

See the Pen AJAX - intro - OMDb API by Jeremy (@J-Roel) on CodePen.

Conclusion:

AJAX is powerful and simplifies the process of accessing APIs and data.
This tutorial will hopefully help you understand how AJAX is used and give you another tool to build awesome web sites and applications.

Stretch Goals:

1. Customize the CSS to make your Movie App look better.
2. Use AJAX to access a local JSON file and render the information to the web browser.

Technologies: jQuery, JavaScript, WordPress

WordPress:
1. Download, unzip and add the smooth-scroll.js to your theme's JS folder.
2. Next, goto Appearance -> Editor. Open the Theme Functions (functions.php) file.
3. At the bottom of the file add the below code:
Note: Depending on the theme, you need to make sure you are inside the PHP closing tag.


function myscripts() {

    $script = get_template_directory_uri() . '/js/smooth-scroll.js';
    wp_register_script( 'smoothscroll-js', $script , '', '', true );

    //always enqueue the script after registering or nothing will happen
    wp_enqueue_script('smoothscroll-js');
     
}
add_action("wp_enqueue_scripts", "myscripts");

4. Now you need to set a href link to your desired location.
5. And your destination will be an element with the same id as the link. See the Codepen example below

Non-WordPress
Follow the instructions above and instead of step 3, you will need to use a script tag in your index.html

See the Pen Smooth Scroll Example by Jeremy (@J-Roel) on CodePen.


Technologies: HTML, CSS, JavaScript, SVG, jQuery

You probably already know the technical aspects of SVG. So I won't go into any of the background.

My task here today is to take a JavaScript Object:

svgData = {
    defs: { },
    svg: {
        height: 500,
        width: 500
    },
    polygon: {
        points: {
             0: [200,10],
             1: [250,190],
             2: [160,210],
             3: [100,80]
        },
        style : {
            fill: "lime",
            stroke: "purple",
            strokeWidth: "4"
        }
    }
}

And render this to the screen:

So to begin with, let's get a basic template setup. index.html:


<!DOCTYPE html>
<head>
    <title>SVG from Object</title>
</head>
<body>
    <div id="svgParent">
        <!--SVG GOES HERE-->
    </div>

<script src="add jquery here"></script>
</body>

Now we need to load the JavaScript Object. I am using the above object as a test to determine what I will eventually need in a loadable/savable JSON object. So it is sort of rough right now, but it will get us started.

The first thing we need to do is setup our JavaScript file.

"use strict";
window.onload = function(){
   //Do something
};

Just a quick FYI, I've recently read some articles that point out Document.Ready() will soon not be the recommended way to check your DOM. So I always use window.onload

So now we need to divide concerns. So let's add a function:

"use strict";
window.onload = function(){

    //Load our SVG Object when the DOM has loaded.
    loadSVGObject(svgData);

}; //End Window Onload

// Description: Parse the loaded object and append to our DOM work area
// params: svgData - the object containing our SVG information;
// return: none;
function loadSVGObject(svgData){

    //Do our parsing and appending here

}; //End loadSVGObject

Now we will learn how to parse the object in JavaScript.
So in our loadSVGObject function we need to do a couple of things:

1. Determine where we are going to attach our SVG element to our DOM - aka our Parent
Note: I use jQuery because the application I am using already has it loaded. But feel free to use pure javascript: var parent = document.getElementById('svgParent');
2. Build our DOM structure, SVG -> Polygon
3. Put together our Polygon attributes based on our svgData
4. Combine 1,2 and 3
5. Add the resulting structure to our DOM
6. And finally, we will need to refresh our DOM's html so the SVG will be accounted for and rendered properly.


function loadSVGObject(svgData){

    //1. Where are we going to attach our svg?
    var parent = $('#svgParent');

    //2. Build our DOM structure
    curObjSVG = document.createElement("svg"); //create a new svg element
    curObjSVG.setAttribute("width", svgData.svg.width); //set the svg element's width and height attributes
    curObjSVG.setAttribute("height", svgData.svg.height);

    //3. Put together our polygon attributes
    curObjSVGPolygon = document.createElement("polygon");
    var pointStr = ""; //create a temp empty string to hold our points
    for(point in svgData.polygon.points){
        aX = svgData.polygon.points[point][0];
	aY = svgData.polygon.points[point][1];
	aPoint = aX + "," + aY;
	pointStr += aPoint + " ";
    }
    curObjSVGPolygon.setAttribute("points", pointStr); //The points are in a string, let's apply them as the attribute
    
    //We are adding the styles inline. I did this because I need each svg object to keep it's individual styles
    var tempStyleStr = "fill:" + svgData.polygon.style.fill + ";" + " stroke:" + svgData.polygon.style.stroke + ";" + " stroke-width:" + svgData.polygon.style.strokeWidth + ";";
    curObjSVGPolygon.setAttribute("style", tempStyleStr ); //The styles are in a string, apply them as the attribute

    //4. Now append the elements together
    curObjSVG.append( curObjSVGPolygon );

    //5. Add them to the parent which is already on the DOM
    parent.append( curObjSVG );
    
    //6. Now refresh the DOM (or parent), so our SVG will be rendered properly
    parent.html(parent.html());

}; //End loadSVGObject

The code in #6 is important because of the way the DOM loads the SVG. The code is processed when it loads the initial html. So we need a little hack to force the DOM to recognize the new SVG and update the rendered element.

Resources:
n/a

Codepen

See the Pen SVG from a JavaScript Object by Jeremy (@J-Roel) on CodePen.

Conclusion:
SVGs are fun to work with. You can utilize these components to achieve some really nice effects and make them responsive. This tutorial can help you get started with dynamically accessing DOM related elements for use on your web applications.

The very basics of using Google Drive as a place for storing files across devices.

Making a moss shader for the Unity3D engine. This can be used for snow, moss or anything you can think of. I don’t know if I’ll release this to the Unity Asset Store, but the current moss/snow shader on the asset store is a little over priced. So I might give him a little healthy competition.