Javascript - Data Storage

Data Storage in Javascript - The Why and How

First, when you think of Javascript you must think contextually where you are. Javascript runs in the end users browser. If you are are doing web development you musy always remember that you are serving your web pages up to your end users from a remote server. Javascript runs within the browser on the end users local machine (pc, mac, laptop, iPad, smart phone, etc...).

Next, it is important to understand that the http protocol is inherently stateless. What this means is that you want to send the end user everything you think they need in the exchange. For example, if you have a form on the page you are sendin them, you likely want to send the scripts that are needed to validate the form. By doing this you save the round trip back to the server.

There will be times where you will want to send data to the end user that is not viewable, but is essential to the webpage itself.

Introduction to Object Literals

In the examples that follow it is my intent to walk you through such a scenario. Along the way we will employ good coding practives.

Javascript in Action

JAVASCRIPT/HTML - Data Wrapper Code

Javascript code in head section

var dataWrapper = {
	lowrangeF: '97',
	highrangeF: '103.7'
};	

function procForm1() { alert("lowrangeF is " + dataWrapper['lowrangeF'] + 
                       "  highrangeF is " + dataWrapper['highrangeF']); }

function modify_lowrangeF(a) {
  dataWrapper['lowrangeF'] = a;
  procForm1();
}


Html code

<form name="form1" id="form1" method="POST" action="javascript_objects_101.php">
	<input type="button" value="show me" onclick="procForm1()"  />
</form>	

Syntax to Consider Before Continuing

In looking over the variable name dataWrapper there are a few points that need to be made. First, I am using a scripting technique called JSON (Javascript Object Notation). Within this variable I have place what are called object literals and set their values.

I have also created a function named procForm(). As you can see by running the script I am displaying the two values. The general syntax for referencing an object literal is ...

  Syntax to reference an object literal: ~~var_name~~['~~object_literal_name~~']

As a final point of clarification, in the world of technology we like to throw around different names and buzzwords. Sometimes, these names mean these same thing as the old names we know and love. Sometimes they are a far cry different. Personally, I think you can think of the variable named dataWrapper as a javascript object. This object is a container that holds two variables.

JAVASCRIPT - Modifying an Object Literal

Initially I had a hard time getting my head around the term "object literal." In a programming language I can declare a literal and set its value to a literal. But, I kept equating this term to a constant. Maybe it is because when I am working in a language that does not have a constant I can easily create a semantic one by declaring a variable, setting its value to a literal without the intent to ever change it (except in code, by re-coding it to a new desired value).

Javascript in Action

If you go back to the original button and click it you will see that the value has indeed changed. If that is not a variable I am not sure what is :-).

Javascript code in head section

function modify_lowrangeF(a) {
  dataWrapper['lowrangeF'] = a;
  procForm1();
}

Persistance of Javascript data in the browser

The value will remain 96.5 until the user refreshes the browser. I mention this as it is a VERY IMPORTANT point in context to this example!

JAVASCRIPT - Practical Javascript Object Use

So far the toycode presented explains some syntax. But, so what? Well, suppose we have a field on our form where the end user enters a temperature in fahrenheit. Our goal is to check the value before submitting the form back to the server. Further suppose that our form is part of a healthcare application. We want to add some measure of assurance that the data we are storing in our database is quality data.

We also want to discover data entry errors in the browser and not back at the server. We want to localize our form checking to minimize network traffic and server load. Maybe in this simple example that might not seem like such a big deal. But, when one needs to scale applications that are more robust and can have thousands of concurrent users every millisecond and byte of network bandwidth matters!

Javascript Variables are Objects

For that matter javascript functions are also objects. But, that is a matter for a different time.

If you are already experienced in object oriented or object based programming this is really an important thing to understand. If this is your first foray into object programming your mind is clear in terms of what objects are and how they behave. Of course, you still need to overcome that while javascript may look like structured programming on the surface, it really is not.

What is really cool is the javascript variables can hold three things.

  • Literal data (var foo = "bar";)
  • Other Variable (called object literals)
  • Functions

Morphing and enhancing our javascript variable

Javascript in Action

In this new version we not only have our two object literals, we also have a function to evaluate a user entered number, determine if the value is "in range" and produce the appropriate outcome. If the value is "in range" the form will be submitted.

There is a great deal new to cover. Lets get started.

First, we should take a look at the code.

Javascript code in head section
var objWrapper = {
	 lowrangeF: 93,
	highrangeF: 110,
	checkFval: function(a) {
		if (a > this['lowrangeF'] && a < this['highrangeF']) {
		   document.forms['form3'].submit();  
   	}
    //i come first or below conditional will trigger when field is left blank
    else if (a === '') {
    	 alert ("Enter data in field before submitting");
    }	
    else if (a < this['lowrangeF']) {
    	 alert (a + " is out of range. Low.");
    }	
    else if (a > this['highrangeF']) {
    	 alert (a + " is out of range. High.");
    }
      
	}	
};

I morphed the pervious variables code contained in the variable dataWrapper into a new variable named objWrapper. What is different about this is I have added added new object literal namded checkFval. But as you can see this is not a variable that hold data it is actually a function. We are going to use this function to check the data value the user enters.

First, I want to to pause and take note about what all this means. The ability to contain code and data within the same construct (in this case a javascript variable) is pretty cool and very powerful. Allowing this degree of encapsulation is a very nice feature of this language. Javascript is one of the most loathed and derided languages on the face of the earth. This is not for many good reasons. Yet, if we can learn to program in this language in a manner than utilizes its strength then maybe life does not have to be so bad after all?

Next lets see how we invoke the function within our variable.

Html code
	<input type="button" value="show me" onclick="objWrapper.checkFval(Fval.value);"  />	

The function I coded within the variable objWrapper works the same as if we had coded it as a standalone function. How we call the function is a little different as you can see. We invoke the function by referencing the variable name followed by the dot operator followed by the function contained within our variable. also note we are passing in the value of our text box using the same type of Notation and a standard javascript object literal named value.

Looking at the conditional I want to point out that I am first evaluating for an end user condition I expect to be the predominant case. I make a point of this as I typically build larger scale enterprise software. It is little things like this that can really make a difference as you scale applications.

Next, I trap the user submitting the form without entering any data. If you swap the second and third conditional you will find that we never reach the conditional that returns the string ""Enter data in field before submitting." In fact, if you were to enter a space in the field and submit the form you will find the what is returned is "...is out of range. Low." alert! This is because the evaluation is against no value. A space is a value. Sometimes nothing can be something. A more important point is bullet-proofing a user interface is easier said than done. That is a topic for a different time.

what is this?

Notice that within our function we reference our two object literals using the keyword "this." Since our object is the variable named objWrapper we can reference any item within the object by use of the "this" keyword. "this" actually refers to objWrapper.

By now you hopefully have plugged in various numbers to exercise this function. I also want to point out that even though our html markup for the third form has the method and action arguments that these done not get invoked until we enter a value that falls between acceptable range. We are actually posting the page back to the server only when the appropriate data has been entered.

You now have some theory, some decent syntax, and an example you can use and expand upon. Javascript can be very useful for form checking prior to form submission back to the server. Typically you would submit html content back to the server to a Php or a CGI handler. You could easily turn this page into a php page.

Download code for this example

You do not want to right click and view the code to see what I am doing under the hood as you will also have to deal with all the framework code for this website. Instead click to download the example you have just gone through.

download file

About the Server Call

I discussed the server call. I have a link here to the Php page that has the same code as you have been working with. The only difference is that I am trapping the call and echoing back the variable at the top of the page. you can run through the scenarios again and see that the server only gets called when you enter a value within the allowable range. This example done in Php.

DISCLAIMER: The example though somewhat realistic in nature does not take into the account that these are typical temperature ranges for someone that is alive. Further, it does not take into account extreme and rare cases where core body temperatures can exceed these threshholds but the patient is still alive. I mention these things in case a Doctor or Nurse is thinking of giving me a bad time :-).


If you find this site useful and are a book buyer/reader...

Abe Books is one of my affiliates. I only use affiliates that I also purchase products from. I love Abe books. I have purchased many books from them originally cost $40 to $60 for as little as $5 to $10 dollars including shipping costs.

By accessing Abe books and clicking on one of my links I receive a small commission on your purchase that helps pay for this site. You pay no more for your books than if you accessed their site directly. Thanks for your support.

I have found Javascript - The Good Parts to be an indespensible resource

Click on the book to find books on Javascript at Abe Books...

If you would like a new version of the book click below to buy it from Amazon (also one of my affiliates).

Javascript Examples

Basics

Forms

Misc













navTango.com free

75% of your donation

goes to charity.