calling two functions from event

Discussion in 'JavaScript' started by tanvirtonu, Jun 14, 2009.

  1. dimitar christoff

    dimitar christoff Active Member

    Messages:
    882
    Likes Received:
    62
    Best Answers:
    0
    Trophy Points:
    90
    #21
    that wont work:

    
    function getCusInfo()
    {
    var xmlhttp2=getXMLHttp(); // this is local scope for getCusInfo
    
    ...
    function updateCusInfo(xmlhttp) 
    { 
      if(xmlhttp2.readyState == 4 && xmlhttp2.status == 200)  // xmlhttp2 is not global so is null.
    
    PHP:
    anyway - you are moving away from what is a very simple solution. i tend to prefer to leave people to figure it out on their own with a little help in the right direction so they learn but you're just not getting there.

    so here is what needs to happen to fix it. consider your code - what does it need to accomplish? whenever creating any app, you need to analyse your requirements and spot the repetitive tasks.
    there is NO point in creating 5 separate functions for what is an action that is being repeated twice. what happens when you need to update another div later on, you don't want to have to write a 6th and 7th function that replicates what the others already do just because the url and target elements have changed.

    what do we need?

    1. need to be able to create a xhmlhttp object dependent on the browser
    2. need to be able to fetch a url via xhtmlhttp and update an element with some id on the page

    for this purpose we will write just 2 functions that we will call later - 1 that's private and returns the object and the other one (which we will call) that creates a local instance and fetches the results, updating a target div/whatever.

    this is called 'programming to the pattern' and it's a very good practice to adopt early on as you're learning. http://fragged.org/dev/sequentialAjax.php -> see it working.
    <?
    if ($_GET['url']) {
        echo htmlentities($_GET['url']);
        die;
    }
    ?>
    <div id="navDiv"></div>
    <div id="showCustomer"></div>
    <script type="text/javascript" >
    var getXMLHttp = function() {
        // private, return object per browser capabilities
        var xmlhttp = false;
        if (window.XMLHttpRequest)
            xmlhttp = new XMLHttpRequest();
        else if (window.ActiveXObject)
            xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
        return xmlhttp;
    }, ajaxUpdate = function(url, targetObject) {
        // public, fetches a url's response and injects it into targetObject
        var xmlhttp = getXMLHttp();
        if (!xmlhttp)
            return false; // ajax not supported.
    
        xmlhttp.open("GET", url, true);
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
                targetObject.innerHTML = xmlhttp.responseText;
        };
        xmlhttp.send(null);
    }; // end ajaxUpdate
    
    window.onload = function() {
        ajaxUpdate("sequentialAjax.php?url=navigateAjax.php", document.getElementById("navDiv"));
        ajaxUpdate("sequentialAjax.php?url=customerdb.php", document.getElementById("showCustomer"));
    };
    </script>
    PHP:
    does that make sense? consider frameworks like jquery or mootools which do things like:
    (mootools) element.load("url", {options:values}); // via extended element prototype
    (jquery) $(element).load("url", {options: values}); // function based

    both results are same: updates the contents of element with the response.

    the purpose of ajaxUpdate is the same.

    change the url and remove the sequentialAjax.php?url= (my test file name) and it should work just fine.
    the idea is, ajaxUpdate is a function that takes the response of the url and puts it into the object that is parameter 2's innerhtml.

    p.s. in a production environment you want to build error handling or at least to trap exceptions. possible errors and advice here:
    1. the target element does not exist (is itn onload, is it in the dom, is the id correct?) - you need to see if targetElement is there.
    2. sometimes (not often) ajax fails and does not give the expected results, currently there's no code that will handle this. you need some kind of gentle degradation / defaults to print then, especially so if your page and user experience depend on the output of the 2 ajax calls.
    3. it's a bad practice to fetch a page and then automatically fetch 2 chunks of data as well and update it - thats 2 additional requests you don't need to make. ideally, the data for the 2 layers should be printed by the renderer (page) and the ajax should only fetch it on events or timeouts (when it's likely for it to have changed).
     
    dimitar christoff, Jun 23, 2009 IP
  2. tanvirtonu

    tanvirtonu Peon

    Messages:
    32
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #22
    Brother "imitar christoff" actually what you mentined from my code was my experiment with the code but later I changed the code in my 19th reply(see it).However I tried with your code and that works not only well but I think that is the most optimized one.Thanks for that. Your considerations for simultaneous onload event are really worth remembering.
    I just need a bit clarifications from your code as I m new.What does it mean-
     echo htmlentities($_GET['url']);
        die;
    Code (markup):
    And one more thing is that what does it mean using a comma ' , ' after the end of - var getXMLHttpfunction(),
    And what does it mean" ajaxUpdate = function(){}"
    IS " ajaxUpdate" the name of the function or a variable holding the result of the function.

    var getXMLHttp = function() {//.......
       }, ajaxUpdate = function(url, targetObject) {//.....}
    Code (markup):
     
    tanvirtonu, Jun 23, 2009 IP
    Unni krishnan likes this.
  3. dimitar christoff

    dimitar christoff Active Member

    Messages:
    882
    Likes Received:
    62
    Best Answers:
    0
    Trophy Points:
    90
    #23
    you can create a function in javascript in many ways. read this (not finished but covers functions):

    http://fragged.org/javascript_best_practices.php

    ajaxUpdate IS a function.

    variable assignments can go like so:

    var foo, bar = {}, moo = [1,334,56,"wee"], vroom = function() { return moo.length; };

    as for htmlentities, it's a php function that replaces certain characters with safer versions of themselves, rendering things like scripts posted useless. it should be applied to any string that is output on-screen when data is collected from the user, otherwise, you leave yourself vulnerable to XSS attacks
     
    dimitar christoff, Jun 24, 2009 IP