New Posts

Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Friday, September 30, 2011

Windows 8 Metro Diary: Day 3

The following few posts will chronicle my experience with the newly released Microsoft Windows 8 Developer's Preview, made available as a free download from Microsoft themselves.

Monday September 26th - Friday September 30th 2011

Day 3 is a little different, in fact its a week, since I had less time to play around with it, and less things to talk about, I'll bundle the week together.

After several days of digging around, I found a way to get the developer tools for Metro style apps for the other downloads, So I have in fact started to develop one application. However since Microsoft considers this a breach of EULA I cannot disclose the technique here. Suffice it to say, its simple and straight forward. Which makes it even the more puzzling that Microsoft chose not to include this in all the downloads.

However that does not end the issues. After a few days of development Visual Studio 11 crashed on me and has never come back up. It now crashes every time I try to load it. However there is another version that gets installed which is labeled the Experimental Instance which continues to work correctly. So I'm using that.

I've also had an issue with my DVD-Drive, an LG DVD-RAM drive. Its picked up flawlessly by both my BIOS, and Windows XP in the same machine, but Windows 8 just refuses to see it. I guess I could chalk it up to a glitch in this pre-release version and expect it to be fixed b y the time the actual full release hits shelves. Though its still a bit of a mystery as to why it won't see it. More so considering that it was that drive that was used to install Windows 8 from the burnt DVD.

In any case moving on to my Metro style application, I have to say development is very natural if you are familiar with the languages involved. I chose the HTML 5 and Javascript approach, but there is of course the C++, C# or even Visual Basic alternatives if required. All 4 boil down to a full screen website style interface with the engine behind the app being any of the mentioned languages. Its an interesting concept, that actually works surprisingly well for consumer applications such as image management, social site interactions, games, and other none productive apps. However I don't see office based apps as Word, Excel, financial applications, etc.. making the leap to Metro Style.

I do expect however that we'll see Metro based alternatives, with probably less functionality, but nicer interfaces. A Metro style text editor is inevitable as will be a basic Image editor. Standard every day tools like a basic email client and instant messenger are also, no doubt, in the horizon.

For users with more involved requirements the now called Desktop mode is basically an update to the Desktop of any Windows version prior to this, and in which users will be able to run non metro style apps as they would in older Windows versions. This is where most corporate environments, and more technically oriented users will spend most of their Windows using time.

In the end Metro is clearly aimed at final, home or casual users; by offering a nice interface to their most often used apps, without needing to get into the actual system OS. It turns a PC into a tablet which is what most casual users would want for their regular tasks.

As far as my metro App goes, I developed a pretty basic unit converter. From Metric to English units, and so forth. Its not done yet, but here's a screen shot to tide you over until the next post.

Photobucket

Friday, May 20, 2011

Ajax 101

Asycnronous Javascript And XML, the mysterious entity known as AJAX.

What is it? What does it do? In simple terms its a method of connecting a website to a server side script without needing to submit a form, or reload a page.

For years the usual way of getting data from the server was to submit a form with values to be processed by the server which would in turn return the results of its process. This usually slowed down websites considerably, and there was no real time interaction between the user and the website.

Ajax solves this by opening a direct connection to the server, and requesting the data processing without needing to submit a form.

Ajax is composed of 3 main sections:
  • The Javascript that executes the Ajax call
  • The Ajax that calls the server side script
  • The Server side Script that takes the parameters and produces the data to be returned to the website.



The main component of AJAX is the XMLHttpRequest object. This thing does it all. It opens the connection, waits for the results, and then makes them available to JS for any further parsing or usage.

But before we can use that we need our Server Side process. This can be pretty much any script that returns data, and it can be done in pretty much any language the server can execute. PHP, ASP, Coldfusion etc...

For our example we'll be using PHP.

The Server Side Script

The Server Side Script has one important task to accomplish, and that is to produce the results we need. The script should be designed like any server side script, except we don't need full html tags as we are going to deliver this to our Javascript layer for usage in an already established page.

So basically all we want is for our script to output our data. We could include a table structure or some other markup if we require, but only if we don't plan for your JS side to do anything to data, otherwise outputting in usable formats such as comma separated strings, or a JSON object is enough.

For our example script we'll just have a process that takes a value from the POST array and echoes it out in a string.

PHP Script


<?PHP

if(isset($_POST['id'])){

echo "The ID Passed is: $_POST[id]";

}

?>





Javascript and Ajax

No we need a way of calling our server side script, and getting back the results. to do this we will require the XMLHttpRequest object from the JS window object.

We start by defining our request object:

Request Object


var requestObj=new XMLHttpRequest();




We can now use our new object to initiate the call to our server side script. However before we can do that we'll need to make a decision. do we want our call to be synchronous or asynchronous. A synchronous call means the Js stops and waits for the server to complete the processing before continuing on, this effectively makes the website hang and be unresponsive until the call is finished. Ultimately we would only use this if don;t have lots of processing to do and the response would be returned rather quickly.

Otherwise we'll want to use the asynchronous method which as it implies lets the website and all JS functions continue to run while the server process is being executed. This allows the user to keep doing things while the request is under way.

We are going to go for the asynchronous method, so we need to
setup a function to handle the data once it returns. For this we use the onreadystatechange event of our ajax object. onreadystatechange triggers every time the the readystate property changes. The readystate property simply holds the status of our request. We want it to be 4 so the Request is complete. The other values are not relevant in the context of a webpage as you can't actually do anything about them.

We also have to check the status property. The value we want is 200, which stands for "O.K." that means the call to our server side script executed correctly and data was returned. Status has many values that you can check; most are the standard HTTP status codes like the classic 500 Internal Server Error, 404 Not found error etc...

We check for both those values, and if they are 4 and 200 we can proceed to use the responseText value to get whatever our script produced as output.

Request Object and Properties


requestObj.onreadystatechange=function()
{
if (requestObj.readyState==4 && xmlhttp.status==200)
{
var results=requestObj.responseText;
document.getElementByID('myDiv').innerHTML=results;
}
}




We can then use our results to populate anything we need using regular JS calls. In the example above I simply placed everything into a div.

The next part of our Ajax interaction is to call our actual script. We'll use the open() method to define our script address, the method we want to use, and the type of call (synch vs asynch) amongst other things.

The Open method


xmlhttp.open("POST","script.php",true);




The Methods are the same ones used in a From, GET or POST. POST is the better alternative if you plan on sending a lot of data to be processed.

The address of our script is the second value we need to set. the request object is limited to reading scripts form the same domain it originates so you can;t go out and read pages from other websites to mash up into your own site.

We then need to set up our headers. Since we are basically recreating the function of a form, we set it up as such.

Headers


requestObj.setRequestHeader("Content-type","application/x-www-form-urlencoded");




And finally we need to send our parameters to our server side script.

Send Paramters


xmlhttp.send("id=" + value + "&action=list");




The parameters will appear in our POST array inside our server side script. In the case of PHP the $_POST variable.

You can set a string, or you can add values from variables or both like above by using concatenation. "value" is a variable that contains the id we wish to pass. We separate each pair with an ampersand &

With that we are done, we can setup our ajax call to be executed when a button is pressed.

Button Call


Enter ID: <input type="text" id="idbox">

<input type="button" onclick="runAjax();">




With that done, inputing an ID and pressing the bun will run our Ajax function and in turn execute our PHP script without needing to reload the page.

In our next installment we'll be looking at a slightly more complex example, by getting data from a database on the fly.

Working Example





Download the example:

Questions? Comments? Use the comment form.

Monday, August 30, 2010

Javascript 101: The Basics

Today we'll start our Journey down the wondrous world of client side scripting.
Javascript is an object oriented interpreted language used to give websites a bit more dynamism in the form of user interactions and interface usefulness that gives the website more ease of use.

However Javascript can and frequently is overused, or misused. We'll look at how a little further into this post.

First of all what does Javascript being object oriented and interpreted mean to the web site developer.

Its interpreted, which means you don't need to compile it, as most browsers automatically understand it and interpret it on the fly.

Its also Object Oriented which means its designed to work off of little black boxes called objects that have properties and methods. That is they have traits to them and can do things.

Everything in JS is an object From the browser window, to the HTML button tag they are all objects which have properties that define them like height, width and a name, and methods; things they can do, like the click() method of a button which clicks the button and executes any associated actions.

For the Browser to understand that Javascript is present in a page it can be in 1 of 3 locations.

Between script tags
In an event of an element in the page such as onClick.
Or preceded by the javascript protocol in a link reference or address section < a href="javascript:someFunction();">

When writing Js code, you will be using objects to access and manipulate things on your page, the principal object you will be dealing with the most is the document object.

This object contains most of the other elements and functions you may want or need to access. From page elements to action events.

Its most useful functions are the getElementBy functions. These functions allow you to find an element in a web page and be able top manipulate its properties and methods.

These are getElementById, getElementsbyName , and getElementsByTagName


getElementById allows you to find any element by its ID. It returns a single element you can use, and if erroneously there is more than one element with the same ID it will only return the first element it finds.

getElementsByName returns an array of all elements that have a matching name.

getElementsByTagName returns an array of all the element of a specific type. Say all Divs all inputs, all images etc..

For instance:

var myElement=document.getElementById('theID');
This returns a reference or pointer if you will to the object or element with an id of 'theID'


To exemplify lets say you have a textbox in your page you want to manipulate when a button is pressed:


<input type=text id="myTextBox" value="Sample">

<input type=button name="manipulate" value="Manipulate Text Box">


First we need to determine when the button is pressed for that we use one of the buttons events. Events are actions that occur to the object. An action such as when the button itself is clicked would trigger the onClick event of the object. So we want to have something happen at that time.

Lets say we want to alter the contents of the text box when the button is clicked. so we use the onClick event of the button to have it execute our JS function to change the value of the text box:


<input type=button name="manipulate" id="MyTxtBox" value="Manipulate Text Box"
onClick="changeTxtBox();">


So know we've set our button to execute a function when its pressed, but what would our function look like and where should it go:

Usually our Javascript code should reside in the script section of our page, which goes in between the <head></head> tags.


<html>
<head>
<script type="text/javascript">

function changeTxtBox(){
...
}
</script>
</head>



Notice how the name of your function matches exactly what we placed in the onClick event of our button. Javascript is case sensitive which means uppercase letters are treated differently to lower case letters. so FunctionName would be different to functionname.


So now that we have our function we need to access our textbox and modify its contents. We'll want to access our element using the getElementById method of the document object and passing the ID we gave to our text box "MyTxtBox".



var OurTextBox=document.getElementById('MyTxtBox');


So we now have a reference to our text box in OurTextBox variable. From here we can manipulate the text box as require. Since we want to change the contents of th textbox which currently says "Example" we'll use its value property:


OurTextBox.value="This is the replaced value";



So at the end our function look like:


function changeTxtBox(){
var OurTextBox=document.getElementById('MyTxtBox');
OurTextBox.value="This is the replaced value";
}


And that's it. Our Button will now alter the contents every time it is clicked.

Try it out here, write something into the textbox and press the button.



By the same toke we can access many other properties of the object such as width, height, name etc...




Javascript 102: Reinventing the Wheel



There are many things that can be done with JS, but as I've said before just because you can do something doesn't mean you should.

JS is supposed help you provide a more pleasant experience to the user, but not at the cost of bugs, and strange issues because your code is so complex you have a hard time maintaining it.

If there's already an HTML element for what you want to do its always a good idea to use it rather that to try to reinvent the wheel.

The most common "Wheel Reinvention" I've encountered is of course the lowly link.
Using a button, or some other html element to simulate a link by using JS.

A few examples follow. A Div, a button, an img, and last one is an actual link.
Notice how all of them look pretty much the same, even the picture-less image. There is no point in using JS to make those things act like a link when there's already a link element.



This is a simple example which only required a single line of JS, but you may encounter other times when you want to do something when there's already something there that does it.




Javascript 103: Error Checking



When coding in Javascript its important to check for errors, as you'll find that for the most part a website will lad without complaining about Javascript issues, but your actions may not function properly.

But how does one check for error when none are shown? Simple you request them. Most Browsers offer some type of debugger to let you know that something went wrong with your client side code.

  1. Internet Explorer shows its very conspicuous Gold shield on the bottom left corner of its window. Double clicking there will bring up the debugger window when there are errors.

  2. Firefox has its Error Console which can be accessed from the Tools menu

  3. Safari has an Error Console under its Develop menu which needs to be activated from its Advanced Tab in the Preferences Dialog.



From there you can see any and all errors you may have listed, and attempt to correct them.