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.

Community
  • 1
  • 1
Sekhmet
  • 523
  • 1
  • 7
  • 21

1 Answers1

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

wanovak
  • 6,117
  • 25
  • 32