Django – AJAX

This post is part of my Django series. You can see an overview of the series along with instruction on how to get all the source code here.

This article assumes you are comfortable creating a Django project, can create apps and register them into the INSTALLED_APPS list of the settings file. If not please read my Django HelloWorld article.

This article assumes you have a project called DjangoSandBox with an application called ajaxintroduction.

Overview

In these examples are we are going to create a page which uses AJAX to GET and POST data between the server.

The page is based around a ‘Quote’ object which contains the quote and the author. We will provide a single page which has the following functionality:

  • Get all quotes for an author
  • Get a random quote
  • Create a quote.

The following examples are split out but in the repository this is a single page. I strongly urge you to work from the source code within the repository.

Initial Page

So before we start on the AJAX calls we need an initial page up and running.

First lets create our model.

#models.py
from django.db import models
from django.db.models import Model

class Quote(Model):
    quote = models.TextField()
    author = models.CharField(max_length=50)

    def __str__(self):
        return "{0}: {1}".format(self.author, self.quote)

Make and run the migrations:

python manage.py makemigrations ajaxintroduction
python manage.py migrate

Next is our view, currently we simply want to return our template:

#views.py

from django.shortcuts import render

def get_quotes(request):
    return render(request, "ajaxintroduction/random_quotes.html")

Next our template; nothing more than a heading currently.

<!-- templates/ajaxintroduction/random_quotes.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Daily Quote!</title>

    <style>
        span {
            display: block;
        }
        span span {
            display: inline;
        }
    </style>
</head>
<body>

<h1>AJAX Examples</h1>
</body>

Then we hook in our view into our URL routing configuration.

# urls.py
from django.conf.urls import patterns, url

from . import views

urlpatterns = 
    patterns('',
    url(r'^$', views.get_quotes, name="index"),
)

Now hook our application into our project URL routing configuration:

#DjangoSandBox/urls.py

from django.conf.urls import patterns, include, url

from ajaxintroduction import urls as ajax_urls

urlpatterns = 
    patterns('',
             url(r'^ajax/', include(ajax_urls, namespace="ajax")),
             )

To test run the development server and navigate to:

http://127.0.0.1:8000/ajax/

You should see the template page loaded with our heading.

Static Files

Next we are going to configure our static files:

  • JQuery which we use for performing AJAX calls in JavaScript
  • JQuery-Cookies which will use to grab the CSRF token from our cookie
  • A new js file which we will place all our required JavaScript code in

First create an empty text file in ajaxintroduction/static/ajaxintroduction/js/ called ajax-example.js

// ajaxintroduction/static/ajaxintroduction/js/ajax-example.js

// Currently empty

Next download JQuery and JQueryCookies. You can download them from the references below if you have not downloaded the repository code of my examples. Alternatively you can download the files directly from GitHub

Note: if you are not downloading the files from my repository ensure you file names match with regards to the versions throughout the examples.

Copy in jquery and jquery.cookie into and DjangoSandBox/static/js

We now need to register these files as being static files which can be served directly to the user.

Within the settings file register the paths of the static directory of the project as well as the application directory of our ajaxintroduction application.

# settings.py
STATIC_URL = '/static/'

STATICFILES_DIRS =  (
    os.path.join(PROJECT_ROOT, 'static'),
    os.path.join(PROJECT_ROOT, 'ajaxintroduction', 'static'),
)

Now are are going to reference all these static files in our html head.

  • Call “load staticfiles” to enable the use of static files in our template
  • Reference the file with the static template tag. Files are referenced relative to the composition of STATICFILES_DIRS/STATIC_URL:
    • For our project files we reference js/file.js
    • For our application files we reference ajaxintroduction/js/file.js

Note: similar to templates we duplicate the application name within the directory path of our application static files as a way of name spacing our files.

<!-- templates/ajaxintroduction/random_quotes.html -->
<head>
    {% load staticfiles %}

    <script src="{% static "js/jquery-2.1.4.js" %}"></script>
    <script src="{% static "js/jquery.cookie.js" %}"></script>
    <script src="{% static "ajaxintroduction/js/ajax-example.js" %}"></script>    
</head>

To test run the development server and navigate to:

http://127.0.0.1:8000/ajax/

You should be able to use FireBug or Developer Tools to view the contents of the JavaScript files which have been downloaded along side our generated HTML.

If you look at the HTML code you will see the file path of the static file has been completed as a relative URL from our website route prefixed with static; static/ajaxintroduction/js/ajax-example.js

Note: if the files have not been downloaded use FireBug or Developer Tools to check the network requests of these resource files. Check the URL of the request is as expected. Check the response. Try entering in the full URL of the resource file into the browser:

http://127.0.0.1:8000/static/ajaxintroduction/js/ajax-example.js

Get – A Random Quote

We are now going to create the functionality to get a random quote. First we create a view which gets a random Quote record. We return the record as JSON data using the inbuilt Python json library:

import json
context_data = {random_quote.author: random_quote.quote}
json.dumps(context_data)

We then return the JSON data via a HTTPResponse setting the content_type to “application/json”. Add the following view function:

#views.py
import json
from random import randint

from django.http import HttpResponse

from .models import Quote

def get_random_quote(request):
    random_number = randint(0, Quote.objects.all().count() - 1)

    random_quote = Quote.objects.all()[random_number]
    context_data = {random_quote.author: random_quote.quote}

    return HttpResponse(json.dumps(context_data), content_type="application/json")

We then create a simple button and a span element to display our random quote. Both require an id as this is how we will be finding the element via JQuery. Add the following into our template file.

<!-- templates/ajaxintroduction/random_quotes.html -->

<h2>Get Random Quote:</h2>
<span>
    <button type="button" id="getquote">Get:</button>
    <span id="quote"></span><span id="author"></span>
</span>

Note: the above should be added into our existing html template file and not replacing its contents.

We now hook up our button to our view which returns our random quote as JSON data within our JavaScript file:

// ajaxintroduction/js/ajax-example.js
$(document).ready(function () {
    $("#getquote").click(function () {
        getQuote();
    });
});

function getQuote() {
    $.getJSON("/ajax/random", function (data) {
        console.log("getQuote.response:");
        console.log(data);
        $.each(data, function (author, quote) {
            $('#quote').text(quote);
            $('#author').text(author);
        });
    });
}
  • The $(document).ready is a special JQuery function which only runs when the html page has finished loading within the browser. We use it to bind our getQuote function onto the click event of our button.
  • The getJSON function is used to make a call to our view via AJAX. The first parameter is a relative URL which we will configure up below in our URL routing configuration. The second parameter is a call back function which is passed our returned random quote as JSON data.
  • We use the JQuery each function to iterate and unpack our JSON data which we display within our span elements,

We now hook in our view to our URL routing configuration.

# urls.py
from django.conf.urls import patterns, url

from . import views

urlpatterns = 
    patterns('',
    url(r'^random/$', views.get_random_quote, name="random"),
)

To test run the development server and navigate to:

http://127.0.0.1:8000/ajax/

Pressing the button will return and display a random quote.

Note: if the AJAX request does not appear to work use FireBug or Developer Tools to check the request. Check the URL, the parameters and it’s status. To see any errors which might be on the actual AJAX view navigate to the URL of the AJAX request.

You can also navigate directly to the new view function via:

http://127.0.0.1:8000/ajax/random

Get Multiple

In our next example we are going to allow the retrieval of all quotes for an author.

First we change our initial page view to return a list of all distinct authors.

Note: SQLite3 does not support the distinct SQL command so we use the Python set collection to create a distinct list of authors.

Secondly we create a new view which looks up all quotes for an author which we will pass in as a GET parameter. We return the quotes as a QuerySet.

The Django QuerySet is not serializable via the inbuilt Python json library. Django provides the serializers class which can.

#views.py
import json
from random import randint

from django.core import serializers
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render

from .models import Quote

def get_quotes(request):
    authors = set(r.author for r in Quote.objects.all())

    return render(request, "ajaxintroduction/random_quotes.html", context={"authors": authors})


def get_author_quotes(request):
    if "author" not in request.GET or request.GET["author"] == "all":
        quotes = Quote.objects.all()
    else:
        author_name = request.GET["author"]
        quotes = Quote.objects.filter(author=author_name)

    return HttpResponse(serializers.serialize('json', quotes), content_type="application/json", )

We next now create our UI. This will consist of a choice list of the authors, a button and a span element for displaying the results.

<!-- templates/ajaxintroduction/random_quotes.html -->

<h2>Get Quotes By Author:</h2>
<span>
    <select id="authors" title="Fpop dfic">
        <option value="all">All</option>
        {% for author in authors %}
            <option value="{{ author }}">
                {{ author }}
            </option>
        {% endfor %}
    </select>
    <button type="button" id="getAuthorQuotes">Get</button>
</span>
<span id="quotesbyauthor"></span>

Now our JavaScript; first hook our function onto our button within the JQuery document ready function.

The only real difference between our call to getJSON in the previous example is that we pass in the selected author from the select box as a GET parameter. GET parameters are constructed from key value pairs represented by a JSON string.

Again we use the JQuery function ‘each’ to loop through all quotes unpacking them into a function as key value pair. We construct a series of list elements and add them into our span element.

// ajaxintroduction/js/ajax-example.js
$(document).ready(function () {
    $("#getAuthorQuotes").click(function () {
        getAuthorQuotes();
    });
});

function getAuthorQuotes() {
    $.getJSON("/ajax/author/", {author: $('#authors').val()}, function (data) {
            console.log("getAuthorQuotes.response:");
            console.log(data);

            var $quotesbyauthor = $('#quotesbyauthor');
            $quotesbyauthor.text("");

            var items = [];

            $.each(data, function (key, value) {
                items.push("<ul>" + value.fields["quote"] + ". " + value.fields["author"] + "</ul>");
            });

            $("<ul/>", {
                "class": "quotes",
                html: items.join("")
            }).appendTo($quotesbyauthor);
        }
    );
}

Now we simply need to hook in our view into our URL routing configuration.

# urls.py
from django.conf.urls import patterns, url

from . import views

urlpatterns = 
    patterns('',
    url(r'^author/$', views.get_author_quotes, )

To test run the development server and navigate to:

http://127.0.0.1:8000/sessionsandcookies/ajax/

You can now ask for all quotes for an author. If you cannot get this to work check the requests being made along with the results. Try navigating to the URL directly.

Post -Create A Quote

There is no real fundamental difference between a HTTP POST or a GET. The method is used as a status; both can contain URL parameters and both can contain a body.

It is advisable that GET requests should never perform CRUD operations. We will use a POST to create our Quote record.

We are going to allow the user to create a quote asynchronously from our page. We will create a new view function which takes our quote and author as strings, ensures they are set and then attempts to create the quote. We will use get_or_create to ensure we don’t create duplicate quotes.

We simply use request.POST[“XXX”] to get our form element value on the server side. For more complicated examples you should think about writing a dedicated Django model form.

We then return an indication of whether the quote was created, a validation message and also the new number of quotes in the database. We return the data as JSON but using the JsonResponse; this will automatically serialise the data to JSON as well as setting the content type of the response to JSON.

# views.py
import json
from random import randint

from django.core import serializers
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render

from .models import Quote

# @csrf_exempt # Use for debugging only.
def new_quote(request):
    message = ""

    is_valid = True
    created = False

    if "quote" not in request.POST or "author" not in request.POST:
        message = "Invalid post data"
        is_valid = False

    if request.POST["quote"] == "" or request.POST["author"] == "":
        message = "Please provide a quote and an author"
        is_valid = False

    if is_valid:
        quote, created = Quote.objects.get_or_create(quote=request.POST["quote"], author=request.POST["author"])

        if created:
            message = "Quote Created"
        else:
            message = "Quote already exists"

    data = {"count": Quote.objects.all().count(), "message": message, "created": created}

    return JsonResponse(data)

We now add a form onto our template which will be used to capture the data required to create our Quote record. We also add a button. We include a csrf_token in our form to prevent from cross site forgery attacks.

<!-- templates/ajaxintroduction/random_quotes.html -->

<h2>Create Quote:</h2>
<form method="post" action="">
    {% csrf_token %}
    <table>
        <tr>
            <th>Quote</th>
            <th>Author</th>
        </tr>
        <tr>
            <td><input type="text" id="txtquote"/></td>
            <td><input type="text" id="txtauthor"/></td>
        </tr>
    </table>
    <button type="button" id="newquote">New Quote</button>
</form>

We now hook in our JavaScript; this is where it starts to get a bit tricky as we need to post back our csrf_token as part of the POST data.

Django writes the token value to a cookie called csrftoken which we can access in JavaScipt via the JQuery-Cookies library. We hooked this file in above as a static file. We should only include this if our HTTP method is not one of GET, HEAD, OPTIONS or TRACE. We set the token in the X-CSRFToken HTTP request header parameter. We use the JQuery ajaxSetup function to do this.

If you want to test posting back without Django validating the presence and validity of the token you can decorate your view with the @csrf_exempt decorator. This should only be used for testing/development purposes.

We then call our new view URL passing in the data of the new quote we would like to create.

We then display our validation message and the new count of elements.

// ajaxintroduction/js/ajax-example.js
function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}

$.ajaxSetup({
    beforeSend: function (xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", $.cookie('csrftoken'));
        }
    }
});

$(document).ready(function () {
    $("#newquote").click(function () {
        createNewQuote();
    });
});

function createNewQuote() {
    $.ajax({
        type: "POST",
        url: "/ajax/new/",
        data: {
            'quote': $('#txtquote').val(),
            'author': $('#txtauthor').val()
        },
        success: function (data) {
            console.log("createNewQuote.response:");
            console.log(data);

            alert(data.message);

            if (data.created) {
                alert("There are now " + data.count + " quotes");
            }
        }
    });
}

The last thing we need to do is to hook our new view into our URL routing configuration.

# urls.py
from django.conf.urls import patterns, url

from . import views

urlpatterns = 
    patterns('',
    url(r'^new/$', views.new_quote, name="new"),
)

To test run the development server and navigate to:

http://127.0.0.1:8000/sessionsandcookies/ajax

##References## {#References}

JQuery Cheat Sheet

A cheat sheet for JQuery.

All source code can be found on GitHub here.

This post is part of my cheat sheet series.

 


// ******** JQUERY SELECTORS ********

// Selectors
$('#id');			// html id
$('a');				// html tag
$('.cssclass');			// css class
$('#navigationBar a'); 	    	// descendants
$('#body > a'); 		// child nodes
$('#h2 + div');			// adjacent siblings

// Compounds selections
= is exactly equal
!= is not equal
^= is starts with
$= is ends with
*= is contains
id
name
href

// Attribute Selectors
$('img[alt]');			// has attribute set
$('input[type=text]');		// has attribute value equal to
$('a[href^=http://]');		// has attribute value starting with
$('a[href$=.pdf]');		// has attribute value ending with
$('a[href*=google.com]'); 	// has attribute value containing

// Filters
$('tr:even');			// even elements
$('.strippedTbl tr:even');	// even elements
$('.strippedTbl tr:odd');	// odd elements
$('a:not(.myClass)');		// elements with exclusion filter
$('a:not([href^=http://])');	// elements with exclusion filter
$('li:has(a)');			// elements with inclusion filter
$('a:contains(Click Me!)');	// elements with inclusion text
$('div:hidden').show();		// elements with hidden filter

// ******** METHODS ********
$('.foo').show().width(300);	// Inline chaining
$('.foo').show()				// Multi line chaining
	.width(300)
	.height(300);

$('.foo').html();			// replaces Javascript innerHtml
$('.foo').html = '<br>';		// replaces Javascript innerHtml
$('.foo').text = '<br>';		// encodes html (to show code in html)

// Adding and replacing page content
$('.foo').append('<br>')	// adds as last child element of selected element
$('.foo').prepend('<br>')	// adds as first child element of selected element
$('.foo').before('<br>')	// adds element before
$('.foo').after('<br>')		// adds element aftter
$('.foo').remove()		// removes element
$('.foo').replace('<br>')	// replaces element
$('#AnID tbody:last').append("<tr><td></td></tr>"); // Add html into a section

// Setting and Reading Tag Attributes
$('.foo').addClass('class')		// adds CSS Class
$('.foo').removeClass('class')	    	// remove CSS Class
$('.foo').toggleClass('class')	    	// toggle add/remove CSS Class
$('.foo').css('background-colour')	// Get CSS property.
$('.foo').css('font-size', '200%')	// Set CSS property.
$('.foo').css({
			'background-colour' : '#FF0000',
			'font-size' : '200%'
			});								// Set multiple CSS properties.

// Reading, setting and removing HTML Attributes
$('img').attr('src')			// Get attribute
$('img').attr('src', 'foo.jpg');	// Set attribute
$('img').removeAttr('src');		// Remove attribute
$('img').fadeOut();			// Set attribute

// Examples
$("input[type=text]").val('');							// All text items
$("input[id^=ProductWrapperName][value='Foo']").get(0).id 			// Starts with and has value
$("input[id^=ProductWrapperProductType][value='" + productType + "']").get(0) 	// Starts with and has value
$("input[id^=TrustP][id$=Trustee][value='Yes']").size(); 			// Starts with and ends with and value
$("text[id^=ProductWrapperName]:contains('Foo')")  				// Text box id starts with html contains
$('#chktable' + asTable + 'Match' + jnRecordRow + ':checked').val() != null 	// Element is checked
$('#contributionsInputPanel input').val('');					// Id and input
$("#myid").length > 0								// Element by Id exists
$("#input").val("Hello");							// Set value
$("#input").val();								// Get value
$('#' + prefix + 'CrystallisedRegularIncomeRadioNo').attr("checked", true );    // Check item
$("input[name=DiscardOption]:checked").val();					// Item is checked
$(".selector").attr("checked", false); 						// Check item
$("input[name='Thirdpartytype1']:checked").val();				// Item is checked
$("input").attr("readOnly", true); 						// Set readonly
$("input").removeAttr("readOnly");						// Remove readonly
$("input").attr("disabled", true); 						// Disable
$("input").attr("disabled", ''); 						// Remove readonly
$("select").removeAttr("disabled");
$("input").show();
$("input").hide();

// ******** LOOPS *********

$('img').each(functionName);		// Named function
$('img').each(function(){		// Anon function
	this				// old school element
	$(this)				// jquery element
	});

var myData = { firstName: 'Bob', lastName:, 'Smith'};
$('#foo').bind('click', myData, functionName);
var fname = evt.data.firstName;
$('#foo').bind('click', functionName);

// ******** EVENTS ********
// Registered as functions (see each above)
// Mouse Events
$('.foo').click(functionName);			// called upon release
$('.foo').dblclick(functionName);		// called upon second release
$('.foo').mousedown(functionName);		// called upon left click down
$('.foo').mouseup(functionName);		// called upon release
$('.foo').mouseover(functionName);		// called when mouse enters area
$('.foo').mouseout(functionName);		// called when mouse leaves area
$('.foo').mousemove(functionName);		// called when mouse moves

// Document / window Events
$(document).load(functionName);			// called after everything loaded; ready better
$(window).resize(functionName);			// called upon release of resize (not always)
$(window).scroll(functionName);			// called upon release of scroll (not always)
$(window).unload(functionName);			// called upon exit (not always)

// Form Events
$('.foo').submit(functionName);			// called upon submit of form
$('.foo').reset(functionName);			// called upon reset of form
$('.foo').change(functionName);			// called entity change
$('.foo').focus(functionName);			// called entity focus recieved
$('.foo').blur(functionName);			// called entity focus released

// Keyboard Event
$('.foo').keypress(functionName);		// called upon key release
$('.foo').keydown(functionName);		// called upon key down
$('.foo').keyup(functionName);			// called upon key release

// JQuery Events

// You can chain events
$(document).ready(functionName)			// Called when javascript manimulation should be made
$('#id').hover(showFunc, hideFunc)		// Encompas mouseover and moustout events
$('#id').toggle(togOffFunc, togOffFunc)		// Encompas toggle on and off functions

// Event object
$(document).click(function(evt){});		// Passed into events
evt.pageX;				        // distance from mouse pointer to left page edge
evt.pageY;				        // distant from mouse poiner to top page edge
evt.screenX;			                // distance from mouse pointer to monitor edge x
evt.screenY;			                // distance fom mouse pointer to monitor edge y
evt.shiftKey;			                // boolean indicating if shift key press *
evt.which;				        // numeric code of key press
evt.target;				        // element bound upon
evt.data;					// data passed in with bind method

String.fromCharCode(evt.which);			// * Get char from key code

// Stoppnig and removing events
evt.preventDefault();				    // prevents other events getting raised
return false;					    // shorthand of preventDefault
evt.stopPropagation();				    // Prevents parent elements recieving bubble events
$(document).unbind('click')			    // remove registered events

JavaScript Cheat Sheet

A cheat sheet for JavaScript.

All source code can be found on GitHub here.

This post is part of my cheat sheet series.

<pre>
// Java Script Basics
document.write("
Hello!
");
name = prompt ("Please Enter Your Name.","Your Name Goes Here");

// ******** ARRAYS ********
var foo = [1,2,3];
var foo = new Array( 1,2,3);
foo[2];
foo[2]=3;
foo.length;
foo.push(4);  					// adds an element at the end
foo.push(5,6,7) 				// can take more than one element
foo.unshift(0); 				// adds an element at the beginning
var lastEl = foo.pop(); 		        // gets and removes last element
var firstEl = foo.shift(); 		        // gets and remove first element
var array.splice(index,howMany,e1,e2,ex) 	// adds and or removes elements. Returns remove elements
document.write(arrayFoo); 		        // writes comma separated to documented
foo.concat()  					// joins two or more arrays, and returns a copy of the joined arrays
foo.join() 					// joins all elements of an array into a string
foo.reverse() 					// reverses the order of the elements in an array
foo.slice() 					// Selects a part of an array, and returns the new array
foo.sort() 					// sorts the elements of an array
foo.toString() 					// converts an array to a string, and returns the result
foo.valueOf() 					// returns the primitive value of an array

// ******** LOOPS ********

for (i=0;i<=5;i++){}   		// for
while (i<=5){i++;}		// while
do{i++;} while (i<=5);		// do while
for (x in foo) {foo[x]};	// for in
break; 				// stop loop
continue; 			// continue next iteration

// ******** TRY CATCH THROW ********

try {	} catch(err) {	txt = err.description; }
try {	throw "Err1"; } catch(er)
{
  if(er=="Err1")
  {	alert("Error! The value is too high");
  }
}

// ******** CHARACTERS / STRING ********
// Escape characters
var txt="We are the so-called "Vikings" from the north.";

"\'"  	// single quote
"\"" 	// double quote
"\&" 	// ampersand
"\\" 	// backslash
"\n" 	// new line
"\r" 	// carriage return
"\t" 	// tab
"\b" 	// backspace
"\f" 	// form feed

"".charAt() 				// Returns the character at the specified index
"".charCodeAt() 	 		// Returns the Unicode of the character at the specified index
"".concat() 				// Joins two or more strings, and returns a copy of the joined strings
"".fromCharCode() 		        // Converts Unicode values to characters
"".indexOf() 				// Returns the position of the first found occurrence of a specified value in a string
"".lastIndexOf() 			// Returns the position of the last found occurrence of a specified value in a string
"".match() 				// Searches for a match between a regex and a string, and returns the matches
"".replace() 				// Searches for a match between a substring (or regex) and a string, and replaces
"".search() 				// Searches for a match between a regular expression and a string, and returns the position of the match
"".slice() 				// Extracts a part of a string and returns a new string
"".split() 				// Splits a string into an array of substrings
"".substr() 				// Extracts the characters from a string, beginning at a specified start position, and through the specified number of character
"".substring() 				// Extracts the characters from a string, between two specified indices
"".toLowerCase() 			// Converts a string to lowercase letters
"".toUpperCase() 			// Converts a string to uppercase letters
"".valueOf() 				// Returns the primitive value of a String object

// ******** DATE / TIME ********
today = new Date()
d1 = new Date("October 13, 1975 11:13:00")
d2 = new Date(79,5,24)
d3 = new Date(79,5,24,11,33,0)
myDate.setFullYear(2010,0,14)
myDate.setDate(myDate.getDate()+5);

getDate() 			// Returns the day of the month (from 1-31)
getDay() 			// Returns the day of the week (from 0-6)
getFullYear() 			// Returns the year (four digits)
getHours() 			// Returns the hour (from 0-23)
getMilliseconds() 	        // Returns the milliseconds (from 0-999)
getMinutes() 			// Returns the minutes (from 0-59)
getMonth() 			// Returns the month (from 0-11)
getSeconds() 			// Returns the seconds (from 0-59)
getTime() 			// Returns the number of milliseconds since midnight Jan 1, 1970
getTimezoneOffset() 	 	// Returns the time difference between GMT and local time, in minutes
Date.parse(datestring)		// Parse
setDate()  			// Sets the day of the month (from 1-31)
setFullYear() 			// Sets the year (four digits)
setHours() 			// Sets the hour (from 0-23)
setMilliseconds() 	        // Sets the milliseconds (from 0-999)
setMinutes() 			// Set the minutes (from 0-59)
setMonth() 			// Sets the month (from 0-11)
setSeconds() 			// Sets the seconds (from 0-59)
setTime() 			// Sets a date and time by adding or subtracting a specified number of milliseconds to/from midnight January 1, 1970
toDateString()  		// Converts the date portion of a Date object into a readable string
toDateString()  		// Converts the date portion of a Date object into a readable string
toGMTString() 			// Deprecated. Use the toUTCString() method instead
toLocaleDateString() 		// Returns the date portion of a Date object as a string, using locale conventions
toLocaleTimeString() 		// Returns the time portion of a Date object as a string, using locale conventions
toLocaleString() 		// Converts a Date object to a string, using locale conventions
toString() 			// Converts a Date object to a string
toTimeString() 			// Converts the time portion of a Date object to a string

// ******** NUMBER ********

Number.NaN
toExponential(x)  	 	// Converts a number into an exponential notation
toFixed(x) 			// Formats a number with x numbers of digits after the decimal point
toPrecision(x) 			// Formats a number to x length
toString() 			// Converts a Number object to a string
valueOf() 			// Returns the primitive value of a Number object

// ******** MATH ********

// Math.Constants
E 				// Returns Eulers number (approx. 2.718)
LN2 				// Returns the natural logarithm of 2 (approx. 0.693)
LN10 			     	// Returns the natural logarithm of 10 (approx. 2.302)
LOG2E 			    	// Returns the base-2 logarithm of E (approx. 1.442)
LOG10E 		        	// Returns the base-10 logarithm of E (approx. 0.434)
PI 				// Returns PI (approx. 3.14159)
SQRT1_2 	        	// Returns the square root of 1/2 (approx. 0.707)
SQRT2 			    	// Returns the square root of 2 (approx. 1.414)

// Math.Methods
abs(x) 				// Returns the absolute value of x
acos(x) 			// Returns the arccosine of x, in radians
asin(x) 			// Returns the arcsine of x, in radians
atan(x) 			// Returns the arctangent of x as a numeric value between -PI/2 and PI/2 radians
atan2(y,x) 			// Returns the arctangent of the quotient of its arguments
ceil(x) 			// Returns x, rounded upwards to the nearest integer
cos(x) 				// Returns the cosine of x (x is in radians)
exp(x) 				// Returns the value of Ex
floor(x) 			// Returns x, rounded downwards to the nearest integer
log(x) 				// Returns the natural logarithm (base E) of x
max(x,y,z,...,n) 		// Returns the number with the highest value
min(x,y,z,...,n) 		// Returns the number with the lowest value
pow(x,y) 			// Returns the value of x to the power of y
random() 			// Returns a random number between 0 and 1
round(x) 			// Rounds x to the nearest integer
sin(x) 				// Returns the sine of x (x is in radians)
sqrt(x) 			// Returns the square root of x
tan(x) 				// Returns the tangent of an angle

// ******** GLOBAL *******

// Properties
Infinity 			// A numeric value that represents positive/negative infinity
NaN 				// "Not-a-Number" value
undefined 			// Indicates that a variable has not been assigned a value

// Functions
decodeURI() 		    	// Decodes a URI
decodeURIComponent() 		// Decodes a URI component
encodeURI() 			// Encodes a URI
encodeURIComponent() 		// Encodes a URI component
escape() 			// Encodes a string
eval() 				// Evaluates a string and executes it as if it was script code
isFinite() 			// Determines whether a value is a finite, legal number
isNaN() 			// Determines whether a value is an illegal number
Number() 			// Converts an object's value to a number
parseFloat() 			// Parses a string and returns a floating point number
parseInt() 			// Parses a string and returns an integer
String() 			// Converts an object's value to a string
unescape() 			// Decodes an encoded string