1

Here's my script:

var Ajax = {

    init: function(){
        try{            
            this.xmlHttp = new XMLHttpRequest();            
        }        
        catch( e ){            
            try{                
                this.xmlHttp = new ActiveXObject( "Microsoft.XMLHttp" );                
            }            
            catch( e ){                
            }            
        }        
        return this;
    },

    get: function( url , async , fn ){
        this.xmlHttp.open( "GET" , url , async );
        console.log( "1" );
        this.xmlHttp.setRequestHeader( 'Content-Type' , 'application/x-www-form-urlencoded' );
        console.log( this.xmlHttp.readyState );
        this.xmlHttp.onreadystatechange = function(){
            console.log( "3" );
            if( this.xmlHttp.readyState == 4 ){
                if( this.xmlHttp.status == 200 ){
                    try{
                        if( fn ) return fn( this.xmlHttp.responseText );
                    }
                    catch( e ){
                        alert( e );
                    }
                }
                else alert( "bad status" );
            }
            else alert( "bad state" );
        }
    }

}

And the line to call it:

Ajax.init().get( "localhost/engine.php" , true , function( txt ){alert(txt)});

Now, at the console I get this:

1
1

Hence, I understand the running stucks at this.xmlHttp.onreadystatechange = function(){ while the readyState is 1. Could you, please, tell me, what's wrong here? Am I missing some bigger error here?

After researching a bit, it seems like the xmlHttp does not really open the url (no request is seen in Chrome's console and Firebug)...

Michael Sazonov
  • 1,531
  • 11
  • 21
  • Does this help: http://stackoverflow.com/questions/751269/ajax-wont-get-past-readystate-1-why – Sudhir Bastakoti Feb 29 '12 at 12:03
  • @Sudhir not really. I need it crossbrowsed, can't depend on `.onload` – Michael Sazonov Feb 29 '12 at 12:05
  • You need to output the value of `readyState` inside the callback for it changing, not directly after you made the request. – Lightness Races in Orbit Feb 29 '12 at 13:40
  • Try to understand [this example,](http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first) it might give you clear idea that whats wrong in your code. Also you can try with debugging your javascript using firebug in mozilla. – Nirmal Feb 29 '12 at 12:23
  • I've been using AJAX for a long time, but not the way I wrote above. I know how it works (or, I guess, I thought I know). The problem is in this script and I just miss it... – Michael Sazonov Feb 29 '12 at 12:29

1 Answers1

2

You are never actually starting the request! Add this at the end of your get() function:

this.xmlHttp.send();

Hope this helps

Leon
  • 4,532
  • 1
  • 19
  • 24