Announcement

Collapse
No announcement yet.

Jumping on the AJAX Bandwagon

Collapse
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Jumping on the AJAX Bandwagon

    I need to learn to atleast get around in AJAX code for a job I'm doing, so I was wondering where I should start. No amount of looking on google has told me about this, they all seem to assume you know how to code it, just not how to implement it. I don't know a lick of javascript, which seems to be what it's all based on (the J), and XML seems pretty self explanatory to me (unless I'm missing something it's less of a language than a data heirarchy, you can even make up all the tags yourself); I also know PHP, which I think may help but I'm not sure if any serverside code is even needed for AJAX.

    So, I'm assuming all I need to learn is javascript, but I don't know if I should just use a standard javascript tutorial or if they have any that is leaned towards AJAX engines, because I'm kind of pressed for time (my boss knows I don't know javascript, so it's not too urgent). Any tips on good AJAX tutorials for the javascript-inept or just some Javascript tutorials which eventually cover AJAX would be appreciated. And let me know if I'm way off base on what I need to learn

    Thanks,

    bendman

  • #2
    I was starting out the same out but only 7 months ago or so. I now feel quite confident with it. AJAX for me (at least in my definition) includes some sort of server side tech. In my case it's PHP. Whether I'm pulling from a database or something else, it's always PHP for me. I know you can also use pretty much any other server tech you wish.

    Yes, AJAX is pretty much just a way of implementing Javascript. AJAX revolves around the XMLHttpRequest Javascript object, which has actually been supported in browsers for years. In order being using any AJAX-ish concepts, you must first create the XMLHttpRequest object.

    Now doing this is quite simple, although it would be simpler if it weren't for the ActiveXObject version that you must use for IE. But still very straight forward. Here is an example of creating the object.

    Code:
    var xmlHttp = null;
    
    function createXMLHttpRequest(){
       if(window.ActiveXObject){
          xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
       } else if(window.xmlHttpRequest){
          xmlHttp = new XMLHttpRequest();
       }
    }
    Pretty easy. xmlHttp is now an instance of XMLHttpRequest().

    Now to make a request. Let's say we wanted pull the price of a product from a database. We have the product id already and we just need the price.

    Let's setup the request, and assume that the server side is PHP.

    Code:
    function beginPriceRequest(productId){
       createXMLHttpRequest();
       
       xmlHttp.onreadystatechange = handlePriceRequest;
       xmlHttp.open("GET","grabPrice.php?productId=" + productId);
       xmlHttp.send(null);
    }
    There, we just sent the request to grabPrice.php with productId we send the beginPriceRequest function. Before the last line of actually sending the request (xmlHttp.send(null)), we had to set up some things. First of all, the xmlHttpRequest object has the onreadystatechange property. This holds what function should be called everytime something happens during the call. But we'll get to that later. Next, we needed to tell it what page to request, and what method to use. In this case, we're requesting information, so let's use GET, and grabPrice.php is the actual page we're requesting.

    Last, but not least, we send the request, using xmlHttp.send. Since we're not actually sending any data, we must use a null within the parenthesis.

    Now that we're sent the request, we must have a way to handle it. So let's setup the function that handle the state changes.

    Code:
    function handlePriceRequest(){
      if(xmlHttp.readyState==4){
          if(xmlHttp.status==200){
             alert('The price is ' + xmlHttp.responseText);
          }
      }
    }
    And there ya' go. This is handlePriceRequest function that we setup during the send function. The first thing to explain here is that the xmlHttp.readyState property contains different status numbers. 4 means that the page is ready and the request was successfull. There are other states as well, but I do not remember them off hand. The status of 200 is just another way to ensure that the request has completed. (I'm not to sure of why to use the status==200 part, someone please inform me of why exactly)

    We then alert the user of the price of the product. The responseText property holds the text that the page requested outputed.

    So for example, this could be a way grabPrice.php works.

    Code:
    <?php
    
    $user = 'root';
    $pass = 'pass';
    $host = 'localhost';
    
    mysql_connect($host,$user,$pass);
    mysql_select_db('products');
    
    $query = "select price from product_list where product_id = $productId"
    $result = mysql_query($query);
    
    while($next = mysql_fetch_array($result, MYSQL_NUM)){
       $price = $next[0];
    }
    
    echo $price;
    
    ?>
    So it's all pretty simple, and if you're experienced at PHP like you say you are, then this should all be a cinch to pick up.

    Hope I helped.

    Comment


    • #3
      ok, so, if I'm right, when the XMLHttpRequest requests grabprice.php it's doing it asynchronous from the rest of the page, so the page doesn't have to refresh? And, to answer your question about the status==200, I think it's because response code 200 means the page loaded properly.

      anyway, thanks for the tutorial!

      Comment


      • #4
        "Asynchronous" actually refers to the fact that other code will continue to execute while the HTTPRequest object does it's thing. Thus, an AJAX call won't halt other scripts on the page. JavaScript, by nature, is asynchronous, so I've never been entirely sure why they bother to point that out (presumably because they like Greek heroes better than video game heroes).

        Rys

        Comment


        • #5
          Originally posted by RysChwith
          JavaScript, by nature, is asynchronous, so I've never been entirely sure why they bother to point that out (presumably because they like Greek heroes better than video game heroes).
          good lord, i got that WAY too fast. i need to go outside into the sunshine and play with the other boys more.

          great thread, btw! i've been kind of poking my head around the corner to see what wonderful, hideous creature the Scientists left in the lab, but i haven't gotten the nerve to actually step in and put my eyes to the 'scope just yet.

          this Wiki entry has some useful info for starters.
          jeremy jarratt.com | FaceBook | LinkedIn | Twitter | YouTube

          Comment


          • #6
            I know this is an old thread, but I've got a few questions about AJAX.

            I read the piece that Transmothra found. So if Javascript is disabled, then an AJAX page won't work. Right? It would probably have some accessibility issues, too, wouldn't it? Can you make it work without using Javascript? Could I make it work using, say, PHP? I wasn't too sure about that.

            Peg
            Cat-herder Extraordinaire

            Comment


            • #7
              Originally posted by Pegasus View Post
              I know this is an old thread, but I've got a few questions about AJAX.

              I read the piece that Transmothra found. So if Javascript is disabled, then an AJAX page won't work. Right? It would probably have some accessibility issues, too, wouldn't it? Can you make it work without using Javascript? Could I make it work using, say, PHP? I wasn't too sure about that.

              Peg
              Hi Peg,

              By definition AJAX needs javascript to be enabled. AJAX has 2 main components, the server side script which processes the server side information, such as grabbing a price from the above example. Then the client side component is javascript and this is actually used to get the information from the server side script and process it to display inside the browser for the visitor. I do not know enough about javascript to be able to tell you how to do this exactly but I think you can use the <noscript> to display HTML to users that don't have javascript enabled. This way you can fetch them a page that doesn't have any AJAX in it so they can still use your site without bugs. Hope that helps.

              aluminumpork, I know this thread is old but if you see this great write up, very simple to understand. Thanks.

              Comment


              • #8
                Originally posted by Pegasus View Post
                ... So if Javascript is disabled, then an AJAX page won't work. Right? It would probably have some accessibility issues, too, wouldn't it? Can you make it work without using Javascript? Could I make it work using, say, PHP? ...
                let's see ...
                yes.
                i would think so.
                i doubt it.
                -and-
                i doubt it.

                Comment


                • #9
                  The best trick is just to do as Gmail do and create an AJAX version and a non JS version, as many of the deisgn patterns associated with AJAX (delayed loading, pre fetch etc) are in no way compatible with non JS browsers.

                  So in short, yes it does cause issues but its a case of weighing the pros against the cons.

                  Comment


                  • #10
                    AJAX relies entirely on JavaScript (or some similar client-side scripting, like vbscript, etc.) to work. There are only two ways to make requests: navigating to another page, or making a request behind the scenes. If you want to navigate to another page, you are not dealing with AJAX, which specializes in making requests while staying on the same page. If you are making a request underneath, u are using scripting. Those are your only two choices.

                    However, if an AJAX-enabled site is benig used by a user who has scripting disabled, the site should gracefully degrade to making POSTs and GETs that navigate to other pages and still accomplish the same thing if that market is desired. Most of the time, AJAX-enabled sites expect users who haev scripting enabled.

                    ~ mellamokb

                    Comment


                    • #11
                      Originally posted by RysChwith View Post
                      "Asynchronous" actually refers to the fact that other code will continue to execute while the HTTPRequest object does it's thing. Thus, an AJAX call won't halt other scripts on the page. JavaScript, by nature, is asynchronous, so I've never been entirely sure why they bother to point that out (presumably because they like Greek heroes better than video game heroes).

                      Rys
                      The "asynchronous" does not refer to JavaScript itself but to the actual XMLHttpRequest. An XMLHttpRequest object has options to send a requset synchonously or asynchronously. If you do it synchornously, the page waits until the response comes back to continue processing--although the JavaScript processing this request is still running asynchronously from the page or other JavaScript. AJAX specializes in code that performs the XMLHttpRequest using the asynchronous option, which takes a lot more work and experimenting to get functioning properly.

                      So the synchronous is for a simple request to another site for small-scale processing. The asynchronous is for the big boys, like fancy Web 2.0 websites that pull data from lots of sources in any single page asynchornously to the page loading--which is what AJAX is for--or pull requests multiple times in a row after a user presses a button, etc.

                      ~ mellamokb

                      Comment


                      • #12
                        asynchronous refers to the mutli-threading of the object. It is asynchronous because of the way the object fires but is still able to do non-blocking calls. Which means it fires an event when complete and does not block the next call from being executed.

                        Javascript itself is not asynchronous, you must create methods/events of your ajax implementation to use this, in which case it really isn't but acts as if it is. It does this by queuing the calls with fire and forget, but the events/methods tied to the object call executing state changes and allow the developer to modify html directly using javascript as you normally would, but using an event system that wasn't really thought of when they built javascript.

                        synchronous/asynchronous is not a choice but an implementation of the Ajax idea. Most common forms use asynchronous, including ASP.net. In .net you can create them asynchronous using WebMethods (Webservices) attribute and telling Ajax event caller to get data from that method. Just plug and run.

                        Javascript itself; may and may not be asynchronous however its usually blocking by the way the developer creates it, so it means nothing.
                        www.shapemetrics.com
                        Red GateSQL tools for DBA

                        Comment

                        Working...
                        X