RAUSHAN KUMAR RAUSHAN KUMAR - 2 months ago 14
Ajax Question

how to make a request to other domain using javascript only

I have to make a request to my project URL from the other websites. I created a script file which will be loaded to other websites. The script should make a request to my project specific URL on window load. I have learned about jquery ajax JSON request.

$.ajax({
type: "GET",
url: "http://saskatchewan.univ-ubs.fr:8080/SASStoredProcess/do?_username=DARTIES3-2012&_password=P@ssw0rd&_program=%2FUtilisateurs%2FDARTIES3-2012%2FMon+dossier%2Fanalyse_dc&annee=2012&ind=V&_action=execute",
dataType: "jsonp",
}).success( function( data ) {
$( 'div.ajax-field' ).html( data );
});


But my script will be run on different sites so, I want to make it using javascript only.

Answer

You can use functions provided by the hosting environment through javascript:

   function httpGet(theUrl)
    {
        var xmlHttp = new XMLHttpRequest();
        xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
        xmlHttp.send( null );
        return xmlHttp.responseText;
    }

However, synchronous requests are discouraged, so you might want to use this instead:

function httpGetAsync(theUrl, callback)
{
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function() { 
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
            callback(xmlHttp.responseText);
    }
    xmlHttp.open("GET", theUrl, true); // true for asynchronous 
    xmlHttp.send(null);
}