1

Possible Duplicate:
How to make an ajax call without jquery?

I have code in js(Ajax) but I want to make it without Ajax(XMLHttpRequest)

$.ajax({
            type:'POST',
            data:'slug='+prize,
            url:'/wybrana-nagroda/',
            success:function(msg)
            {
                $('#whaiting').hide();
                if(msg==='winner') 
                    $(window.location).attr('href','/formularz');
            }
        });

How it should look?

function send(post, url) {
  var client = new XMLHttpRequest();
  client.open("POST", url);
  client.send(message);
}

?

Thanks.

4
  • 2
    developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest Commented Dec 10, 2012 at 18:16
  • stackoverflow.com/questions/8567114/… Commented Dec 10, 2012 at 18:17
  • 1
    Why? Perhaps more insight about what you are trying to do can help others provide a more complete answer. Commented Dec 10, 2012 at 18:22
  • Sometimes in some projects i can not use jquery, and how to do ajax in native javascript without any third-party library ? Commented Dec 10, 2012 at 18:23

1 Answer 1

2

If you want it to be compatible on all browsers, you'll need to do something like the following:

function sendRequest(url,callback,postData) {
    var req = createXMLHTTPObject();
    if (!req) return;
    var method = (postData) ? "POST" : "GET";
    req.open(method,url,true);
    req.setRequestHeader('User-Agent','XMLHTTP/1.0');
    if (postData)
        req.setRequestHeader('Content-type','application/x-www-form-urlencoded');
    req.onreadystatechange = function () {
        if (req.readyState != 4) return;
        if (req.status != 200 && req.status != 304) {
//          alert('HTTP error ' + req.status);
            return;
        }
        callback(req);
    }
    if (req.readyState == 4) return;
    req.send(postData);
}

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;
}

Credit: quirksmode

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.