0

When I click the test button I get no result, no errors whatsoever. As you can probably see I'm extremely beginner when it comes to javascript. What solutions will you recommend so I can write this "class" in order to work? I want it to work more like jQuery ajax call $.ajax({}); ...

var Ajax = function(){

        this.method = null;
        this.url = null;
        this.headerType = null;
        this.data = null;

        function request (callback) {
            var xml = new XMLHttpRequest();

            xml.open(this.method, this.url, true);
            xml.setRequestHeader(this.headerType || "Content-type", "application/x-www-form-urlencoded");

            xml.onreadystatechange = function() {
                if(xml.readyState == 4) {
                    if(xml.status == 200) {
                        callback(xml.responseText);
                    }
                }
            }
            xml.send(this.data || null);
        }
    }

document.getElementById('test').addEventListener('click', function() {
        Ajax({
            method : 'GET',
            url : 'test.php',
            request : function(response) {
                document.getElementById('testResult').innerHTML =  response;
            }
        });
    });

thank you

EDIT: here is the html code

<button id="test">Get data</button>
<div id="testResult"></div>
lesandru
  • 839
  • 2
  • 11
  • 27

4 Answers4

1

Something like this will set you in the right direction; I didn't test this, but it should work...good luck!

var Ajax = function(options){
    var method = options.method || null,
        url = options.url || null,
        headerType = options.headerType || null,
        data = options.data || '',
        request = options.request || null; // callback function

    var _request = function(callback) {
        var xml = new XMLHttpRequest();

        xml.open(method, url, true);
        xml.setRequestHeader(headerType || "Content-type", "application/x-www-form-urlencoded");

        xml.onreadystatechange = function() {
            if(xml.readyState == 4) {
                if(xml.status == 200) {
                    callback(xml.responseText);
                }
            }
        }
        xml.send(data || null);
    }

    _request(request);
}
blakev
  • 4,154
  • 2
  • 32
  • 52
  • thank you so much. It worked like a charm now I understand what @epascarello was trying to explain me. And thank you very much to all of you who also came with different solutions – lesandru May 22 '14 at 13:26
1

You need to understand what your call to Ajax() is doing. By using {} with properties, you are passing an object literal to the function, as the argument. Therefore you need some code inside the function to capture the argument and set the properties.

Once you capture the argument and options, you need to call your request() function, and pass it the callback option.

Your use of this in the function is incorrect, because you don't call the function with any context, therefore it will refer to the window object, and subsequently will make your variables global (the same as doing window.method = null.

    var Ajax = function(customOptions){

        var options = {
            method : null,
            url : null,
            headerType : null,
            data : null,
            request : function(){ }
        };

        // override the defaults
        options = merge_options(options, customOptions); // see note below

        // call the request() function
        request(options.request);

        // modified below to use options.x not this.x
        function request (callback) {
            var xml = new XMLHttpRequest();

            xml.open(options.method, options.url, true);
            xml.setRequestHeader(options.headerType || "Content-type", "application/x-www-form-urlencoded");

            xml.onreadystatechange = function() {
                if(xml.readyState == 4) {
                    if(xml.status == 200) {
                        options.callback(xml.responseText);
                    }
                }
            }
            xml.send(options.data || null);
        }
    }

Note: In the above, merge_options() is not a built in function, you can find the source of it in this answer, which you must include if you want to use it.

Community
  • 1
  • 1
MrCode
  • 63,975
  • 10
  • 90
  • 112
0

Well, either make it a function that takes confuguration object for an argument:

function Ajax(config) { 
    if(config==null)
      ERROR!
    if(config.method == null)
      config.method = "GET";
    ... check the values and use default or throw errors
    function request (callback) {
        var xml = new XMLHttpRequest();

        xml.open(config.method, config.url, true);
        .... and so on
    }

}

Or make it really OOP (keep the 'class' the same and use it like following):

var ajax = new Ajax();
ajax.method = "GET"
...
ajax.send();

//Only change to the class
function Ajax() {
   ... keep the former script
   this.send = function() {
       request();  //That is the function you defined, remember?
   }

And why this.send? Because anything you define using var and function within a pseudo-class is not accessible from outside.

General concept of javascript classes is this:

function Class(construct_argument1) {
    //refference to this for private and anonymous functions
    var _this = this;    //The underscore means nothing. It could be as well 'that' or anything you like
    var private_variable;
    function privateMethod() {
        private_variable = _this.public_variable;
    }
    this.publicMethod = function() {
        alert("Private variable value: "+private_variable);
    }
    this.public_variable = null;
 }
 //For classes with many instances, it's good to define methods in prototype
 //These methods, however, have no private access
 Class.prototype.methodThatDoesntEatAllRam = function() {};
Tomáš Zato
  • 50,171
  • 52
  • 268
  • 778
-1

Did you try onclick function on tag?

<button id="test" onclick="javascript:alert('hello world')">

You can call any javascript function.

Alex
  • 23
  • 5
  • That's not the problem. Also, this "solution" is [despised](http://stackoverflow.com/a/6348597/1048572), [wrong](http://stackoverflow.com/q/372159/1048572), and incorrect - you cannot call any javascript function, but only global ones. – Bergi May 22 '14 at 13:39