Much to every developers pain we often find that JavaScript that is functional in one browser is not functional in other browsers.  Recently the update to Safari 3 requrired that the window open command to not contain the url. As it would fail to open a window if it did, the simple fix was to create a new window with no url and set the url after creating the window. However as other brothers do not require this we can set up a two step process in that we try to open the window normally and if it fails then we open one with no url defined.

function create_popup( url, win_title, win_options )
{
  var popWin = window.open( url, win_title, win_options );
  if( !popWin ) {
    popWin = window.open('', win_title, win_options);
    popWin.location.href = url;
  }
}
popWin
, ,

The standard approach to submit a form is through the use of the submit button. However we may find that we may want to utilize an image, text link or other elements to submit a form. In these cases we can utilize JavaScript to submit the form for us through the use of the JavaScript form object.

When your html page contains a form then a form object is created in your document that can be accessed by its name.  The form object contains both the submit and reset functions. To access the form object we use the notation document.FORM_NAME.

Examples

HTML Form

<form name='mailForm' method="POST">
   // form contents
</form>

JavaScript Form Submit

<a href="javascript: document.mailForm.submit()">Send mail</a>

JavaScript Form Reset

<a href="javascript:  document.mailForm.reset()">Clear</a>

Javascript Method

<SCRIPT language="JavaScript">
  function sendEmail ()
  {
     document.mailForm.submit();
  }
</SCRIPT>
 
<a href="javascript: sendEmail()">Send mail</a>
, ,

This short tutorial shows how to access Stock Information from Yahoo Finance through an AJAX call utilizing JSONP. For the tutorial the following information is required.

  • JQuery - Javascript library with built in AJAX and JSONP functions
  • YahooFinanceAPI - PHP library that utilizes Yahoo Finance to return stock information from an underlying call to download.finance.yahoo.com/d/qutoes.csv – Please note that you can utilize this library to create your own web page that will return various stock information. For the purpose of the example we will be accessing a url on my server to showcase the cross domain capability.

Step 1: Create a sample html page that includes the JQuery library

<!DOCTYPE HTML PUBLIC
   "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <script src="http://code.jquery.com/jquery-latest.js"/>
  </head>
  <body>
    <div id="quote">
 
    </div>
  </body>
</html>

Step 2: Create the table that will hold the stock information returned by the AJAX call

<table cellspacing="0" cellpadding="3" border="1">
  <tr>
    <th>Symbol</th>
    <th>Last Trade</th>
    <th>Last Trade Time</th>
    <th>Change</th>
    <th>Open</th>
    <th>Previous Close</th>
    <th>Day's Low</th>
    <th>Day's High</th>
    <th>Volume</th>
  </tr>
  <tr>
    <td id="symbol"></td>
    <td id="lastTrade"></td>
    <td id="lastTradeTime"></td>
    <td id="change"></td>
    <td id="open"></td>
    <td id="previousClose"></td>
    <td id="daysLow"></td>
    <td id="daysHigh"></td>
    <td id="volume"></td>
  </tr>
</table>

Step 3: Define the JQuery JavaScript code that will call make an AJAX call for the specified stock information

  1. Create the document ready function so the JavaScript is not called until the page is loaded.
    $(document).ready(function(){
    });
  2. perform the AJAX call for JSONP data using the getJSON function of JQuery
    $.getJSON(
      "http://mdbitz.com/testing/PHPYahooFinance/finance.php?symbol=DELL&amp;callback=?",
      function( data ) {
      }
    );
  3. Output the returned data to the appropriate cells of the Table.
    $("#symbol").text( data.symbol );
    $("#previousClose" ).text( data.previousClose );
    $("#open" ).text( data.open );
    $("#lastTrade").text( data.lastTrade );
    $("#lastTradeTime").text( data.lastTradeTime );
    $("#change").text( data.change );
    $("#daysLow").text( data.daysLow );
    $("#daysHigh").text( data.daysHigh );
    $("#volume").text( data.volume);

Step 4: View your sample page

Symbol Last Trade Last Trade Time Change Open Previous Close Day’s Low Day’s High Volume
DELL 16.13 10.19AM +0.31 15.77 15.82 15.75 16.20 7162443

Full Sample HTML Source

<!DOCTYPE HTML PUBLIC
  "-//W3C//DTD HTML 4.01 Transitional//EN"
  "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <script src="http://code.jquery.com/jquery-latest.js"></script>
    <script>
      $(document).ready(function(){
        $.getJSON("http://mdbitz.com/testing/PHPYahooFinance/finance.php?symbol=DELL&callback=?",
          function(data){
            $("#symbol").text( data.symbol );
            $("#previousClose" ).text( data.previousClose );
            $("#open" ).text( data.open );
            $("#lastTrade").text( data.lastTrade );
            $("#lastTradeTime").text( data.lastTradeTime );
            $("#change").text( data.change );
            $("#daysLow").text( data.daysLow );
            $("#daysHigh").text( data.daysHigh );
            $("#volume").text( data.volume);
          }
        );
     });
     </script>
  </head>
  <body>
    <div id="quote">
      <table cellspacing="0" cellpadding="3" border="1">
        <tr>
          <th>Symbol</th>
          <th>Last Trade</th>
          <th>Last Trade Time</th>
          <th>Change</th>
          <th>Open</th>
          <th>Previous Close</th>
          <th>Day's Low</th>
          <th>Day's High</th>
          <th>Volume</th>
        </tr>
        <tr>
          <td id="symbol"></td>
          <td id="lastTrade"></td>
          <td id="lastTradeTime"></td>
          <td id="change"></td>
          <td id="open"></td>
          <td id="previousClose"></td>
          <td id="daysLow"></td>
          <td id="daysHigh"></td>
          <td id="volume"></td>
        </tr>
      </table>
    </div>
  </body>
</html>
, , , ,

JavaScript Object Notation or JSON for short is a data interchange format commonly used in AJAX Web Applications. The format is human readable and can represent simple data structures and Objects by use of associative arrays.

Syntax Formatting

The JSON format is lightweight in that the properties of the JSON Data Object are encoded by  curly braces. And the properties of the object are represented by key-value pairs delimited by the colon character and separated by a comma. In addition to an array value is defined by square brackets that can contain objects or values. Using these basic building blocks you are able to represent complex data.

Basic Examples

Example 1: Stock Information

{
    "symbol":"DELL",
    "open":"14.23",
    "lastTrade":"13:85"
}

Example 2: A Book Object with title, isbn, and author(s)

{
    "title": "First Lord's Fury",
    "isbn": "102304312",
    "authors": [
                 { "fullName": "Jim Butcher", 
                   "lastName":"Butcher", 
                   "firstName":"Jim" 
                 }
               ]
}

JSONP for cross Domain JSON Data

JavaScript Object Notation with Padding (JSONP) is a method that a server can implement for allowing other sites to access and utilized data from your server. Do to browser security it is not possible to access JSON data directly from a remove server. JSONP resolves this issue by allowing the caller to pass in a callback function that the JSON data gets wrapped in so that the data is executed by your defined function. The really nice element of this is that JQUERY and other JS libraries already contain AJAX support for you to easily create these calls.

JSONP server response format

For JSONP to function the server must except a parameter to be used as the callback function in addition to any data it needs to obtain the requested information.

http://www.example.com/?callback=XYZ

What the server needs to do is take the callback parameter and wrap the json data in a call to the callback function as:

XYZ( JSON-DATA )

That is all there is to it.

, , , ,

Overview

A very important element of any website is its navigation or menu, and a good website has a non-obtrusive but prominent one that the user knows intuitively to interact with. A common menu technique I use is having an image as the menu item with a second image as the roll-over state.  To accomplish this I utilize JQuery to modify the DOM based on the user’s interaction. In Part 1 of the guide we will lay the ground work by defining the base elements and javascript that will perform the image swap.

Basic Roll-over Roll-out Set-up

The javascript code we will implement will work within any Document hierarchy that utilizes the navigation element as an image wrapped in an anchor tag, example:

<a href="../about/" ><img src="../img/about_btn.jpg" width="82" height="68" alt="About" /></a>

Using the above as our basic structure we need to add some identification to the link (Anchor tag) that this is a navigation element to do this we will add a class to them of  “siteNav” so our links will now look like:

<a class="siteNav" href="../about/" ><img src="../img/about_btn.jpg" width="82" height="68" alt="About" /></a>

Now that we have identification on the navigation links we can start implementing our javascript. To start with we will utilize the jquery ready function so that our code is called after the page has been loaded and is ready for manipulation. Once the page is loaded we can utilize the identifying class to access and manipulate the navigation items using the each function.

$(document).ready(function () {
    $(".siteNav" ).each(function (i) {
    });
});

Inside the each statement we can set-up functions to fire on mouse events (rollover, and rollout) to simplify it further JQuery has a nice hover function that we will utilize to modify our navigation images. The basic logic we are going to instantiate is that on rollover modify the image url so it shows the over image, and on rollout modify the url so it shows the out or default image. To accomplish this we will name all over images the same as the default image with _over appended to the name. An example is about.jpg and about_over.jpg.

$(document).ready(function () {
    $(".siteNav" ).each(function (i) {
        $(this).hover( function () {
            var img_url = $(this).find("img:last").attr("src");
            $(this).find("img:last").attr("src", img_url.substring( 0, img_url.indexOf( ".jpg") ) + "_over.jpg" );
        },
        function () {
            var img_url = $(this).find("img:last").attr("src");
            $(this).find("img:last").attr("src", img_url.substring( 0, img_url.indexOf( "_over.jpg") ) + ".jpg" );
        );
        });
    });
});

Conclusion

With this set-up we now have a navigation whose items change images when the user rolls over them.  Now to be fully informative and user friendly you will also want to have an active state such that if a user is not interacting with the navigation the link that corresponds to the page they are on will remain in its rollover state. How to accomplish this is outlined in Part 2.