Weird Thoughts From Eric's Head

Categories : All | AJAX | BUSINESS | PERSONAL | PROGRAMMING | BOOK REVIEW

AJAX : A Basic Example and a Bookmarklet
Okay now what you all been waiting for: my example on AJAX. Waring: I am not going to go into extreme detail; you can get Dave Crane’s and my book (AJAX in Action) for that when it comes out later this year. First lets see an example of AJAX working right here under our noses.

Now everyone in a JavaScript world says. How can I protect my pages with a username and password without a server side language? Well it can not be done, but you can make it hard to find your content. In this example below you can see a textbox, a password box and the wonderful submit button. Try entering in a username and password.

User Name:
Password:  

Look at the source and you will see there is no username and password. Instead we are using the username and password field to see if the file exists. With AJAX, we look to see if this file is there. If it is, we go there, if not we get the error. Well I am sure you want to see the location so the username is Eric and the password is pass. Now you are able to go there and see my message.

So what is the code to do this? Well now we all know the fun we have coding JavaScript, nothing works the same for different browsers. With IE we need to use ActiveX to do it. Mozilla has there own method to do it.

First we have two things. We have the code that does the request, and then we have a function that handles the returned data. If you are using one of those libraries, you may not have seen this, so open up your eyes wide. Now I am just going to explain the code with comments. (Yeah that is cheating compared to my normal discussion style here on my blog, but I am trying to write a book you know!)

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

      //We need a wonderful global variables to hold our request object!
      //So we can pass it around.
      var reqXML;
      //We need to have a global variable to hold the url.
      //It keeps us from having to repeat code!
      var url;

      //Create our function to start the request
      function VerifyLogin(){

        //inform there is an action!
        document.getElementById("spanLog").innerHTML = "<span style='color:green'> Checking Information</span>";

        //Grab our form field values
        var strName = document.Form1.username.value;
        var strPass = document.Form1.password.value;
        
        //Make the URL for the request
        url = "http://radio.javaranch.com/pascarello/files/" + strName + strPass + ".html";

        //determine if the browser is Moz, FF, NN, Op
        if (window.XMLHttpRequest){ 
          reqXML = new XMLHttpRequest();            //set the request
          reqXML.onreadystatechange = LoginUser;    //function to call on each set
          reqXML.open("GET", url, true);            //set the page to request
          reqXML.send(null);                        //initialize the request 
        }
        //ActiveX - can we say IE?
        else if(window.ActiveXObject){ 
          //Create our RequestObject
          reqXML = new ActiveXObject("Microsoft.XMLHTTP"); 
          if(reqXML){ 
            reqXML.onreadystatechange = LoginUser  //function to call on each step
            reqXML.open("GET", url, true);         //set the page to request
            reqXML.send(null);                     //initialize the request
          }
        }
        else{  //I do not support this so I need to do something!
           window.location.href = url;
        }       
      }
          
      function LoginUser(){

        //Look to see if the request is in the 4th stage (complete)         
        if(reqXML.readyState == 4){
          //Make sure that we get a sucess page status   
          if(reqXML.status == 200){
            //change our location
            window.location.href = url;
          }
          //For all of the wrong error pages here
          else{
            document.getElementById("spanLog").innerHTML = "<span style='color:red'> Error: username and password is not correct!</span>";
          }
        }
      }
    </script>
  </head>
  <body>
    <form name="Form1" onsubmit="VerifyLogin();return false;">
      <span style="font-family:courier">User Name: </span><input type="text" name="username"><br/>
      <span style="font-family:courier">Password:  </span><input type="password" name="password"><br/>
      <input type="submit" name="btnSub" value="Login" style="font-family:courier">
    </form>
  </body>
</html>

Now I added the event handler to the form to allow us to submit it, I did not think that needed a comment! Now you may be wondering what some things actually mean.

Now the XMLHttpRequest Object has an event handler onreadystatechange that we set to call LoginUser. Now when the XMLHttpRequest is executed we go through 5 stages:

  • 0 - un-initialized
  • 1 - loading
  • 2 - loaded
  • 3 - interactive
  • 4 - complete

We also need to check the status of the document that has been returned. We are looking for a status code of 200 since that means success! We do not want to see that 404 error!

I know I just went over this fast, but you can get more details in AJAX in Action when it comes out. But you may be saying why would I ever want to use this? Well with some minor changes, creating a JS file, and creating a bookmarklet, we can make a very very very very (did I say very) useful tool for a web master that has to check pages to see if all of the links are correct.

Let’s try this out then I will give you the source code. The first step is create a bookmarklet. Take the link below, right click on it, and save it as a bookmark. Agree to the security warning because the link is a JavaScript statement that executes some code. You will be shown the code for the bookmark on the example page.

Verify Links!

After you bookmarked that link above, you need to do open up this link below, go to your bookmarks/favorites and select the one that you just saved. It will then got through all of the links and verify them if they are good or bad. Good is marked in green and bad are marked in red! Give this code to your webmaster!

The test page for you.

There are good and bad links for you!

Now have you seen anyone else use AJAX like this? I do not think so. Hopefully you can see why AJAX is not hype. You can make it do things that you can run from a command in your bookmarks! Now below is the source code so you can save it to your server. Change the bookmark to point to where you saved this document.


      //Set those global variables!
      var reqXML;
      var url;
      var arrLinks;
      var intErrors = 0;
      var currentLink = 0; //We need a counter!
      var timeOutTimer;
      var maxWaitTime = 10000; //Milliseconds!
      var strErrColor = "red";
      var strValidColor = "green";

      function TestThatLink(){
        window.status = "testing: " + url.href;
        timeOutTimer = setTimeout("reqXML='';intErrors++;FinishRequest('" + strErrColor + "');",maxWaitTime);
        try {
	  if (netscape.security.PrivilegeManager.enablePrivilege) {
		netscape.security.PrivilegeManager.enablePrivilege('UniversalBrowserRead');
	  }
        }
        catch (ex) { // eat it
        }
        if (window.XMLHttpRequest){ 
          reqXML = new XMLHttpRequest(); 
          reqXML.onreadystatechange = TestLink;
          reqXML.open("GET", url.href, true); 
          reqXML.send(null);
        }
        else if(window.ActiveXObject){ 
          reqXML = new ActiveXObject("Microsoft.XMLHTTP"); 
          if(reqXML){ 
            reqXML.onreadystatechange = TestLink;
            reqXML.open("GET", url.href, true); 
            reqXML.send(); 
          } 
        }
        else{
          alert("Test browser does not support this!");
        }       
      }
          
      function TestLink(){         
        try {
	  if (netscape.security.PrivilegeManager.enablePrivilege) {
		netscape.security.PrivilegeManager.enablePrivilege('UniversalBrowserRead');
	  }
        } 
        catch (ex) { // eat it
        }
        if(reqXML.readyState == 4){
          window.clearTimeout(timeOutTimer);
          try {
          if(reqXML.status == 200){
            strColor = strValidColor; 
          }
          else{
            strColor = strErrColor;
            intErrors++;
          }
          }
          catch(ex){
            strColor = strErrColor;
            intErrors++;
          }

          FinishRequest(strColor);
        }
      }

      function FinishRequest(xColor){
        window.clearTimeout(timeOutTimer);
        url.style.backgroundColor = xColor;
        currentLink++;
        if(arrLinks.length > currentLink){
          url = arrLinks[currentLink];
          TestThatLink();
        }
        else{
          alert(intErrors + " broken link(s) were found!");
          window.status = "done";
        }
      }

      arrLinks = document.links;  //Grab those Links
      url = arrLinks[currentLink];  //Get the link

      TestThatLink()

Hopefully you can understand what is going on in the code. We are grabbing all of the links, checking to see if they exist, and showing the result on the page. See AJAX does not need to use server side code like everyone says! If you want to understand more about this code, ask away in the comments in this page. (If I do not answer, it is because I am sitting on the beach!)

Now it is Friday, so I think we need to put your brain to rest until Monday where we will talk about AJAX with server side code! But if you want to see a Moderator’s game that uses AJAX, take a look at Bear’s Blackbox here: Blackbox. Or you can sit back and play my JavaScript game (no AJAX) until my bandwidth is used up: Reversi.



Eric Pascarello
Moderator of HTML/JavaScript at www.JavaRanch.com
Author of: JavaScript: Your Visual Blueprint for Dynamic Web Pages

More information on "Ajax In Action"

Hey everyone! Make sure to check out my co-author's blog here:

http://dave.sunwheeltech.com/wordpress/category/tech/ajax/

Go there and learn about the book AJAX In Action a little bit more. He tells you how the book came about and what to expect. Plus there are some good articles on Ajax there too! Put a comment there saying Eric sent ya just to see if his blog can handle it!

I will post my next article on AJAX when I wake up tomorrow. Thanks for your support so far!

Eric Pascarello
Moderator of HTML/JavaScript at www.JavaRanch.com
Author of: JavaScript: Your Visual Blueprint for Dynamic Web Pages

AJAX Securtity and Mistakes I Have Seen
Well two items I have on mind for today with AJAX is security concerns and problems I see with some current implementations of AJAX. Since we are using JavaScript, we are opening one door to people, but it is not much different than a normal form. The problems that I see are just things that I have observed. Might be a little repeat of yesterday, but I think you can handle it.

Security
AJAX is allowing us to develop rich user interfaces but are we causing more security concerns? I have not seen anyone really discuss this topic in detail but AJAX is vulnerable just like any other form submission out there!

Just like everyone in the world should know JavaScript is open source. You can see the code by just doing the views source command. I have seen great tricks to hide the code, but you can always get to it without much problem. The best thing I ever saw to hide their code was 10,000 returns! (Hope you realize I am joking about the best!) People actually fell for this and asked up how they were hiding their source code. My answer: Hit Ctrl F4 as multiple times as fast as you can and then go back to the page and use the down arrow key. It will trick the computer into showing the code! (The person said it worked…Wish I would have saved that email and printed it on the wall!)

Since people can see your client side code, they are half way to understanding your logic. But wait! That is no different than a person looking at the names of your form fields and sending a request. With AJAX you should not be sending back SQL queries to the server, you should be sending back form values, strings, numbers, and what ever else you seem to have the need to send back.

I have seen people use JavaScript to hack all of the hidden fields on a form! I think I talked about that HERE! Yes people get slammed with that stupid mistake! A person went in changed the hidden fields and started to delete every single record from a database. Since the logic used did not do any real checks other than that value in the hidden field. (Okay that person was I and I made sure I made a back up to prove a point to a person so I can say “And you complain about my coding” ~ Sorry getting side tracked!)

So what am I saying here? You need to build the security on the server side. You need to check to see the values being passed. Make sure there are no wonderful SQL injections. What ever you do to verify that it is valid for form submissions you need to do it here. Track sessions, limit requests, verify data, check referrers, and so on! You should be applying the same logic you would for normal form submissions! (You are doing this on your own system with form submissions right now; right?!)

Problems, Issues, Peeves, etc!
People that start to use AJAX are jumping into it without thinking what the consequences of it are. We are taking on a new technology that is only supported by a limited number of browsers: IE 5.0, 5.5, 6.0, Netscape 6.x, 7.x, Mozilla 1.x, FireFox 1.x, Safari 1.x., & Opera 8.01 Are you concerned with that? Personally I am not concerned with that since I am working on the premise that only current technology should be supported. What are you going to do for these browsers that do not support AJAX? Yes we can detect if they do not support it (I will talk about that tomorrow.) Are you going to loose that audience or are you lucky like me and work with only one browser on an intranet? Do you still support Netscape 4.X? Or do you develop two pages or double the amount of code on one page? Up to you to choose!

Now lets talk about the problems I have seen on applications. Now I am not going to point out applications, tool kits, or frameworks since that is not nice. Yesterday I talked about searches and how they are not bookmarkable. Simple fix was to add a link that could give you the option to save the results. Enough on that subject, if you want more information look at yesterday’s blog!

One thing that is nice is that AJAX runs “secretly” in the background meaning you really do not know what is happening. This stealth mode with AJAX is great but some applications are performing their actions and you have no clue that it is doing anything!

You click a button and nothing happens, no message or animation is displayed. How am I supposed to know if I did not click the button hard enough? A normal form submission shows the progress bar in the page. AJAX does not show this. Lets do another analogy since people like analogies! It is like going to your friend’s house and you ring the doorbell. You sit there waiting, your friend said they would be home, and you are standing there twiddling your thumbs. You then think to yourself, did it ring, I did not hear it or did I hear it and just not realize it? You press it again and you do not hear it so you keep hitting it thinking it will work eventually. Your friend finally gets to the door and says, “STOP IT! I have ears you know I was on the toilet!!”

So you need to give the user some reference an action has been taken! That is the short answer to that issue I see. Use a layer and pop it up with the words processing. You an animated gif, go back 7 years ago and get those groovy status bar and title bar scrollers. (Come one you people, you know your first site had them along with your clocks, mouse followers, flying text, shaking browsers, etc ~ SLAP ~ off the path again!)

Another thing that irks me is trying to use AJAX too much. Yes you should use AJAX, but there is a limit. Just because you can use it does not mean it has to be done that way. For example a .NET site used AJAX to fill in dropdown fields with AJAX after the page loads, for a double combo yes do it, but not for a single dropdown. Now we do the entire rendering on the page than the page loads. We send back another request to get the dropdown values and pull them in again. It is a waste of time. It should be done on the server unless we are talking about the fields being related to other items on the page!

All I can say is use AJAX wisely. And tomorrow we will get to do the HELLO WORLD Example! I know you are excited to do it!



Eric Pascarello
Moderator of HTML/JavaScript at www.JavaRanch.com
Author of: JavaScript: Your Visual Blueprint for Dynamic Web Pages

Should you use AJAX?
This is a question that is on top of everyone’s mind: “Should I use AJAX?” or another question is: “How do I convince my boss that we need to look into AJAX?” Well the basic idea is there are times to use it and there are times that you should not use it! There are benefits and there are drawbacks too just like any other technology out there.

Before I discuss the drawbacks and benefits, let me explain the classic Web site model versus the AJAX model in simple non-technical terms that drivers can relate too. (Well most of you may consider this non-technical)

The Car Analogy
The classic Web page model is like a manual car with a bad driver. First we know we need to get to our destination so we start up our car and start driving. We shift through the gears and get to a stop sign. We step on the brake without stepping on the clutch so we stall. So we have to restart the car. We get to the next stop sign and we forget the clutch again and we stall. Again we need to restart the car. We finally get to our destination where we can turn off the car.

Now the AJAX model is like an automatic car. We start up the car and start to head to our destination. We stop at the first stop sign look both ways and we release the break. We keep driving and we do not worry about stalling since we are in an automatic (Well in my old car I had to worry, but that is a different story.) Again we stop and we are able to continue without turning the key. We get to our destination without causing the cars behind us to honk, since we did not stall and have to wait to restart!

Now in this analogy we have two stops signs. These stop signs could have been form verifications, double combo scripts, data retrieval, data posting, and so on. AJAX is able to do all of this without causing the whole entire page to be stopped and started. This stopping and starting can be seen as the stalling of our manual car. After a time it gets really annoying since we have to worry about the current page state. Will it remember the scroll position on the page, will my forms be filled in, will the information be cached or am I pulling all of the data? With AJAX, we are able to eliminate all of those questions/concerns a developer may have.

Benefit and Drawbacks
One benefit that I see is this. You have a double combination script on your web page and your first selection list is dynamically built on the server. You may have to rebuild that selection list every time the page is rendered and select any value that is there. That is a waste of the processor in my mind. With AJAX you would only pass back the value and obtain the new selection values. That means we are only grabbing the data we need and not having to process all of this excess. We do not have to wait as long as a classic post back. AJAX is not as quick as a desktop application since we do have a slight network lag, but it is a lot quicker than having to wait for the page to re-render!

Now what are the drawbacks to Ajax? Can your server handle all of the requests with certain Ajax applications? For example, a type-ahead script that posts back to get the newest results can have multiple requests. Imagine 1000 people using it with large words. How many requests is that?

The famous problem with frames effects AJAX too: Bookmarking a page. Do a search on Google and you get that handy dandy query string which you can send to other people. Do a search that utilizes Ajax and you loose that functionality! How can you overcome this? Incorporate a link on the page that a user can copy and paste. Add either client side or server side processing that checks for this link and returns the results. Little more work, but at least we can see the results.

The third drawback is not a drawback for me, but one for people that are afraid of a technology that is so much fun to play with. This would be JavaScript. Just like I said in my blog yesterday, people are afraid of JavaScript since it has cross-browser compliance issues. That is why it may be a drawback. With a little effort, you will see this is not a drawback. In Ajax In Action and this blog, I try to help you understand the issues with Cross Browser code and how to overcome the common problems. One of the downfalls to JavaScript is the code examples online are wrong on some big sites since the code is out dated and not updated. It is equivalent of using the first Beta version of Java or .NET and today’s current version. Things change!

Now back to our question from the start
Now is AJAX for you? The answer is really for you and your company to decide. Can you take the hits on the server for certain application types? Can you improve the user’s experience? Can you write the JavaScript? Can you understand the packages/libraries that are out there that are available to download? Do you want to save processor space? Do you want to use a cool technology and impress your friends at dinner? (Wait that should not be a reason why you use it!)

I know you want to see some sample code, but I still want to explain other issues I see before I even let you get your hands dirty!



Eric Pascarello
Moderator of HTML/JavaScript at www.JavaRanch.com
Author of: JavaScript: Your Visual Blueprint for Dynamic Web Pages

AJAX..Is It hype?
AJAX (Asynchronous Javascript And XML) seems to be a term that everyone is talking about. One person says it is hype, another person says it is the Holy Grail, and then you got the third person that says I have been using that for years. So is it hype? Is it new or old? What did people do before AJAX? Before I answer any of those, lets start from the point of having no clue about AJAX

What is AJAX and what can it do?
I have seen this question asked multiple times on the HTML and JavaScript forum here at http://www.JavaRanch.com and countless other forums. The simple answer is a programming concept that takes advantage of JavaScript’s XMLHttpRequest object to transfer information to and from the server without having to physically submit an entire page back to the server.

The cool thing about this is it works with JSP, ASP, .NET, PHP, etc. Are there any downfalls to note? Right off the bat, as always we need to rely on JavaScript. So for those users that are scared to death about JavaScript, since it is evil, they will not be able to handle this technology. Also, not all browsers handle the XMLHttpRequest Object. IE uses and ActiveX control and Mozilla followed IE (Yes they copied IE ~ surprised?) and implemented their own version of it. So that means wonderful cross browser code! So if your user is not using a current version of a browser, they will not be able to use this.

The second downfall is my favorite and why certain people call AJAX hype. That downfall is developer’s fear, ignorance, or hatred of JavaScript. I have been programming in JavaScript for over 10 years so I know it can be a pain. I have taught people how to program and I can still hear them banging their heads. People are afraid of this language since it has cross-browser differences. I wrote a book on JavaScript and I still have to sit there and bang my head when I forget which browser uses what for the width of the browser. It can be annoying, but grab a good reference and learn. Take a class, hire me (in the DC/Baltimore area), or buy a book!

Is this new? The term for AJAX is new but it has been around. IE implemented it years ago and no one seemed to use it. Then when the big names in the industry started to use it, people noticed its potential and went crazy. The way people jumped on this topic gave it the hype term, but over time I have seen so many applications utilizing the power of AJAX, that it is not hype and it is here to stay. Tell me that Google Maps, Google Suggest, GMAIL, or A9 is useless and is not user friendly.

With Ajax we can take a Web site’s user interface and turn it into a very rich client with responsiveness that reminds you of working with a desktop application. Yes we need to take into account network lag, but it is a lot quicker then rendering a page that has tons of images and HTML over and over again. For example, scroll the map on Google and scroll a map on MapQuest. Does that Network lag on Google compare to the post back and re-rendering of MapQuest? I will let you be the judge there.

The concept of avoiding post backs has been around for a long time. People have used this idea with hidden frames, iframes, and pop up windows for years. I have sent data back to the server through hidden iframes to keep people from being logged out of a web application. I have posted scores through an iframe for my JavaScript card games. I have seen pop ups used to transfer data to the server so the main page stays static so the user does not lose data. As you can see the concept has been there and we can improve.

The pop ups and frames have issues that the XMLHttpRequest object can address. My applications would freeze if there were 500 errors with pages. With the XMLHttpRequest Object, it is able to detect the 500 error and handle the situation. No more freezing.

In future articles I will discuss how to use the XMLHttpRequest Object, what are common mistakes I see, and what can we do to improve. So check back so you can learn more about AJAX and how it can help you create a Rich User Interface to improve your users experience.

As of right now, I am working with Dave Crane to produce AJAX In Action with Manning. That is the one main reason why my blog has been lacking material since I have been spending my free time creating content to give you the tools to unlock AJAX’s power. With the content in this book, we will give you the key to create the next AJAX application that everyone will be talking about! As it gets closer to publication I will talk more about the book.

Now please do not forget to check back and look for my next article on AJAX. If you have any questions about AJAX or JavaScript, add a comment here on my blog and I will make sure to answer it.



Eric Pascarello
Moderator of HTML/JavaScript at www.JavaRanch.com
Author of: JavaScript: Your Visual Blueprint for Dynamic Web Pages