Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 14 of 14
  1. #1
    New to the CF scene
    Join Date
    Aug 2008
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    return request from onreadystate

    I'm trying to make my javascript code more dynamic, so I've made an Ajax request class that takes the requesturl as a parameter through the constructor and sends the response back through a method getResponse.

    I'm using onreadystate in asynchronous mode. I've read on a forum that it's the best way.

    My problem is that I can't figure out how to check when onreadystate is completed... Since it's asynchronous it calls the function getResponse before the request is completed...

    Please give me some hints!!!!

    Code:
    var reqObj = new AjaxRequest("http://localhost:8080/AjaxProject/autoGetCities.do?city=b");
    var r  = reqObj.getResponse();
    console.log("Finished" + r.resposeText);
    
    function AjaxRequest(urlStr){ 
      var req; 
      var status = "false";
      
      this.initRequest = initRequest;
      this.doRequest = doRequest;
      this.getResponse = getResponse;
      this.onreadystate = onreadystate;
      
      this.doRequest(urlStr);
      
      function doRequest(url){
        req = this.initRequest();
        req.open("GET", url, true);
        req.onreadystatechange = onreadystate; 
        req.send(null);
      }
      
      function getResponse(){
        if(status=="true"){
          return req;
        }else{
          return null;
        }
      }
      
      function onreadystate(){
        if (req.readyState == 4) {
          if (req.status == 200) {
            if( req.responseText.length > 0){
              status = "true";
            }
          }else if (req.status == 204){
            this.clearTable();
          }
        }    
      }
      
      function initRequest() {
        if (window.XMLHttpRequest) {
          return new XMLHttpRequest();
        } else if (window.ActiveXObject) {
          return new ActiveXObject("Microsoft.XMLHTTP");
        }
      }
    }

  • #2
    Senior Coder A1ien51's Avatar
    Join Date
    Jun 2002
    Location
    Between DC and Baltimore In a Cave
    Posts
    2,717
    Thanks
    1
    Thanked 94 Times in 88 Posts
    It is impossible to do that with an asynchronous request. You need to design your code to work with an asynch request.

    Eric
    Tech Author [Ajax In Action, JavaScript: Visual Blueprint]

  • #3
    Senior Coder
    Join Date
    Oct 2008
    Location
    Long Beach
    Posts
    1,196
    Thanks
    36
    Thanked 164 Times in 164 Posts
    It's not impossible:
    Code:
    /*Author: itsallkizza*/
    function XML_HTTP_Util()
    	{
    	this.sendRequest = function(url,method,params,async,callback,callbackargs)
    		{
    		method = method.toUpperCase();
    		callback = callback || function(){};
    		params = params ? params.join("&") : "";
    		if (method == "GET" && params) url += "?"+params;
    		var req = this.createXMLHTTPObject();
    		if (!req) callback.call(this,false,callbackargs);
    		req.ref = this;
    		req.open(method,url,async);
    		req.setRequestHeader('User-Agent','XMLHTTP/1.0');
    		if (method == "POST")
    			{
    			req.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    			req.setRequestHeader("Content-length",params.length);
    			req.setRequestHeader("Connection","close");
    			}
    		req.onreadystatechange = function()
    			{
    			if (this.readyState != 4) return;
    			if (this.status != 200 && this.status != 304)
    				{
    				//alert("HTTP error " + req.status);
    				callback.call(this.ref,false,callbackargs);
    				}
    			else
    				{
    				callback.call(this.ref,req,callbackargs);
    				}
    			}
    		if (req.readyState == 4) return;
    		req.send(method=="GET"?null:params);
    		}
    	this.createXMLHTTPObject = function()
    		{
    		var xmlhttp = false;
    		for (var i=0;i<this.XMLHttpFactories.length;i++)
    			{
    			try
    				{
    				xmlhttp = this.XMLHttpFactories[i]();
    				}
    			catch(e)
    				{
    				continue;
    				}
    			break;
    			}
    		return xmlhttp;
    		}
    	this.XMLHttpFactories = [
    	function() {return new XMLHttpRequest()},
    	function() {return new ActiveXObject("Msxml2.XMLHTTP")},
    	function() {return new ActiveXObject("Msxml3.XMLHTTP")},
    	function() {return new ActiveXObject("Microsoft.XMLHTTP")}
    	];
    	}
    var xhu = new XML_HTTP_Util();
    I wrote this so you can pass arguments to your callback specific to the request you sent. So you can run it asynchronously and not lose track of which requests were sent when and for what, etc. It will return both the request object and any extra arguments you'd like to pass along as an array.

    Key is in the ECMA Function.call() function.
    Last edited by itsallkizza; 01-03-2009 at 11:07 AM.
    Feel free to e-mail me if I forget to respond ;)
    ohsosexybrit@gmail.com

  • #4
    Senior Coder A1ien51's Avatar
    Join Date
    Jun 2002
    Location
    Between DC and Baltimore In a Cave
    Posts
    2,717
    Thanks
    1
    Thanked 94 Times in 88 Posts
    itsallkizza,

    It sounds like the poster wanted to do something like this:

    Code:
    function foo(){
      //Make Ajax call
      return foo.responseText
    }
    
    var myBar = foo();
    That would require a sych request and not an asych one.

    Eric
    Tech Author [Ajax In Action, JavaScript: Visual Blueprint]

  • #5
    Senior Coder
    Join Date
    Oct 2008
    Location
    Long Beach
    Posts
    1,196
    Thanks
    36
    Thanked 164 Times in 164 Posts
    Strictly adhering to the format you posted - you're right, you'd need to false the async.

    Ultimately though, the title of the OP ("return request from onreadystate") is definitely possible.
    Last edited by itsallkizza; 01-04-2009 at 01:58 AM.
    Feel free to e-mail me if I forget to respond ;)
    ohsosexybrit@gmail.com

  • #6
    New Coder
    Join Date
    Apr 2007
    Posts
    48
    Thanks
    4
    Thanked 1 Time in 1 Post
    Code:
    		req.onreadystatechange = function()
    			{
    			if (this.readyState != 4) return;
    			if (this.status != 200 && this.status != 304)
    				{
    				//alert("HTTP error " + req.status);
    				callback.call(this.ref,false,callbackargs);
    				}
    			else
    				{
    				callback.call(this.ref,req,callbackargs);
    				}
    			}
    Could you explain what the "callback.call...." is trying to do here?



    Also, what is the most efficient method to retrieve information from a "send" command. That is, if I write out some XML in a .php file with an <xmlresponse></xmlresponse> tagged section, is this the most effective way to get at that data/info/etc.? Are there alternate methods?

    Not as slick as what's been posted, but....

    Code:
    function ajaxFunction()
     {
    
    if (window.XMLHttpRequest)
      {
      xmlHttp = new XMLHttpRequest()
      }
    else if (window.ActiveXObject)
      {
      xmlHttp = new ActiveXObject("Microsoft.XMLHTTP")
      }
    
    xmlHttp.onreadystatechange=function()
    {
    if(xmlHttp.readyState==4)
      {
         // get data from XML section <the_text></the_text>
        //  ...  generated from the send request/command
      var response_stat = xmlHttp.responseXML.getElementsByTagName('the_text').item(0).firstChild.data;
      
      }
    
     }
    
      xmlHttp.open("POST","time.php",true);
      xmlHttp.send(null);
    
     }  // close ajaxFunction()

  • #7
    Senior Coder
    Join Date
    Oct 2008
    Location
    Long Beach
    Posts
    1,196
    Thanks
    36
    Thanked 164 Times in 164 Posts
    1) The code you posted is sending your specified callback function the request object along with any variables you attached when sending the request, when the response is received.

    2) You can use responseXML or responseText - either one is parseable using normal DOM functions though with the responseXML method you can begin accessing it's members using childNodes and whatnot right away.
    Feel free to e-mail me if I forget to respond ;)
    ohsosexybrit@gmail.com

  • #8
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,296
    Thanks
    10
    Thanked 583 Times in 564 Posts
    Quote Originally Posted by broncozr View Post
    Could you explain what the "callback.call...." is trying to do here?
    .call allows you to specify what the keyword "this" in your callback function means. it also allows you to pass arguments to the function as you call it.


    Quote Originally Posted by broncozr View Post
    Also, what is the most efficient method to retrieve information from a "send" command. That is, if I write out some XML in a .php file with an <xmlresponse></xmlresponse> tagged section, is this the most effective way to get at that data/info/etc.? Are there alternate methods?


    i strongly recommend json for javascript client consumption instead of xml.
    it's much easier and quicker to write javascript to handle json than xml.
    plus the data is usually a lot more compact as it travels to the client.
    might want to check it out as an alternative to xml/dom headaches, or shaky xslt support.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%

  • #9
    New Coder
    Join Date
    Apr 2007
    Posts
    48
    Thanks
    4
    Thanked 1 Time in 1 Post

    Thumbs up

    kizza and rnd,

    Thanks for the replies. I am an AJAX newbie, but from what I've read, the security risks for using AJAX can be heavy. Is there a book out there that would give me some advice on protecting my sites in the event that I implement AJAX (like Shiflett's PHP Security). I'm actually sorry that I dismissed AJAX in my mind for so long!!!! The possibilities seem endless.

    btw, is navigating the child nodes in XML more dependable than in the document's DOM. How about JSON? I know that it can be done and that there is considerable debate between using, for example, .innerHTML vs. navigating the DOM tree. It seems that for different browsers the DOM has to be navigated in different ways. I'm sure there is cross-browser code for that though.

    Thanks again for your help!!!

  • #10
    Senior Coder
    Join Date
    Oct 2008
    Location
    Long Beach
    Posts
    1,196
    Thanks
    36
    Thanked 164 Times in 164 Posts
    Navigation of the DOM is pretty much cross-browser. If you go the XML route you can use childNodes and whatnot as you would expect, or you can use document.getElementsByTagName/id/etc. I've never experienced any problems in any current browsers traversing the DOM this way.

    JSON is just plain easier because it takes a single line to convert your input to a JS Object. You can then access it's data members in a semantic object-oriented way - the same way you've always done in JS.

    You asked what's more dependable... No matter what route you take, your data is always going to be available to you in the same format in every browser - it doesn't really matter.
    Feel free to e-mail me if I forget to respond ;)
    ohsosexybrit@gmail.com

  • Users who have thanked itsallkizza for this post:

    broncozr (01-06-2009)

  • #11
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,296
    Thanks
    10
    Thanked 583 Times in 564 Posts
    Quote Originally Posted by broncozr View Post
    kizza and rnd,

    Thanks for the replies. I am an AJAX newbie, but from what I've read, the security risks for using AJAX can be heavy.
    i don't think there's any extra security issues associated with ajax that aren't normally present. your page should work without javascript enabled after all...
    all you are doing with ajax is loading user available urls that could, in theory, be typed into an address bar anyway.
    more imposrtantly, don't think that ajax somehow increase the security of your site because the user "sees" fewer urls and actions.


    Quote Originally Posted by broncozr View Post
    btw, is navigating the child nodes in XML more dependable than in the document's DOM. How about JSON? I know that it can be done and that there is considerable debate between using, for example, .innerHTML vs. navigating the DOM tree. It seems that for different browsers the DOM has to be navigated in different ways. I'm sure there is cross-browser code for that though.

    Thanks again for your help!!!
    there is a lot of code and material that answers all your questions in great detail.

    it sounds like you are kinda just starting out.

    some advice:

    if i were you, i would consider playing around with a library like jQuery for a while.

    i historically have sneered at frameworks.
    after all, i make my own libraries and try to personally write all the code i use.
    i am beginning to come around a little however.

    i think of frameworks like a calculator.
    when calculators got cheap, scholars worried that no-one would know how to do long division by hand. i think that were mostly right.

    when you use a framework, you aren't exactly learning javascript, you are learning the framework.
    as you learn you can mix in more and more "regular javascript", so frameworks can be good "training wheels" in some respects.

    in analogy: you won't become a mathematician with a framework, but you might become an accountant.


    here why i think they can be useful to newcomers to web development:

    1. good documentation.
    jQuery and prototype both have great documentation, examples of everything, and lots of places to find cut-and-paste workable code. Microsoft and Mozilla have good documentation as well, but that just leads up to point 2:

    2.they are well supported in all browsers.
    it takes at least 6 months to learn the nooks and crannies of both IE's and firefox's DOM. There are very few people who could name every method and property of every object in both.
    Then you start throwing in iphone and wii browsers, and well, you get the idea. it's honestly very tedious and harder to keep up, and test, than it used to be...

    using a framework means learning how to do something once, and having it work everywhere you want it to once it gets up and running. you don't need to worry about nearly as many bugs and snags, significantly reducing the amount of custom code required for a project.

    3. managing complexity.
    a good programmer knows that they can never know every detail of a complicated system. they know what they need to know, and also know what they don't need to worry about. you have a lot less code to worry about with a framework or library.

    4. shoulders of giants.
    you can often cut and paste then customize tons of widgets, styles, fx, etc. i'e met design students who are not good programmers, but they know about css.
    they can pull of some pretty clean, professional, and compatible pages with stuff they cut and paste and modify the css selectors on.

    it kind of annoyed me because this stuff is supposed to be more complicated.
    it's not fair that it works so well.

    5. not mutually exclusive.
    the most frustrating part of webdev is probably the DOM. a framework spares you a lot of headaches. if you use the resulting "free time" to really concentrate on javascript the language, you can get the best bang for your buck.

    the core language is probably the most consistent piece of the webdev puzzle. it can be learned in a day or two. that said, chess could be learned in an hour or two, but that doesn't mean you'll be a chess master the next day.

    hopefully, in the not-too-distant future, the DOM and surrounding technologies will be fairly consistent and powerful.
    you would have a lot less need for a framework at that point, and by that time you could be pretty skilled at javascript.

    there's lots of room to expand in javascript itself; computer science is a big field.

    you can get into constructors, templates, prototypes, functional programming, closures, object-oriented javascript, inheritance patterns, lambda, performance tuning, the list goes on and on...

    your javascript knowledge would allow you to code widgets, photoshop plugins, flash apps, home-automation systems, etc. you would need to rewire the ins and outs to the new environment, but your logic and data manipulation can remain essentially unchanged.


    I would consider a hybrid approach if i had to do it all over again...
    using a framework for the ins and outs of the browser while refining Jedi abilities on javascript.

    - my two or three cents -
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%

  • Users who have thanked rnd me for this post:

    broncozr (01-06-2009)

  • #12
    New Coder
    Join Date
    Apr 2007
    Posts
    48
    Thanks
    4
    Thanked 1 Time in 1 Post
    Navigation of the DOM is pretty much cross-browser. If you go the XML route you can use childNodes and whatnot as you would expect, or you can use document.getElementsByTagName/id/etc. I've never experienced any problems in any current browsers traversing the DOM this way.
    kizza,

    The examples that I've used so far employ the document.getElementsByTagName approach, and I wondered if there were browswer-compatibility issues. Glad to hear that there aren't w/ XML.




    there's lots of room to expand in javascript itself; computer science is a big field.

    you can get into constructors, templates, prototypes, functional programming, closures, object-oriented javascript, inheritance patterns, lambda, performance tuning, the list goes on and on...
    rnd me,

    I tend to prefer writing my own code like you. I don't like relying on frameworks unless I basically know what's going on underneath the hood. I have played around with some of the PEAR packages w/ PHP, and they do take care of a lot of details. I will try to take a look at jQuery and see what it has to offer.

    I have played around with some of the more powerful sides of JS (e.g. OO, constructors, etc.), but most of my experience has been teaching myself by using online tutorials and cutting/pasting from the examples of others.

  • #13
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,296
    Thanks
    10
    Thanked 583 Times in 564 Posts
    Quote Originally Posted by broncozr View Post
    rnd me,

    I tend to prefer writing my own code like you. I don't like relying on frameworks unless I basically know what's going on underneath the hood. I have played around with some of the PEAR packages w/ PHP, and they do take care of a lot of details. I will try to take a look at jQuery and see what it has to offer.
    my main point is to try to find a way to avoid the pitfalls of dom code.
    you can use a framework as little or as much as you need, after all javascript is always available.
    if you write your own dom handler library, thats a great way to get under the hood.
    it can be a little overwhelming though, there are a lot of tiny details.

    your other question reveals a most suitable argument for some kind of higher level abstraction:
    document.getElementsByTagName will not work in some render modes in some browsers in mixed xml namespaces, like webDAV for instance.
    document.getElementsByTagNameNS will do the trick in browsers that support it.

    JSON is another great way to avoid DOM headaches.
    xslt is pretty well supported at this point as well.
    you can run transforms on the client and avoid the dom that way.
    Last edited by rnd me; 01-07-2009 at 12:00 AM.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%

  • #14
    New Coder
    Join Date
    Apr 2007
    Posts
    48
    Thanks
    4
    Thanked 1 Time in 1 Post
    if you write your own dom handler library, thats a great way to get under the hood.
    it can be a little overwhelming though, there are a lot of tiny details.
    Yes. I have avoided using my own code to traverse the DOM using firstChild, etc. I just didn't think that I could make it cross-browser friendly with what I knew. Instead, I have relied on getElementById and the like to access elements in my pages. I basically have a few blogs that I keep in a database and that's about it; however, I would like to stay up on what's new so that I can write more complex pages...



    JSON is another great way to avoid DOM headaches.
    xslt is pretty well supported at this point as well.
    you can run transforms on the client and avoid the dom that way.
    I appreciate the suggestions. I will look into them. Thanks!


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •