JSON Introduction

In JavaScript, JSON stands for JavaScript Object Notion. Notion is simply the syntax of how something is written. Basically, we are dealing with JavaScripts objects, but we are using the idea of JSON. JavaScript gives JSON a few special functions, but we will get to these later. It should be said that, in JavaScript, we can have JSON objects and JSON arrays, but I will not be highlighting the difference in this tutorial as we will only work with objects. JSON arrays are just an array of JSON objects, so I don’t really consider them to be much different that real arrays.

So, what is JSON and why should you care? You should care because JSON has revolutionized how to transfer information because of its simplicity and functionality. Sure, you can transfer data using XML, raw text, or some other structured data, but how easily is that integrated with JavaScript? Since it is JavaScript Object Notion, JSON is obviously integrated quite well with JavaScript. You can use JSON inside your code as a type of variable if you want, but it is most useful for requests made by AJAX. I won’t dive into detail on how to transfer data using JSON with AJAX in this tutorial, but we will create a JSON object. Let’s create some JSON:

Example
var people = { “firstName”:”Jared” , “lastName”:”Drake” }
document.write(people.lastName);

This is a very simplistic example of JSON, which really is not that much different that creating another object in JavaScript. We create an object variable people that is set to this odd little string. The string is actually 2 separate variables or properties: “firstName” and “lastName”. Yes, those variables or object properties are defined in quotes because that is how JSON is written. Following those properties, we have a colon and then what looks like another variable or property. Technically, it is a property of the preceding variable, but for our purposes think of it as a simple string. The same thing occurs for the next variable. That seems easy enough, but how does document.write(people.lastName); know to print out “Drake”? Like I said, people is an object with “firstName” and “lastName” as properties. So, when you tell JavaScript to write out people.lastName, it looks at the people object and sees that it does have a “lastName” property. Then, it prints out the contents of that property, which is “Drake”.

I know that is a little difficult to wrap our heads around, but JSON is very useful for transferring data. Look at the structure of the example we created. We have just one ultimate variable name, that has ordered internal properties, which helps us reduce variable collisions or overwrites in our JavaScript.

References

Math Object

The JavaScript Math Object might not be used quite as often as the string object, but it is really useful when dealing with numbers. Sometimes we need to find the nearest integer to a number with a decimal (float). Other times, we need to do some sophisticated mathematics on them, such as powers or square roots. The math object is also where random number generation resides.

Number in JavaScript are really simple and so is the Math Object. However, I have sort of mislead you on numbers and the Math Object. See, the Math Object acts upon numbers, they do not utilize the Math Object as a method. As you will see in the examples below, we must perform the Math methods on our numbers. This is why you will see Math.method(number) being used in the references below. I know it seems like once you have a number it should have methods that do these Math Object Methods, but they simply don’t exist.

Common Math Object Methods

abs(x) – gets absolute value of x

Example
document.write(Math.abs(-1));
Result

1

ceil(x) – gets x rounded up to the nearest integer

Example
document.write(Math.ceil(2.6));
Result

3

floor(x) – gets x rounded up to the nearest integer

Example
document.write(Math.floor(2.6));
Result

2

max(x,y,z,…) – gets the highest number of the arguments

Example
document.write(Math.max(2,3,4,5));
Result

5

min(x,y,z,…) – gets the lowest number of the arguments

Example
document.write(Math.min(2,3,4,5));
Result

5

pow(x,y) – gets x to the power of y

Example
document.write(Math.pow(2,3));
Result

8

random() – generates random number between 0 and 1

Example
document.write(Math.random());
Result

0.6697745699866664

round(x) – gets x rounded to the nearest integer

Example
document.write(Math.round(2.5));
Result

3

sqrt(x) – gets the square root of x

Example
document.write(Math.sqrt(16));
Result

4

Date Object

JavaScript date objects are obviously used to track time. You might be thinking, “awesome, I can make a clock.” Please don’t limit yourself to just building a clock. You can use the date for so much, such as sessions, updates, etc.

When the creators of JavaScript made the date object, they did a wonderful job. In other languages, dates and times are often separated which makes comparison very difficult. However, JavaScript date objects are still quite complicated because the people who created the calendar obviously didn’t consider programming.

Date Properties are fairly normal with just the constructor and prototype, neither of which are commonly used.

Common Date Methods

The date object can either get or set times and can compare times.

Getting Times

I am not going to show the examples here, but you should know that all of the date methods that get time return integers. If it was monday getDay() would return 1 instead of Monday (Sunday returns 0).

  • getFullYear() – gets the year (Ex. 2012)
  • getMonth() – gets the month, where January is 0 and December is 11
  • getDate() – gets the day of the month
  • getDay() – gets the day of the week, where Sunday is 0 and Saturday is 6
  • getHours() – gets the hour
  • getMinutes() – gets the minutes
  • getSeconds() – gets the seconds
  • getMilliseconds() – gets the milliseconds, remember that there are 1000 milliseconds in a second
Example
<script type="text/javascript">
    var d = new Date();
    document.write(d.getDay());
</script>
Result

2

Setting Times

Example
<script type="text/javascript">
    var d = new Date(2012,3,1,20,28,56,445); //year, month, day, hours, minutes, seconds, milliseconds
    document.write(d);
</script>
Result

Sun Apr 01 2012 20:28:56 GMT-0400 (Eastern Daylight Time)

While I would say the best way to set a time is when you create it, I understand that there are a few reasons to change a time after it has been set.

  • setFullYear() – sets the year (Ex. 2012)
  • setMonth() – sets the month, where January is 0 and December is 11
  • setDate() – sets the day of the month
  • setDay() – sets the day of the week, where Sunday is 0 and Saturday is 6
  • setHours() – sets the hour
  • setMinutes() – sets the minutes
  • setSeconds() – sets the seconds
  • setMilliseconds() – sets the milliseconds, remember that there are 1000 milliseconds in a second

Comparing Times

Setting and getting times are extremely useful, but what if you want to compare them?

Example
<script type="text/javascript">
    var oldTime = new Date(2012,3,1,20,28,56,445);
    var nowTime = new Date();
    if(oldTime.getTime() <= nowTime.getTime())
    {
        document.write("nowTime is greater than oldTime");
    }
    else
    {
        document.write("oldTime is greater than nowTime");
    }
</script>
Result

nowTime is greater than oldTime

You have to remember that the nowTime above is a date object. It would not work to say is now time <= some number.

Finally, we have one last important topic to cover with date objects.

  • toString() - converts a date object to a string

The date method toString() is useful when you would like to display only parts of a time in a string. This allows you to join the strings together to show exactly what parts of the time you would like to display. Let's go through an example for a better explanation.

Example
<script type="text/javascript">
    var nowTime = new Date();
    var year = nowTime.getFullYear();
    var month = nowTime.getMonth();
    var day = nowTime.getDate();
    var combined = year + month + " " + day;
    document.write(combined);
    document.write("<br/>"); //line break
    var combinedString = year.toString() + month.toString() + " " + day.toString();
    document.write(combinedString);
</script>
Result

2015 3
20123 3

Now you see that, if you don't use the toString(), the year and month are added. However, if we use the toString() methods when we add them we get 20123, which is the year and the month joined not added. I put the day in the example above so you can see that they are not added if a string separates them. So, if you want to use the date objects as strings, use the toString() just to be safe.

Arrays

Javascript Arrays are an object that permits you to store multiple values into a collection for easy reference. For example, if you wanted to track a user’s position position over some time, you could insert the x and y values into an array. Arrays are more than just the example of x and y values though.

Let’s say we are building a calculator. Initially, we might think that we only need to variables. We need one for the first number before the operator is pressed and another one after. Congratulations on us being super static. Maybe we now want to be able to add more than just 2 values before calculating the sum. We should have used an array from the very beginning. If we would have used an array, we could have put all of those numbers in one single array, which is a 1000 times better than having to create a new variable for each number. It is a compliment in the world of programming if someone says your coding is dynamic. Arrays are in fact just that, dynamic.

Example
var example = new Array(“aa”,”bb”,”cc”);
example[3] = “dd”;
example[4] = “ee”;
document.write(example); // write out our entire array
document.write(“<br/>”); // line break
document.write(example[2]); // write out array item with an index of 2
Result

aa,bb,cc,dd,ee
cc

Common Array Properties

constructor – tells us the function that created the Array object’s prototype

Example
var example = new Array(“aa”,”bb”,”cc”);
document.write(example.constructor);
Result

function Array() { [native code] }

length – returns the total number of items in a array

Example
var example = new Array(“aa”,”bb”,”cc”);
document.write(example.length);
Result

3

Common Array Methods

As an object, arrays have a variety of methods. Since arrays are super dynamic, we have a lot of things we want to do with them. The creators of JavaScript gave us plenty of methods to use on our arrays.

concat() – this is the proper way to combine multiple arrays

Example
var example1 = new Array(“aa”,”bb”,”cc”);
var example2 = new Array(“dd”,”ee”,”ff”);
var example3 = new Array(“gg”,”hh”,”ii”);
var example4 = example1.concat(example2,example3);
document.write(example4);
Result

aa,bb,cc,dd,ee,ff,gg,hh,ii

indexOf() – finds item and returns it’s position

Example
var example = new Array(“aa”,”bb”,”cc”,”cc”);
document.write(example.indexOf(“cc”));
Result

2

lastIndexOf() – finds item’s finale occurrence and returns it’s position

Example
var example = new Array(“aa”,”bb”,”cc”,”cc”);
document.write(example.lastIndexOf(“cc”));
Result

3

join() – joins all of the elements in an array into a string (values separated by a comma)

Example
var example = new Array(“aa”,”bb”,”cc”);
document.write(example.join());
Result

aa,bb,cc

slice() – selects and returns part of an array

Example
var example = new Array(“aa”,”bb”,”cc”,”dd”);
document.write(example.slice(2,4)); 
Result

cc,dd

reverse() – reverses the order of the array

Example
var example = new Array(“aa”,”bb”,”cc”);
document.write(example.reverse());
Result

cc,bb,aa

sort() – sorts elements as you would expect

Example
var example = new Array(“dd”,”cc”,”bb”,”aa”);
document.write(example.sort()); 
Result

aa,bb,cc,dd

splice() – add and/or removes elements from array

Example
var example1 = new Array(“aa”,”bb”,”cc”,”dd”);
example1.splice(2,1);
document.write(example1);
document.write(“
“); // line break

var example2 = new Array(“aa”,”bb”,”cc”,”dd”);
example2.splice(1,1,”ee”,”ff”);
document.write(example2);
Result

aa,bb,dd
aa,ee,ff,cc,dd

push() – adds items to the end of array, and returns position of the added item

Example
var example = new Array(“aa”,”bb”,”cc”);
document.write(example.push(“dd”));
Result

4

pop() – removes and returns the last item of the array

Example
var example = new Array(“aa”,”bb”,”cc”);
document.write(example.pop()); 
document.write(“
“); // new line
document.write(example);
Result

cc
aa,bb

shift() – removes and returns the first item of the array

Example
var example = new Array(“aa”,”bb”,”cc”);
document.write(example.shift()); 
document.write(“
“); // new line
document.write(example);
Result

aa
bb,cc

unshift() – adds item to beginning of the array and returns its new length

Example
var example = new Array(“aa”,”bb”,”cc”);
document.write(example.unshift(“zz”)); 
document.write(“
“); // new line
document.write(example);
Result

4
zz,aa,bb,cc

XMLHttpRequest Object

For now, let’s discuss what an AJAX XMLHttpRequest Object is. It is an object that we use in AJAX that allows us to talk to a server behind the users back. This object is the sole reason we are allowed to make updates into the user’s page without forcing them to reload the entire page. An HTTP Request is actually sent out by your browser each time you type a website, which is then sent to a server that finally sends you back the web page. Of course, this happens right before your eyes and you know what it is doing. The XMLHttpRequest is very much like that, but it is very sneaky. The XML is simply a reference to the data structure that is being returned. Now, we can vent about Internet Explorer. Don’t get me wrong. I love Microsoft, but I absolutely hate the tyranny it has on developers. I will vent my anger more as we move through this tutorial.

Let’s make an XMLHttpRequest:

Example

var xmlhttp;
if (window.XMLHttpRequest)
{ // works with IE7+, Chrome, Firefox, Safari

xmlhttp=new XMLHttpRequest();

}
else
{ // works with IE6, IE5

xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

}

It is the else statement that annoys me about Internet Explorer. However, you can see that they now have jumped on the bandwagon and started using XMLHttpRequest. Now, we can start sending requests to the server.

To GET Or To POST?

I won’t go into much detail here, but GET is usually the best because it is faster. However, you might want to use POST when you are transferring a very large amount of data. GET actually has a limit to the maximum allowed size for a url.

We will only deal with the GET

Example

//PHP File
<?php

echo $_GET[‘sampleVar’];

?>
//end PHP File

//HTML File
<script type="text/javascript">
function doGET()
{

var xmlhttp;
if (window.XMLHttpRequest)
{

xmlhttp=new XMLHttpRequest();

}
else
{

xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

}
xmlhttp.onreadystatechange=function() //This part is actually executed last
{

if (xmlhttp.readyState==4 && xmlhttp.status==200) // Was the request processed successfully?
{

document.getElementById("sampleDiv").innerHTML=xmlhttp.responseText;

}

}
xmlhttp.open("GET","ajaxTest2.php?sampleVar=" + Math.random());
xmlhttp.send();

}
</script>
<button type="button1" onclick="doGET()">GET</button>
<div id="sampleDiv">Nothing is here</div>

Obviously, call the function doGet() by clicking our button1. In that function, we have the standard setting up of our xmlhttp variable, creating the actual XMLHttpRequest. Next, we skip over the xmlhttp.onreadystatechange=function().

When then prepare to send our request with xmlhttp.open(“GET”,”ajaxTest2.php?sampleVar=” + Math.random(),true);. Let’s break this down a little bit. The “GET” is the request type. The ajaxTest2.php is the url that we are going to talk with. After the separating ?, we have a variable, sampleVar that is equal, =, to our Math.random(). The Math.random() simply generates a random number between 1 and 0. We use this so that our changed page won’t be cached by the browser. Finally, we send the request with xmlhttp.send();.

Eventually, the xmlhttp.onreadystatechange=function() will fire when the request returns with data. In that function, we set our sampleDiv‘s content equal to our returned data, xmlhttp.responseText, which in this case is whatever our Math.random() is. As you can see, every time you click the button the Math.random() variable is sent to the PHP file that spits out the variable’s value into the sampleDiv container.