user1305760
user1305760

Reputation:

Ajax return var with server response

I have this function, just make a simple request to the server, simply AJAX.

( function() {
'use strict';
Request  = { 
    Call: function ( u, theme, params ) { 
      var ajax, t; ajax = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); 
      ajax.onreadystatechange = function() { 
        if ( ajax.readyState == 4 ) { 
          this.Reponse = ajax.responseText; 
        } 
      }; 
      if ( theme == 'POST' ) { 
        ajax.open('POST', u, true); 
        ajax.setRequestHeader('Content-type','application/x-www-form-urlencoded'); 
        ajax.send(params); 
      } 
      else { 
        if ( theme == 'GET' ) { 
          ajax.open('GET', u, true); 
          ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); 
          ajax.send(null); 
        }  
      } 
    },
    Response : null
  } 
})();

I want to store the server's response into a variable, like this :

window.onLoad = function () {
  Request.call('post.php', 'POST', 'bar=foo');
  //then
  document.getElementById('foo').innerHTML = Ajax.Request.Response;
}

Because I want to process the response separately.

Somebody can help me?

Upvotes: 0

Views: 947

Answers (2)

Dion
Dion

Reputation: 3345

Replace

if ( ajax.readyState == 4 ) { 
          this.Reponse = ajax.responseText; 
        } 

with

if(ajax.readyState == 4) { 
          yourfunction(ajax.responseText);
}
[...]
function yourfunction(var response) {
      //use variable response here
}

Upvotes: 1

Starx
Starx

Reputation: 79031

You can access the response using responseText

var response = ajax.responseText

Upvotes: 0

Related Questions