0

I'm just learning JavaScript Objects and have a question/problem. I have the following code / js object:

CHANGED: This is the complete code - it's a Appcelerator Titanium Project!:

spike.xhr = spike.xhr || {};

spike.xhr.init = function() {
    this.severResponse = '';
    this.xhrMethod = 'GET';
}

spike.xhr.isOnline = function() {
    if( Titanium.Network.online ) {
        return true;
    } else {
        return false;
    }
}

spike.xhr.notOnline = function() {
    var alertDialog = Titanium.UI.createAlertDialog({ 
        title: CONFIG.PROJECT_SHORT, 
        message: 'You do not have an online connect. Please connect...',
        buttonNames: ['Continue'],
        cancel: 0
    }); 
    alertDialog.show(); 
}

spike.xhr.connect = function( url ) {

    if( spike.xhr.isOnline() ) {
        spike.xhr.clients = Ti.Network.createHTTPClient();

        spike.xhr.clients.onload = function() {
            if (spike.xhr.clients.status != 200 && spike.xhr.clients.status != 201) {
                var alertDialog = Titanium.UI.createAlertDialog({ 
                    title: CONFIG.PROJECT_SHORT, 
                    message: 'We are sorry, but we have received an status error!',
                    buttonNames: ['Continue'],
                    cancel: 0
                }); 
                alertDialog.show(); 
                return false;
            }    
            this.serverResponse = this.responseText; 
        }

        spike.xhr.clients.onerror = function(e) {
            Ti.API.log( 'ERROR: ' + e.status + ': ' + e.statusText + ' - ' + e.error );
        }   

        spike.xhr.clients.open( this.xhrMethod, url );

        spike.xhr.clients.send();
    } else {
        spike.xhr.notOnline();
    }
}

spike.xhr.basicAuthentication = function( username, password ) {
    authstr = 'Basic ' +Titanium.Utils.base64encode( username+':'+ password);
    spike.xhr.client.setRequestHeader( 'Authorization', authstr );
}

spike.xhr.setMethod = function( type ) {
    this.xhrMethod = type;
}

spike.xhr.response = function() {
    return this.serverResponse;
}

If I now run:

spike.xhr.connect( 'http://mydomain' );
theResponse = spike.xhr.response();

I get <null> returned! - why do I not get "This is a Test!" back or better question: What do I have to change to get "This is a Test!" back?

6
  • Is XHR some kind of XMLHttpRequest (AJAX) ? Commented Jun 5, 2012 at 15:06
  • 2
    please provide the code of spike.xhr.connect function - probably you're looking for returned value while an ajax call is still running Commented Jun 5, 2012 at 15:06
  • The thing is, when i add an alert(this.serverRepsonse) below this.serverResponse = "This is a test!", i correctly get "This is a test!"?!?!? Commented Jun 5, 2012 at 15:09
  • @StanleyStuart: yes, it should be an object to handle xhr requests. Commented Jun 5, 2012 at 15:10
  • The line containing spike.xhr.response() is executed before the value is changed, likely because an asynchronous call is being made in the connect-function. Commented Jun 5, 2012 at 15:14

1 Answer 1

3

The reason the above code doesn't work is because your spike.xhr.connect function is asynchronous. This means you can tell the browser to make a request, but continue doing other stuff while the browser waits for the response to come back.

JavaScript runs in a single thread, meaning that you can only execute one thing at a time. Certain operations like "AJAX" calls are asynchronous in that the browser knows how to make that request, but doesn't block your currently running code to wait for the request. Typically, asynchronous code is called with a callback function, which runs when the request is returned:

// pseudo code.

spike.xhr.connect( 'http://google.com', function ( response ) {
    alert( 'google' );
});
alert( 'this will fire before spike.xhr.connects callback' );

The callback function will be executed when the response from the server comes back AND the browser isn't doing anything else.

Sign up to request clarification or add additional context in comments.

1 Comment

It looks like spike.xhr.clients.onload is intended as a callback but it doesn't invoke a passed-in callback such as Stanley Stuart is suggesting. With his suggestion, invoke that 2nd parameter as a function within spike.xhr.clients.onload.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.