Need Help ASAP! AJAX problem

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • nicksname7
    New Member
    • Jun 2007
    • 2

    #1

    Need Help ASAP! AJAX problem

    Hi, I am a newbie in the AJAX world. first of all, take a look at my script first:
    assume this script is saved as "myAjax.js"

    [CODE=javascript]//-----------------inside myAjax.js--------------------
    function AJAX()
    {
    var isBusy = false;
    var obj = null;
    var url = "";
    var Method = "";
    var param = "";
    var result = "";
    var isReady;

    if(window.XMLHt tpRequest)
    this.obj = new XMLHttpRequest( );
    else
    {
    try
    {this.obj = new ActiveXObject(" MSXML2.XMLHTTP" );}
    catch(exception )
    {
    try
    {this.obj = new ActiveXObject(" Microsoft.XMLHT TP");}
    catch(exception ){this.obj = null;}
    }
    }
    this.isReady = false;

    function setOpenProperti es(_method,_url ,_param)
    {
    this.url = _url;
    this.Method = _method;
    this.param = _param;
    }

    function getData(data)
    {
    if(this.obj)
    {
    if(isBusy)
    {
    window.status = "busy";
    }
    var tObj = this.obj;
    if(this.Method. toUpperCase() == "POST")
    {
    this.obj.open(t his.Method,this .url);
    this.obj.setReq uestHeader('Con tent-Type', 'application/x-www-form-urlencoded;');
    }
    else
    {
    if(this.param != "")
    {this.obj.open( this.Method,thi s.url + "?" + this.param + data);}
    else
    {this.obj.open( this.Method,thi s.url + "?" + data);}
    }
    isBusy = true;
    this.obj.onread ystatechange = function()
    {
    if(tObj.readySt ate == 4)
    {
    if(tObj.status == 200)
    {
    var temp = tObj.responseTe xt;
    saveResult(temp );
    isBusy = false;
    }
    }
    }

    if(this.Method. toUpperCase() == "POST")
    {
    data = this.param + encode(data);
    this.obj.send(d ata);
    }
    else
    {this.obj.send( null);}
    }
    }

    function saveResult(_res ult)
    {
    this.obj.result = _result;
    this.obj.isRead y = true;
    }

    function getResult()
    {
    alert(this.obj) ;
    }

    this.setOpenPro perties = setOpenProperti es;
    this.getData = getData;
    this.getResult = getResult;
    }[/code]
    //--------------------------End of script---------------------------

    this AJAX function is called from another js file, assume myMain.js.
    script in myMain.js is pretty simple(like below:

    [code=javascript]//--------------Inside myMain.js------------------------
    var count = 5;
    var obj = new AJAX();

    function display_thumbna il(htmlObj,appr oved_flag)
    {
    var str = "select p_thumImage from products where p_gallery = " + approved_flag;
    obj.setOpenProp erties("POST"," callBackHandler .php","function =query&type=p_i mage&sql=")
    obj.getData(str );
    var isReady = false;
    obj.getResult() ;
    //alert(obj.getRe sult());
    }[/CODE]
    //------------------------End of script--------------------------

    the function "display_thumbn ail" will be called as a part of mouseclick event in one of my html page.

    As you can see in myMain.js, I am trying to get any data that is returned from the call by the XmlHttpRequest. responseText method which is called inside getData function declared in myAJAX.js, but I don't know how to do that "properly". the function getResult will return the data properly after the user clicks on the link which will call the "display_thumbn ail" function once again. In the other words, the first call to getResult always return nothing.

    Can someone help me out with this???
  • acoder
    Recognized Expert MVP
    • Nov 2006
    • 16032

    #2
    Welcome to TSDN!

    I have added code tags for you.

    What is the purpose of line 10 in myMain.js, i.e. setting variable isReady to false?

    Comment

    • praveen2gupta
      New Member
      • May 2007
      • 200

      #3
      Originally posted by nicksname7
      Hi, I am a newbie in the AJAX world. first of all, take a look at my script first:
      assume this script is saved as "myAjax.js"

      //-----------------inside myAjax.js--------------------
      function AJAX()
      {
      var isBusy = false;
      var obj = null;
      var url = "";
      var Method = "";
      var param = "";
      var result = "";
      var isReady;

      if(window.XMLHt tpRequest)
      this.obj = new XMLHttpRequest( );
      else
      {
      try
      {this.obj = new ActiveXObject(" MSXML2.XMLHTTP" );}
      catch(exception )
      {
      try
      {this.obj = new ActiveXObject(" Microsoft.XMLHT TP");}
      catch(exception ){this.obj = null;}
      }
      }
      this.isReady = false;

      function setOpenProperti es(_method,_url ,_param)
      {
      this.url = _url;
      this.Method = _method;
      this.param = _param;
      }

      function getData(data)
      {
      if(this.obj)
      {
      if(isBusy)
      {
      window.status = "busy";
      }
      var tObj = this.obj;
      if(this.Method. toUpperCase() == "POST")
      {
      this.obj.open(t his.Method,this .url);
      this.obj.setReq uestHeader('Con tent-Type', 'application/x-www-form-urlencoded;');
      }
      else
      {
      if(this.param != "")
      {this.obj.open( this.Method,thi s.url + "?" + this.param + data);}
      else
      {this.obj.open( this.Method,thi s.url + "?" + data);}
      }
      isBusy = true;
      this.obj.onread ystatechange = function()
      {
      if(tObj.readySt ate == 4)
      {
      if(tObj.status == 200)
      {
      var temp = tObj.responseTe xt;
      saveResult(temp );
      isBusy = false;
      }
      }
      }

      if(this.Method. toUpperCase() == "POST")
      {
      data = this.param + encode(data);
      this.obj.send(d ata);
      }
      else
      {this.obj.send( null);}
      }
      }

      function saveResult(_res ult)
      {
      this.obj.result = _result;
      this.obj.isRead y = true;
      }

      function getResult()
      {
      alert(this.obj) ;
      }

      this.setOpenPro perties = setOpenProperti es;
      this.getData = getData;
      this.getResult = getResult;
      }
      //--------------------------End of script---------------------------

      this AJAX function is called from another js file, assume myMain.js.
      script in myMain.js is pretty simple(like below:

      //--------------Inside myMain.js------------------------
      var count = 5;
      var obj = new AJAX();

      function display_thumbna il(htmlObj,appr oved_flag)
      {
      var str = "select p_thumImage from products where p_gallery = " + approved_flag;
      obj.setOpenProp erties("POST"," callBackHandler .php","function =query&type=p_i mage&sql=")
      obj.getData(str );
      var isReady = false;
      obj.getResult() ;
      //alert(obj.getRe sult());
      }
      //------------------------End of script--------------------------

      the function "display_thumbn ail" will be called as a part of mouseclick event in one of my html page.

      As you can see in myMain.js, I am trying to get any data that is returned from the call by the XmlHttpRequest. responseText method which is called inside getData function declared in myAJAX.js, but I don't know how to do that "properly". the function getResult will return the data properly after the user clicks on the link which will call the "display_thumbn ail" function once again. In the other words, the first call to getResult always return nothing.

      Can someone help me out with this???
      I think you are not able to display the resturned data / text. The ajax returned is dispalyed in the div tag in the page. You should create an div tag where you wants to display the returned text.
      I am explaning the three major pars of the as separately.
      Plese take help of following code and set in your application. The
      <div id="targetDiv" >
      <p>The fetched data will go here.</p>
      </div> is the location where result will be placed.

      function getData(dataSou rce, divID) , function defined the div where you wants
      to display the result.

      The onmouseover events is calling function getData is defining the name of div tag where result should br returned.

      <input type="button" value="Display Message" onmouseover='ge tData("test.txt ","targetDiv")' >

      please take the help of following code


      Code:
      <html>
      <head>
      <title>Ajax at work</title>
      
      <script language = "javascript">
      var httpObj = false;
      
      	if (window.XMLHttpRequest) 
      	{
      		httpObj = new XMLHttpRequest();
      	} 
      	else if (window.ActiveXObject) 
      	{
      		httpObj = new ActiveXObject("Microsoft.XMLHTTP");
      	}
      
      
      
      
      	function getData(dataSource, divID)
      	{
      		if(httpObj) 
      		{
      			var obj = document.getElementById(divID);
      			httpObj.open("GET", dataSource,true);
      			httpObj.onreadystatechange = function()
      			{
      				if (httpObj.readyState == 4 && httpObj.status == 200) 
      				{
      					obj.innerHTML = httpObj.responseText;
      				}
      			}
      			httpObj.send(null);
      		}
      	}
      </script>
      </head>
      <body>
      <H1>Fetching data with Ajax</H1>
      
      <form>
      <input type="button" value="Display Message" onclick="getData(options1.php','targetDiv')">
      <input type="button" value="Display Message" onmouseover='getData("test.txt","targetDiv")'>
      
      </form>
      
      <div id="targetDiv">
      <p>The fetched data will go here.</p>
      </div>
      </body>
      </html>

      Comment

      • nicksname7
        New Member
        • Jun 2007
        • 2

        #4
        I've recently updated my code and it will look like this:(in myMain.js)

        ------------------------------Beginning of myMain.js-----------------------------------
        function get_thumbnail(h tmlObj,approved _flag)
        {
        var str = "select p_thumImage from products where p_gallery = " + approved_flag;
        obj.setOpenProp erties("POST"," callBackHandler .php","function =query&type=p_i mage&sql=")
        obj.getData(str );
        setTimeout(func tion(){display_ thumbnail(htmlO bj,approved_fla g);},0); //<-- need to use setTimeout to get the result
        htmlObj.classNa me = "";
        htmlObj.innerHT ML = (approved_flag == false)?"Unappro ved images":"Approv ed Images";
        htmlObj.onclick = function(){};
        htmlObj.onmouse over = function(){};
        htmlObj.onmouse out = function(){};
        }

        function display_thumbna il(htmlObj,isAp proved)
        {
        var p_images = obj.getResult() ;
        }
        -------------------------------------End of myMain.js--------------------------------------------

        and for the myAjax.js, it will be look like this:

        -----------------------------------Beginning of myAjax.js--------------------------------------
        function AJAX()
        {
        var isBusy = false;
        var obj = null;
        var url = "";
        var Method = "";
        var param = "";
        var result = "";
        var tempStorage = "images";

        //beginning of constructor part
        if(window.XMLHt tpRequest)
        this.obj = new XMLHttpRequest( );
        else
        {
        try
        {this.obj = new ActiveXObject(" MSXML2.XMLHTTP" );}
        catch(exception )
        {
        try
        {this.obj = new ActiveXObject(" Microsoft.XMLHT TP");}
        catch(exception ){this.obj = null;}
        }
        }
        this.isReady = false;
        //end of constructor part

        function setOpenProperti es(_method,_url ,_param)
        {
        this.url = _url;
        this.Method = _method;
        this.param = _param;
        }

        function getData(data)
        {
        if(this.obj)
        {
        if(isBusy)
        {
        this.obj.onread ystatechange = function(){};
        this.obj.abort( );
        }
        var tObj = this.obj;
        if(this.Method. toUpperCase() == "POST")
        {
        this.obj.open(t his.Method.toUp perCase(),this. url,true);
        this.obj.setReq uestHeader('Con tent-Type', 'application/x-www-form-urlencoded;');
        }
        else
        {
        if(this.param != "")
        {this.obj.open( this.Method.toU pperCase(),this .url + "?" + this.param + data);}
        else
        {this.obj.open( this.Method.toU pperCase(),this .url + "?" + data);}
        }
        isBusy = true;
        this.obj.onread ystatechange = function()
        {
        if(tObj.readySt ate == 4)
        {
        if(tObj.status == 200)
        {
        //saveResult(tObj .responseText);
        saveResult(tObj .responseText);
        isBusy = false;
        }
        }
        }

        if(this.Method. toUpperCase() == "POST")
        {
        data = this.param + encode(data);
        this.obj.send(d ata);
        }
        else
        {this.obj.send( null);}
        }
        }

        function saveResult(rslt )
        {
        this.obj.result = rslt;
        }


        function getResult()
        {
        //return document.getEle mentById(tempSt orage).value;
        //window.status = this.result;
        return this.result;
        }

        this.setOpenPro perties = setOpenProperti es;
        this.getData = getData;
        this.getResult = getResult;
        }
        -----------------------------------------End of myAjax.js--------------------------------------

        Somehow I figured out the problem yesterday, and it was related to the timing.
        If you take a look in "myMain.js" script, I am trying to overcome the timing problem by using the "setTimeout " function; However, I don't really know when the "onreadystatech ange" in myAjax.js function will get the value first before I call the "getResult( )" function.

        The "saveResult(rsl t)" function in myAjax.js is mainly used to save any fetched data resulting from the call to the server database which is triggered inside the "onreadystatech ange" function.

        let's make it simple through the following example:
        suppose I have 2 links in my html file:
        getData1 and getData2
        Assumably, getData1 and getData2 will return a string value of "myData1" and "myData2", respectively. On this scenario I will click the "getData1" link first before "getData2" link.
        the first result by clicking the "getData1" returned "undefined" , followed by "myData1" as a result generated by clicking the "getData2".

        based on that scenario, you can see that during the first call, the getResult() function wasn't actually ready with the value to be returned to the caller.
        my question here is, how do I actually notify the caller whether the result has been fetched or not??

        Comment

        Working...