Skip to content Skip to sidebar Skip to footer

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 erro

Solution 1:

missed new, must be:

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

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/

Solution 2:

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.

varXMLHttpFactories = [
    function () {returnnewXMLHttpRequest()},
    function () {returnnewActiveXObject("Msxml2.XMLHTTP")},
    function () {returnnewActiveXObject("Msxml3.XMLHTTP")},
    function () {returnnewActiveXObject("Microsoft.XMLHTTP")}
];

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

Solution 3:

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

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

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

Post a Comment for "Xmlhttprequest Is Not A Function"