Archive for the ‘Javascript’ Category

AJAX – setup and test

Monday, March 8th, 2010

AJAX is the way of communicating with a back end server without having to send the full information (you can of course) but for example you could just send a username check to see if it is available, but the main thing is that you do not send back a full page but only the part that you want to update.

With reference to the example of a username, you could just send the username and send back either yes or no response which saves allot of time and traffic from the client to the server (and makes the whole web page experience nicer).

All the AJAX is shorthand for “Asynchronous JAvascript and Xml”, asynchronous means that you can do something else whilst waiting for the response (put the kettle on and get a cup for the drink whilst the kettle is boiling) thus with javascript on the client web browser sends a request to a web page on the server with XML wrappings.

To get the basics lets start with the being

  // this function will return a XmlHttpRequest object that allows you to "talk" to the server.
  function GetXmlHttpObject()
  {
      // IE7+, FF, Chrome, Opera, Safari
      if (window.XMLHttpRequest) return new XMLHttpRequest;
 
      // IE6 , IE5
      if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
  }

the GetXmlHttpObject will return a object that will allow the javascript to talk to the backend server, the newer version is call a XMLHttpRequest whilst on older browsers it was part of the ActiveXObjects.

The next is to send a request to the backend server

    xmlHttpObject.onreadystatechange=callBackFunction;
    xmlHttpObject.open("GET", GetUrl, true);
    xmlHttpObject.send(null);

The onreadystatechange, will call a function (in javascript on the client browser) when the request alters from different states, the different states are

  • 1.open method invoked successful, open a connection with the server
  • 2.server responsed with a valid header response.
  • 3.server has sent some data, the response content is started to load.
  • 4.server has finished sending all of data

so from reading the states, you are really interested in state 4, because that will have the data (server response) that you are interested in for this.

The .open forms the request to the XmlHttpRequest object to call (”GET” in HTML) the server web site, the GetUrl is just a variable that well call a php page (”ajaxbackendcall.php”) which takes a parameter called name and returns a string with the name in reverse (shall include that source code later).

And then the .send will start the ready states to change and sends the request to the backend server, here is the function that is called on the state change

  function callBackFunction()
  {
    if (xmlHttpObject.readyState == 4)
      alert(xmlHttpObject.responseText);
  }

What is happening here, is that from the state stages I am waiting on ready state to equal 4 ( when the server has finished responding) and then output the response from the responseText which is filled from the AJAX call to the backend server.

That is mainly it, here is some full code for you to try out save this as “codingfriends.com.ajax.test.html”

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html3/strict.dtd">
<html>
<head>
<script type="text/javascript">
  // the xmlHttpRequest object
  var xmlHttpObject;
 
  // the ajax call 
  function getInnerText()
  {
    // get the name to send to the server backend page
    var namehere = document.getElementById("namehere");
 
    // request the xmlHttpObject 
    xmlHttpObject = GetXmlHttpObject();
 
    // if there is not xmlHttpRequest object being allowed to be created then the browser does not support it.
    if (xmlHttpObject==null)
    {
      alert("Browser does not support XmlHttp calls e.g. AJAX");
      return;
    }
 
    // fill in the request details, e.g. the url to call and also the query string inserted into the url
    var GetUrl = "ajaxbackendcall.php"+"?name="+namehere.value;
 
    // here is the call to the server.
    // to start with setup which function to call when a ready state on the XmlHttpRequest object has changed
    xmlHttpObject.onreadystatechange=callBackFunction;
    // request the html "GET" to obtain the url (e.g. the backend server page, dynmaic normally)
    xmlHttpObject.open("GET", GetUrl, true);
    // and then issue it
    xmlHttpObject.send(null);
  }
 
  // the function that is called once the XmlHttpRequest object state has changed
  /* the readyStates are 
    1 open method invoked successful, open a connection with the server
    2 server responsed with a valid header response.
    3 server has sent some data, the response content is started to load.
    4 server has finished sending all of data
  */
  // so we listen for readyState 4 when all finished
  // and output the response text into the div id innertextoutput
  function callBackFunction()
  {
    if (xmlHttpObject.readyState == 4)
      document.getElementById("innertextoutput").innerHTML=xmlHttpObject.responseText;
  }
 
  // this function will return a XmlHttpRequest object that allows you to "talk" to the server.
  function GetXmlHttpObject()
  {
      // IE7+, FF, Chrome, Opera, Safari
      if (window.XMLHttpRequest) return new XMLHttpRequest;
 
      // IE6 , IE5
      if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
  }
</script>
</head>
<body>
<a href="#" onclick="javascript:getInnerText()">click here to return text from a ajax call</a>
<br/>
Enter the name here <input id="namehere"/>
<br/>
<div id="innertextoutput"></div>
</body>
</html>

and then save this as the ajaxbackendcall.php file to call (in the same directory as the code above and also within a directory that has PHP plugin enable for that webserver be it apache or IIS.

<?php
    $name = $_GET['name'];
 
    // change the output to say something else, here I am just reversing the name
    if (strlen($name) > 0)
    {
      // have to insert something into it so that php does not make it into a array but a string
      $namereturn="0";
      $j = 0;
      for ($i = strlen($name)-1; $i >= 0; $i--)
      {
        $namereturn[$j++]=$name[$i];
      }
      echo "normal name {$name} and in reverse {$namereturn}";
    }
    else
      return "No name inputted";
?>

The output would be similar to the below. OUTPUT

click here to return text from a ajax call
Enter the name here

END OF OUTPUT

If you do not have a PHP webserver to test with, you can just alter the codingfriends.com.ajax.test.html code by altering the backend web page to call to this

var GetUrl = "nonephpbackend.html"

and create a page within the same directory as the codingfriends.com.ajax.test.html page and place something inside it like

hi there

Alter img (image) tag – on click

Monday, February 15th, 2010

With javascript you can do allot of fun things that a static page, in this example I am going to use the getDocumentID to obtain a image (img) HTML tag, and whilst I have this as a javascript object I can then alter the src image details.

I have created a “a” href HTML tag that will not go anywhere, but I am using the onclick javascript method to call the javascript function which references the id name within the img HTML tag.

  <a onclick="javascript:alterImg()">Alter Image</a>
  <img src="pic1.jpg" width="250" height="350" id="imagesrc"/>

and within the alterImg javascript function, getting the image (img HTML tag) via the ID

  function alterImg()
  {
    // get the element img into the imgobject variable
    var imgobject = document.getElementById('imagesrc');
    // change the src of the image to the other image to display.
    imgobject.src = pictureImage;
    // change the image to the other image.
    if (pictureImage == "pic2.jpg") 
      pictureImage = "pic1.jpg";
    else
      pictureImage = "pic2.jpg";
  }

Here is the full code and if you save the below as changeimage.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<script language="javascript">
  var pictureImage = "pic2.jpg";
  function alterImg()
  {
    // get the element img into the imgobject variable
    var imgobject = document.getElementById('imagesrc');
    // change the src of the image to the other image to display.
    imgobject.src = pictureImage;
    // change the image to the other image.
    if (pictureImage == "pic2.jpg") 
      pictureImage = "pic1.jpg";
    else
      pictureImage = "pic2.jpg";
  }
</script>
<body onload="alterImagenow()">
  <a onclick="javascript:alterImg()">Alter Image</a>
  <img src="pic1.jpg" width="250" height="350" id="imagesrc"/>
</body>
</html>

The output would be this.. click on “Alter Image”.


Alter Image

You can save the images by selecting the image and right clicking save as..

How to convert the output format in Javascript

Monday, July 27th, 2009

How to convert the output format in Javascript

If you want to format the output in Javascript, you must realize your codes by yourself because there are no related functions in Javascrip. These days, I got a set of functions written in Javascript to realize the data formatting coded by AJAX WebShop (You can dowonload AJAX WebShop in theire official site:link. Version 3 is recommended). They are very helpful.

Find ’system.js’ in the directory of AJAX WebShop and you will get these functions below:

function FormatFloat(value,mask)
{
       return BasicFormat(value,mask,'FormatNumber')
}
function FormatDate(varDate, bstrFormat, varDestLocale)
{
       return BasicFormat(varDate,bstrFormat,'FormatDate',varDestLocale);
}
function FormatTime(varTime, bstrFormat, varDestLocale)
{
       return BasicFormat(varTime,bstrFormat,'FormatTime',varDestLocale);
}
function BasicFormat(value,mask,action,param)
{
       var xmlDoc;
       var xslDoc;
       var v='<formats><format><value>'+value+'</value><mask>'+mask+'</mask></format></formats>';
       xmlDoc=parseXML(v);
 
       var x; 
       if(isIE)
              x='<xsl:stylesheet xmlns:xsl="uri:xsl">'
       else
              x='<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">';
       x+='<xsl:template match="/">';
       if(isIE) {
              x+='<xsl:eval>'+action+'('+value+',"'+mask+'"';
              if(param)x+=','+param;
              x+=')</xsl:eval>';
       }
       else
              x+='<xsl:value-of select="format-number('+value+',\''+mask+'\')" />';
 
       x+='</xsl:template></xsl:stylesheet>';
       xslDoc=parseXML(x);
       var s;
       if(isIE)
        s= xmlDoc.transformNode(xslDoc)
       else{
              //for mozilla/netscape 
        var processor = new XSLTProcessor(); 
              processor.importStylesheet(xslDoc);
              var result = processor.transformToFragment(xmlDoc, xmlDoc);
        var xmls = new XMLSerializer(); 
        s = xmls.serializeToString(result);
       }
       return s;
}

On mouse events

Monday, July 27th, 2009

Within javascript it is able to reference an HTML object so that if any “on” events happen, for example if an mouse hovers over the HTML object it is called onmouseover event and these events are capable of changing the webpage as well.

To create an process attached to an event, you can either add the code inline to the HTML object like

       <a href="/" title="testing" onmouseover="javascript:this.style.background = 'blue'" onmouseout="javascript:this.style.background = 'white'">First Test </a>

This will change the link object <a> events for when the mouse hovers over the <a> HTML object (onmouseover) and also when the mouse leaves the <a> HTML object (onmouseout).

Also with using the body HTML onload event, it is able to attach an javascript process to any object without doing inline code.

       <body onload="javascript:objload('aid');">

which is attached to any function, in this case I have attached to objload(objectID) function.

Here is the full HTML code

<html>
       <head>
              <script language="javascript">
                     /// can do a window.onload function instead of the body onload
                     window.onload = function()
                     {
                            //objload("aid");
                     }
 
                     // function to alter the object with mouse over events
                     function objload(objID)
                     {
                            // obtain the object of the passed in element ID
                            <span style='color:blue'>var</span> obj = document.getElementById(objID);
                            // <span style='color:blue'>for</span> the object mouse over function (e = event)
                            obj.onmouseover = function(e)
                            {
                                   obj.style.background = 'blue';
                                   obj.style.color = 'white'
                                   return true;
                            }
                            // <span style='color:blue'>for</span> the object mouse out function 
                            obj.onmouseout = function(e)
                            {
                                   obj.style.background = 'white';
                                   obj.style.color = 'blue';
                            }
                     }
              </script>
       </head>
       <!-- can do onload event with the standard html -->
       <body onload="javascript:objload('aid');">
              <a href="/" title="testing" onmouseover="javascript:this.style.background = 'blue'" onmouseout="javascript:this.style.background = 'white'">First Test </a>
              <p>
              <a href="/" title="test" id="aid">Second test</a>
</html>

Styles – alter with javascript

Monday, July 27th, 2009

To alter style values within a html page via Javascript can be done two different ways, that I know of, one is via getting the object itself and then altering the style from that and the other is via the document style sheets object.

The document style sheets object is all of the styles on the web page and is index within an array manor. For example

       styleSheet = document.styleSheets[<insert number of object>]

But since the two main browsers (Internet Explorer and also Firefox) deal with the css rules within this object with a different reference (IE = rules and FF = cssRules).

       if (styleSheet.cssRules)
              cssRule = styleSheet.cssRules[0]; // Firefox
       else if (styleSheet.rules)
              cssRule = styleSheet.rules[0];         // IE

The other method is via the id of the object, to obtain this just need to use the javascript getElementById function with the document object.

       cssRule = document.getElementById(style)

And then once the object of the style is obtained with both functions can just alter the style of the object with the same code.

       if (cssRule.style.backgroundColor == colour)
              cssRule.style.backgroundColor = colour2;
       else
              cssRule.style.backgroundColor = colour;

Here is the full code

<html>
       <head>
              <style language="text/css">
                     h1 { background-color: lightblue;}
                     #pstyle { background-color : lightblue;}
              </style>       
              <script language="javascript">
                     function alterh1(colour, colour2)
                     {       
                            var styleSheet, cssRule;
                            if (document.styleSheets)
                            {
                                   styleSheet = document.styleSheets[0];
                                   if (styleSheet)
                                   {
                                          if (styleSheet.cssRules)
                                                 cssRule = styleSheet.cssRules[0]; // Firefox
                                          else if (styleSheet.rules)
                                                 cssRule = styleSheet.rules[0];         // IE
                                          if (cssRule)
                                          {
                                                 if (cssRule.style.backgroundColor == colour)
                                                        cssRule.style.backgroundColor = colour2;
                                                 else
                                                        cssRule.style.backgroundColor = colour;
                                          }
                                   }
                            }
                     }
 
                     function alterstyle(style,colour, colour2)
                     {
                            var cssRule;
                            cssRule = document.getElementById(style);
                            if (cssRule)
                            {
                                   if (cssRule.style.backgroundColor == colour)
                                          cssRule.style.backgroundColor = colour2;
                                   else
                                          cssRule.style.backgroundColor = colour;
                            }
                     }
              </script>
 
       </head>
       <body>
              <h1>Change this style</h1>
              <input type="submit" value="click here" onclick="javascript:alterh1('blue', 'lightblue')"/>
 
              <p id="pstyle">
                     HI there
 
              <input type="submit" value="click here" onclick="javascript:alterstyle('pstyle','blue','lightblue')"/>       
       </body>
 
</html>

Arrays – Insert into a div

Monday, July 27th, 2009

Javascript arrays are just like any other object orientated language, in the aspect an array is a block of memory associated with main object. To create an array in Javascript just need to call
= Array(5);
Or
= Array(’value1′,’value2′);

The code below is using a default screen from which you press the ‘Click Here’ button and the array is used to insert into a <div> html tag. To insert into a div tag within javascript, there needs to be a new node created and in this instance a text node is created which in turn is appended to the div.

The code hopefully will explain more.

<html>
       <script language="javascript">
              // setup the main array
              var setArray = Array("hi", "there", "this", "is", "a","test");
 
              // insert the array into the DIV smalltest object
              function insertArray()
              {
                     var theText = "";  // set the theText output to an empty string otherwise it would start with null.
                     for (var i=0; i < setArray.length; i++)
                     {
                            // create the array of text to insert
                            theText += setArray[i];
                     }
                     // create the createTextNode 
                     var insertText = document.createTextNode(theText);
                     document.getElementById("smalltest").appendChild(insertText);
              }
       </script>
       <body>
              Just a small test, 
              <div id="smalltest">
              </div>
              <input type="submit" value="click here" onclick="javascript:insertArray()" />
       </body>
</html>

Add two numbers

Monday, July 27th, 2009

This tutorial demonstrates how to get two inputs from the user within a HTML page and have a button on the page to call a javascript method to process the inputs and alter the answer output on the web-page.

Within HTML, there are input tags that allow the user to input data that is passed either to a javascript method to validate the inputs (for example a registration forum) or to pass data back to the server (after the validation has taken place if required).

The value 1 input is defined as
value 1 = <input type=’text’ id=value1 name=’value1′ value=’1′/>
the input type is text, which means any textual value, [A-Z]*[0-9]* but in this case since just adding integers [0-9] would be the required input.
The id is for getting the value from the input with using javascript document.getElementById, value is for setting the default value.

The function within the javascript, addNumbers() will get the inserted value1 by using the javascript document object. Within this object there is a method called getElementById that returns back the object, which in turn using the .value of the object returned can be passed to the parseInt (which converts a string value into a integer value). The same method is used for the answer input within the web-page (getElementById) but assign the return object to a variable allows access to the .value to set the value on the web-page.

The source code is

<html>
  <head>
        <title>Input tutorial</title>
        <script language="javascript">
                function addNumbers()
                {
                        var val1 = parseInt(document.getElementById("value1").value);
                        var val2 = parseInt(document.getElementById("value2").value);
                        var ansD = document.getElementById("answer");
                        ansD.value = val1 + val2;
                }
        </script>
  </head>
  <body>
        value1 = <input type="text" id="value1" name="value1" value="1"/>
        value2 = <input type="text" id="value2" name="value2" value="2"/>
        <input type="button" name="Sumbit" value="Click here" onclick="javascript:addNumbers()"/>
        Answer = <input type="text" id="answer" name="answer" value=""/>
  </body>
</html>

save as addtwonumbers.html and then open in a web browser (e.g. FireFox)

Hello world

Monday, July 27th, 2009

Well, this is the javascript hello world. The javascript is used within web pages and the client browser (e.g. Internet Explorer or Firefox etc) will use the javascript code to help display the content of the page. This tutorial displays the “Hello World” in the webpage.

If you cut from

<html>
       <title>Javascript hello world</title>
       <body>
       <script language="javascript">
              document.write("Hello World!");
       </script>
       </body>
</html>

as javascripthelloworld.html

and then open up within IE or FF, this shall display a white page with the words in the top left “Hello World!”

The javascript is based on Objects, the same as Java,C++, C# etc, and the document object is the web page itself.

Hope it helps