0

I've made a JavaScript class to make Ajax requests easier.

My class :

var ajax =
{
    method:"GET",
    action:"",
    data : "",
    result: "",

    setResult : function(re){this.result = re;},
    setMethod : function(method){this.method = method.toUpperCase();},
    setAction : function(page){this.action = page;},
    addData : function(name,value){data_for_setting_data = name+"="+value+"&";this.data += data_for_setting_data;},

    send : function()
    {
        var XMLHttpRequestObject = false;
        if(window.XMLHttpRequest)
            XMLHttpRequestObject = new XMLHttpRequest();
        else if(window.ActiveXObject)
            XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
        else
        {
            try
            {
                XMLHttpRequestObject = new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch(e)
            {
                return false;
            }
        }
        if(XMLHttpRequestObject)
        {
            var resulter;
            datalength = this.data.length;
            datasender = this.data.substr(0,datalength-1);
            switch(this.method)
            {
                case "GET" :
                    XMLHttpRequestObject.open("GET",this.action+"?"+datasender,true);
                    XMLHttpRequestObject.onreadystatechange = function()
                    {
                        if(XMLHttpRequestObject.readyState == 4)
                        {
                            this.result = XMLHttpRequestObject.responseText;
                        }
                    }
                    XMLHttpRequestObject.send(null);
                ;
                break;
                case "POST" :
                    XMLHttpRequestObject.open("POST",this.action,true);
                    XMLHttpRequestObject.setRequestHeader("Content-type","application/x-www-form-urlencoded");
                    XMLHttpRequestObject.send(datasender);
                    XMLHttpRequestObject.onreadystatechange = function()
                    {
                        if(XMLHttpRequestObject.readyState == 4)
                        {
                            this.result = XMLHttpRequestObject.responseText;
                        }
                    }                   
                ;break;
            }
        }
    }
}

When I send a data like this :

ajax.setAction("a.php");
ajax.setMethod("get");
ajax.addData("myname","mohsen");
ajax.send();
alert(ajax.result);

the result will be nothing.

But for example, on line 44, if I use

alert(XMLHttpRequestObject.responseText)

instead of

this.result = XMLHttpRequestObject.responseText; 

it will work correctly.

What should I do to solve this problem ?

And one more question: Does it reduce loading speed?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • 1
    Is there any reason why you cannot use jQuery's [`$.ajax()`](http://api.jquery.com/jQuery.ajax/)? – Aiias Jun 09 '13 at 07:25
  • Yes . Because Ajax's Directory Is Too Heavy For Client Part And It's Not A Goof Idea To Use That Just For Ajax !And Of Course I Have Other Reasons that is for my site ... – Mohsen Nemati Jun 09 '13 at 07:27
  • 1
    You are trying to access `ajax.result` **before** it was set. Ajax is **asychronous**. That's why you have to assign a callback to `XMLHttpRequestObject.onreadystatechange`. Have a look at http://stackoverflow.com/q/14220321/218196 to learn the differences between synchronous code and asynchronous code and to handle the response of Ajax calls. You have to work with *callbacks*. – Felix Kling Jun 09 '13 at 07:29
  • My English Is Not Good you Know :(( – Mohsen Nemati Jun 09 '13 at 07:40
  • Still Don't know what to do. – Mohsen Nemati Jun 09 '13 at 07:41
  • Should you be checking against `if(XMLHttpRequestObject.readyState==4 && XMLHttpRequestObject.status==200)` ? – Aiias Jun 09 '13 at 07:45
  • I did that still have that problem it returs nothing ... – Mohsen Nemati Jun 09 '13 at 07:47
  • Please Help I Am Getting Crazy :(( – Mohsen Nemati Jun 09 '13 at 07:50
  • AJAX is ASYNCHRONOUS, as someone said before. It means it will not wait until data is loaded, control is passed. When data is loaded, the "onreadystatechange" event will fire and there is where you need to define an "event handler" function. – Alejandro Iván Jun 10 '13 at 02:19
  • You shouldn't have this behaviour wrapped in a singleton. Consider using constructors and prototypes. – Ja͢ck Jun 10 '13 at 02:19

1 Answers1

1

The problem is this.result, this does not refer to your ajax variable. To fix this, change to:

ajax.result = XMLHttpRequestObject.responseText;

Or declare a variable to hold the current context object:

send : function()
    {
       var self = this;

And use it like this:

self.result = XMLHttpRequestObject.responseText;

One more problem with your code. Because ajax is asyn, when you call alert(ajax.result);. The response from the server may not arrive yet. To fix the asyn problem, you could either use syn request by setting the final parameter to false (although this approach is not recommended as it blocks the browser, the app will appear hung if the request takes long time to complete)

XMLHttpRequestObject.open("GET",this.action+"?"+datasender,false);

Or pass in a callback function. When the ajax response has arrived, call it:

 send : function(callback){
  ....your code
      if(XMLHttpRequestObject.readyState == 4)
      {
            if (typeof callback === "function"){ 
                callback(XMLHttpRequestObject.responseText);
            }
      }
 }

Use it like this:

ajax.send(function(result){
      alert(result);
});
Khanh TO
  • 48,509
  • 13
  • 99
  • 115