Emil Laine
Emil Laine

Reputation: 42828

XMLHttpRequest is not a function

I'm trying to write some client-side JavaScript using XMLHttpRequest:

$('#someId').on('input', function() {
  var req = XMLHttpRequest();
  // …
});

but I get the following error:

XMLHttpRequest is not a function. (In 'XMLHttpRequest()', 'XMLHttpRequest' is an instance of XMLHttpRequestConstructor)

How to fix this?

Upvotes: 0

Views: 1673

Answers (3)

Aditya Singh
Aditya Singh

Reputation: 16650

XMLHttpRequest is a constructor and not a (usual) function in JavaScript and you need to use new XMLHttpRequest()

$('#someId').on('input', function() {
  var req = new XMLHttpRequest();
  // …
});

Refer this MDN article on using XMLHttpRequest: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest

Upvotes: 1

Ali Mamedov
Ali Mamedov

Reputation: 5256

If you are already using jQuery, you can make ajax requests with $.ajax() method:

Example:

$('#someId').on('input', function() {

    $.ajax({

        url: 'some_file.php',
        data: {

            postparam_1: 'ok',
            postparam_2: 'no'
        },
        method: 'get',
        success: function(x) {

            alert(x); // string result from server
        },
        error: function() {

            alert('Error!');
        }
    });
});

If you want to use It in your app you have to retrieve XmlHttpRequest object that works across all browsers.

var XMLHttpFactories = [
    function () {return new XMLHttpRequest()},
    function () {return new ActiveXObject("Msxml2.XMLHTTP")},
    function () {return new ActiveXObject("Msxml3.XMLHTTP")},
    function () {return new ActiveXObject("Microsoft.XMLHTTP")}
];

function createXMLHTTPObject() {
    var xmlhttp = false;
    for (var i=0;i<XMLHttpFactories.length;i++) {
        try {
            xmlhttp = XMLHttpFactories[i]();
        }
        catch (e) {
            continue;
        }
        break;
    }
    return xmlhttp;
}

Upvotes: 1

Andrew Evt
Andrew Evt

Reputation: 3689

missed new, must be:

$('#someId').on('input', function() {
  var req = new XMLHttpRequest();
  // …
});

you can read more about XHRHttpRequest here -
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest

and how to work with it here -
https://developer.mozilla.org/ru/docs/XMLHttpRequest
(only this page translation exists yet, but google translate can help a lot :) )

p.s. If you are using jQuery - better to use $.ajax() as @synthet1c said.

Read more about it here - http://api.jquery.com/jquery.ajax/

Upvotes: 3

Related Questions