Focus in Textbox when the page is Loaded through Ajax

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • webhead
    New Member
    • Mar 2006
    • 56

    #16
    Originally posted by pbmods
    Couple of things to change:

    Code:
    //var http = getHTTPObject(); 
    .
    .
    .
    function initAjax(url, callback) {
    	var http = getHTTPObject();
    .
    .
    .
    	}
    Moved the "var http = getHTTPObject() ;" to initAjax, but since it's no longer global I assume I must add that line to any other functions, right? My page won't load at all so I went ahead and added it to other functions, but I must have it in the wrong place since it still won't load. Example:
    Code:
    function nutherFunction(theButton) {
    	str = "moreStuff.php?button="+theButton;
            // add line here
            var http = getHTTPObject();
    	//
            http.open("GET", str, true);
    	http.onreadystatechange = handleHttpResponse;
    	http.send(null);
    	}

    Comment

    • pbmods
      Recognized Expert Expert
      • Apr 2007
      • 5821

      #17
      Originally posted by webhead
      Moved the "var http = getHTTPObject() ;" to initAjax, but since it's no longer global I assume I must add that line to any other functions, right?
      The idea is to use initAjax to handle all of your AJAX calls. In other words:

      Code:
      function doSomething() {
      	initAjax('thepage.php?arg=val', function(ajax_response) {
      		alert(ajax_response.responseText);
      		recno.focus();
      	});
      }
      
      function doSomethingElse() {
      	initAjax('anotherpage.php?and=so&on=', function(ajax_response) {
      		recno.fetch();
      		recno.rollOver();
      		recno.playDead();
      		
      		//	Or if you prefer...
      		recno.whaddyaMeanMyTransmissionIsShotAllIWantedWasAnOilChange();
      	});
      }
      In the examples above, doSomething and doSomethingElse call initAjax, which creates the XMLHttpRequest object and then executes the callback function. So neither doSomething nor doSomethingElse has to deal with any of that.

      Comment

      • webhead
        New Member
        • Mar 2006
        • 56

        #18
        Aaaahhhhh, I see. (Can't tell I'm a n00b at AJAX can ya? Or that I even had anything working at all just by copy/paste from sketchy tutorials?)

        So now it goes a little something like this:

        Code:
        function getFunky() {
        	url = "doStuff.php?button=add";
        	initAjax(url, function response(){ --- stuff here if needed --- });
        	}
        And "function response" can be empty between the {} if I don't have other things to do after that, right?

        But... still no page loading. Checking code for typos...

        Comment

        • webhead
          New Member
          • Mar 2006
          • 56

          #19
          This can't be right:
          Code:
          function initAjax(url, callback) {
          	var http = getHTTPObject(); 
          	var http = new XMLHttpRequest();
          	http.open("GET", url, true);
          	http.onreadystatechange = callback;
          	http.send(null);
          	}

          Comment

          • pbmods
            Recognized Expert Expert
            • Apr 2007
            • 5821

            #20
            Originally posted by webhead
            Aaaahhhhh, I see. (Can't tell I'm a n00b at AJAX can ya? Or that I even had anything working at all just by copy/paste from sketchy tutorials?)
            We've all been there. With time, all things pass :)

            Originally posted by webhead
            And "function response" can be empty between the {} if I don't have other things to do after that, right?
            Alrightey. Buckle down and forget everything you learned about JavaScript. Here we go.

            JavaScript is fiercely object-oriented. Just about everything is an object. 2 is an instance of the Number class. 'Hello, World!' is an instance of the String class. And getFunky (in the example above) is an instance of the Function class.

            As I noted above, when you type this:

            Code:
            function getFunky(mark) { return mark * 5; }
            JavaScript treats it like this:
            Code:
            getFunky = new Function('mark', 'return mark * 5;');
            The browser creates a new global variable called 'getFunky', and assigns it an instance of the Function class with one argument ('mark'), and a function body ('return mark * 5;');

            The two statements are equivalent, but the browser will automatically use the latter form at runtime.

            Remember that. All functions in JavaScript are actually Function objects.

            Ok, so with that in mind, consider this: When you invoke a function, and you pass arguments to that function, sometimes you use 'literals' instead of variables. Here's an example:

            Code:
            doSomething(5);
            
            var mark = 5;
            doSomething(mark);
            In both cases, you're passing the number 5 to doSomething. But in the first statement, you use the 'literal' 5, whereas in the second set of instructions, you're passing the variable 'mark', which has a value of 5.

            So far so good?

            Now, since in JavaScript, the number 5 is actually an instance of the Number class, you could also do this:

            Code:
            doSomething(new Number(5));
            This statement creates a new instance of the Number class, assigns it the value of 5 and passes it to doSomething.

            Ok. Now, instead of a Number object, let's use a Function object. We'll start with an easy one:

            Code:
            function myFunc(x) { return x * 5; }
            //  Which is the same as:
            //  myFunc = new Function('x', 'return x * 5;');
            
            alert(myFunc);
            What happens here, keeping in mind that myFunc is a variable that stores a Function object?

            The output of the alert statement, btw, is outside the scope of this post, so we'll just move on to the next part:

            Code:
            //  Remember from before where we passed a literal to a function:
            alert(10);
            alert(new Number(10));
            //  Or...
            alert('Hello, World!');
            alert(new String('Hello, World!'));
            
            //  We can also pass a Function 'literal':
            alert(function(x) { return x * 5; });
            alert(new Function('x', 'return x * 5;'));
            Note that, just like 10 or 'Hello, World!', there is no variable that stores the function you created in those last two statements; they are called "anonymous functions".

            Still with me?

            So going back to your code, when you type:

            Code:
            initAjax(url, function(response) {
            });
            which is identical to this:

            Code:
            initAjax(url, new Function('response', ''));
            You're actually creating a new anonymous function which takes one argument (response, which will store the returned object from your XMLHttpRequest call automatically [and you don't have to worry about it; just assume that it will]).

            Now, let's take a look at initAjax:

            Code:
            function initAjax(url, callback)
            Note that url is a String object, and callback is a Function object. callback stores the anonymous function that you created when you invoked initAjax in the last code block.

            Likewise, when you do this:

            Code:
            http.onreadystatechange = callback;
            You are copying the function stored in callback to http.onreadysta techange. When http's readystate changes, it will check to see if there is a function stored in its onreadystatecha nge property, which in this case is (technically a copy of) the anonymous function you created when you invoked initAjax.

            Hope that answered a few more questions than it generated.

            And also, you are correct:

            Originally posted by webhead
            This can't be right:
            Code:
            function initAjax(url, callback) {
            	var http = getHTTPObject(); 
            	var http = new XMLHttpRequest();
            	http.open("GET", url, true);
            	http.onreadystatechange = callback;
            	http.send(null);
            	}
            Get rid of this line:
            Code:
            var http = new XMLHttpRequest();
            Since you brought in the getHTTPObject function, you no longer need that line. getHTTPObject will create a new XMLHttpRequest object (or some Microsoft thing if you're using IE) and return it.

            In this case, initAjax stores the returned object to the variable http.

            Code:
            function initAjax(url, callback) {
            	var http = getHTTPObject(); 
            	http.open("GET", url, true);
            	http.onreadystatechange = callback;
            	http.send(null);
            	}

            Comment

            • webhead
              New Member
              • Mar 2006
              • 56

              #21
              Originally posted by pbmods
              We've all been there. With time, all things pass :)
              Yes, but now and then you need a little Ex-Lax to get things moving ;-)

              Alrightey. Buckle down and forget everything you learned about JavaScript. Here we go....

              Code:
              function myFunc(x) { return x * 5; }
              //  Which is the same as:
              //  myFunc = new Function('x', 'return x * 5;');
              
              alert(myFunc);
              What happens here, keeping in mind that myFunc is a variable that stores a Function object?
              So anything "new" creates a variable that holds a string, number, or function, right? So if I pass an empty function { } it's just like passing an empty string.

              ...

              Code:
              initAjax(url, new Function('response', ''));
              You're actually creating a new anonymous function which takes one argument (response, which will store the returned object from your XMLHttpRequest call automatically [and you don't have to worry about it; just assume that it will]).
              A little fuzzy on how that works but right now I'm happy to take your word for it.

              Question: We used to do
              Code:
              http.onreadystatechange = http.responseText;;
              instead of
              Code:
              http.onreadystatechange = callback;
              . When do we do http.responseTe xt now?

              Still no page load, so I started the old put alerts everywhere thing, and it seems to go through all the right motions, yet nothing is put out. I tried it also on a much simpler part of my app, a section in another frame that just puts out a "rate card" of values used in calculations for an invoice. It displays the numbers and takes any changes, only this and nothing more.

              Yet no output. But it's small so I'll try and post the whole thing here:
              Code:
              theOutput = 'output'; 
              function handleHttpResponse() {
              	if (http.readyState == 4) {
              		document.getElementById(theOutput).innerHTML = http.responseText;
              		}
              	}
              
              function getHTTPObject() {
              	var xmlhttp;
              	/*@cc_on
              	@if (@_jscript_version >= 5)
              		try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); } 
              		catch (e) {
              			try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } 
              			catch (E) { xmlhttp = false; }
              			}
              	@else
              		xmlhttp = false;
              		@end @*/
              		if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
              			try { xmlhttp = new XMLHttpRequest(); } 
              			catch (e) { xmlhttp = false; }
              			}
              		return xmlhttp;
              	}
              
              function initAjax(url, callback) {
              	var http = getHTTPObject(); 
              	http.open("GET", url, true);
              	http.onreadystatechange = callback;
              	http.send(null);
              	}
              /////////////////////////////////////////////////////////////////////////////////
              function getRatecard() {
              	url = "Rfunc.php";
              	initAjax(url, function response(){ });
              	}	
              
              function rChange(theField) {
              	fldnam=document.getElementById(theField).name;
              	fldval=document.getElementById(theField).value;
              	url = 'Rfunc.php?fldn='+fldnam+'&fldv='+fldval; 
              	initAjax(url, function response(){ });
              	} 
              
              function rReport() {
              	url = 'Rfunc.php?report=recvbls'; 
              	initAjax(url, function response(){ });
              	}

              Comment

              • webhead
                New Member
                • Mar 2006
                • 56

                #22
                Interesting:
                Code:
                function getRatecard() {
                	url = "Rfunc.php";
                	initAjax(url, function response(){ document.getElementById(theOutput).innerHTML = http.responseText; }); 
                	}
                puts out nothing but:
                Code:
                function getRatecard() {
                	url = "Rfunc.php";
                	initAjax(url, function response(){ document.getElementById(theOutput).innerHTML = 'blah'; }); 
                	}
                puts out "blah". Looks like we just aren't putting anything into ...innerHTML, because by the time we get to that statement the responseText is gone.

                Comment

                • pbmods
                  Recognized Expert Expert
                  • Apr 2007
                  • 5821

                  #23
                  Go back and reread my last post.

                  Comment

                  • pbmods
                    Recognized Expert Expert
                    • Apr 2007
                    • 5821

                    #24
                    Originally posted by webhead
                    So anything "new" creates a variable that holds a string, number, or function, right? So if I pass an empty function { } it's just like passing an empty string.
                    Basically, considering that when you pass an empty string, you're actually passing an instance of the String class without a value:

                    Code:
                    doSomething('') === doSomething(new String(''));
                    doSomething(function() {}) === doSomething(new Function('', ''));
                    Question: We used to do
                    Code:
                    http.onreadystatechange = http.responseText;;
                    instead of
                    Code:
                    http.onreadystatechange = callback;
                    . When do we do http.responseTe xt now?
                    This is where that 'response' that you keep confusing for the function's name comes into play.

                    NOTE WHERE I PUT 'RESPONSE'. IT GOES INSIDE THE PARENTHESIS.

                    Code:
                    initAjax(url, function (response) { eval(response.responseText); });
                    
                    initAjax(url, new Function('response', 'eval(response.responseText);'));
                    The two statements do exactly the same thing. Remember that when http.onreadysta techange fires, it will automatically pass the result as the first parameter.

                    Fix your callbacks, and things should start working.

                    Comment

                    • webhead
                      New Member
                      • Mar 2006
                      • 56

                      #25
                      Oops, how did I do that with the ()? Fixed, added the eval, but still nothing. Tried this too and still nothing:
                      Code:
                      function initAjax(url, callback) {
                      	var http = getHTTPObject(); 
                      	http.open("GET", url, true); 
                      	http.onreadystatechange = callback;
                      	http.send(null);
                      	}
                      
                      function getRatecard() {
                      	url = "Rfunc.php";
                      	initAjax(url, function (response) { 
                      		eval(response.responseText); 
                      		document.getElementById(theOutput).innerHTML = response.responseText;
                      		}); 
                      	}
                      Sorry I'm not catching on too well, maybe I need to go back and find some more beginner tutorials. But you've been a most patient teacher and I am very grateful for your help.

                      Comment

                      • pbmods
                        Recognized Expert Expert
                        • Apr 2007
                        • 5821

                        #26
                        Originally posted by webhead
                        Oops, how did I do that with the ()? Fixed, added the eval, but still nothing. Tried this too and still nothing:
                        Code:
                        function initAjax(url, callback) {
                        	var http = getHTTPObject(); 
                        	http.open("GET", url, true); 
                        	http.onreadystatechange = callback;
                        	http.send(null);
                        	}
                        
                        function getRatecard() {
                        	url = "Rfunc.php";
                        	initAjax(url, function (response) { 
                        		eval(response.responseText); 
                        		document.getElementById(theOutput).innerHTML = response.responseText;
                        		}); 
                        	}
                        Ok, this is looking pretty good. But now we have a conflict:

                        Code:
                        		eval(response.responseText); 
                        		document.getElementById(theOutput).innerHTML = response.responseText;
                        I used the 'eval' line just as an example, because I wasn't sure what you were getting back from your server-side script. But it looks like the script is sending HTML, not JavaScript. So you can go ahead and remove the 'eval' line (since eval(html code) will produce an error):

                        Code:
                        function getRatecard() {
                        	url = "Rfunc.php";
                        	initAjax(url, function (response) { 
                        		document.getElementById(theOutput).innerHTML = response.responseText;
                        		}); 
                        	}
                        Sorry I'm not catching on too well, maybe I need to go back and find some more beginner tutorials. But you've been a most patient teacher and I am very grateful for your help.
                        I'm having fun, I promise. I know we all make typos occasionally (I happen to hold the world record for typos per hour, and I broke it three times last weeek^K^Kk). I apologize for my outburst.

                        Comment

                        • webhead
                          New Member
                          • Mar 2006
                          • 56

                          #27
                          Code:
                          function getRatecard() {
                          	url = "Rfunc.php";
                          	initAjax(url, function (response) { 
                          		document.getElementById(theOutput).innerHTML = response.responseText;
                          		}); 
                          	}
                          Done, but still nothing from "response.respo nseText;". Is it possible we need to wait for "http.readyStat e == 4"? I tried putting that around the "...innerHTML.. ." line but still nothing.

                          Originally posted by pbmods
                          I'm having fun, I promise. I know we all make typos occasionally (I happen to hold the world record for typos per hour, and I broke it three times last weeek^K^Kk). I apologize for my outburst.
                          No prob. I know I can get on people's nerves with endless questions, especially when it's free edjamakashun. Thanks again.

                          Comment

                          • pbmods
                            Recognized Expert Expert
                            • Apr 2007
                            • 5821

                            #28
                            Originally posted by webhead
                            Done, but still nothing from "response.respo nseText;". Is it possible we need to wait for "http.readyStat e == 4"?
                            Ooh. Good point. Alrightey. Let's add another layer of complexity to initAjax:

                            Code:
                            function initAjax(url, callback) {
                            	var http = getHTTPObject(); 
                            	http.open("GET", url, true); 
                            	http.onreadystatechange = function(response) {
                            		if(response.readyState == 4)
                            			callback(response);
                            	};
                            	http.send(null);
                            	}
                            We create a new anonymous function that checks for response's readyState (remember that response is set to the result from the AJAX call automatically when you assign it to http.onreadysta techange; http is undefined outside of initAjax, so we pass the response through callbacks). If it is 4, then we call callback and pass the response to it. Otherwise, we do nothing.

                            I tried putting that around the "...innerHTML.. ." line but still nothing.
                            Hm.

                            Try alerting your responseText to see if your script is sending anything back to you.

                            Code:
                            initAjax(url, function (response) { 
                            		alert(response.responseText);
                            		});

                            Comment

                            • webhead
                              New Member
                              • Mar 2006
                              • 56

                              #29
                              Originally posted by pbmods
                              Try alerting your responseText to see if your script is sending anything back to you.
                              Code:
                              initAjax(url, function (response) { 
                              		alert(response.responseText);
                              		});
                              Tried this:
                              Code:
                              function initAjax(url, callback) {
                              	var http = getHTTPObject(); 
                              	http.open("GET", url, true);
                              	http.onreadystatechange = function(response) {
                              		if (response.readyState == 4) { callback(response); } 
                              		};
                              	alert('ack');
                              	http.send(null);
                              	}
                              
                              function getTestpage() { 
                              	url = "afunc.php";
                              	initAjax(url, function (response) { 
                              			document.getElementById(theOutput).innerHTML = response.responseText;
                              			alert(response.responseText);
                              		});
                              	alert('done');
                              	}
                              I get alerts for "ack" and "done" but not "response.respo nseText". Not even a blank alert, no alert at all.

                              Comment

                              • pbmods
                                Recognized Expert Expert
                                • Apr 2007
                                • 5821

                                #30
                                Originally posted by webhead
                                Tried this:
                                Code:
                                function initAjax(url, callback) {
                                	var http = getHTTPObject(); 
                                	http.open("GET", url, true);
                                	http.onreadystatechange = function(response) {
                                		if (response.readyState == 4) { callback(response); } 
                                		};
                                	alert('ack');
                                	http.send(null);
                                	}
                                
                                function getTestpage() { 
                                	url = "afunc.php";
                                	initAjax(url, function (response) { 
                                			document.getElementById(theOutput).innerHTML = response.responseText;
                                			alert(response.responseText);
                                		});
                                	alert('done');
                                	}
                                I get alerts for "ack" and "done" but not "response.respo nseText". Not even a blank alert, no alert at all.
                                Here's why you're not seeing anything:

                                heh

                                Because http actually *isn't* automatically assigning a value to response. I went back and looked at my AJAX frameworks, and it turns out that you have to manually do this.

                                Yeah. *sheepish grin*

                                So anyway, here's what initAjax *really* should look like (are we having fun yet?):

                                Code:
                                function initAjax(url, callback) {
                                	var http = getHTTPObject(); 
                                	http.open("GET", url, true);
                                	http.onreadystatechange = function() {
                                		if (http.readyState == 4) { callback(http); } 
                                		};
                                	http.send(null);
                                	}

                                Comment

                                Working...