29

I want to send request parameters to other domain

I already know that Cross Scripting needs JsonP and I have used JsonP with Jquery ajax

but i do not figure out how to do Cross Scripting as using XMLHttpRequest

following code my basic XMLHttpRequest code.

i guess i need to chage xhr.setRequestHeader() and i have to add parsing code

please give me any idea

var xhr;
function createXMLHttpRequest(){    
    if(window.AtiveXObject){
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }else{
        xhr = new XMLHttpRequest();
    }   
    var url = "http://www.helloword.com";   
}

function openRequest(){ 
    createXMLHttpRequest();
    xhr.onreadystatechange = getdata;
    xhr.open("POST",url,true);
    xhr.setRequestHeader("Content-Type",'application/x-www-form-urlencoded');
    xhr.send(data); 
}

function getdata(){
    if(xhr.readyState==4){
        if(xhr.status==200){
            var txt = xhr.responseText;
            alert(txt);
        }
    }   
}
alex9311
  • 1,230
  • 1
  • 18
  • 42
happenask
  • 1,062
  • 3
  • 14
  • 21
  • possible duplicate of [Ways to circumvent the same-origin policy](http://stackoverflow.com/questions/3076414/ways-to-circumvent-the-same-origin-policy) – Quentin Apr 01 '14 at 08:37
  • You can't make POST requests with JSONP. JSONP is not the only method to make cross origin requests. If you need to make a cross origin POST request, use a technique other than JSONP. – Quentin Apr 01 '14 at 08:38
  • you mean If I make Get reqeusts, it is possible? – happenask Apr 01 '14 at 09:10

5 Answers5

71

JSONP does not use XMLHttpRequests.

The reason JSONP is used is to overcome cross-origin restrictions of XHRs.

Instead, the data is retrieved via a script.

function jsonp(url, callback) {
    var callbackName = 'jsonp_callback_' + Math.round(100000 * Math.random());
    window[callbackName] = function(data) {
        delete window[callbackName];
        document.body.removeChild(script);
        callback(data);
    };

    var script = document.createElement('script');
    script.src = url + (url.indexOf('?') >= 0 ? '&' : '?') + 'callback=' + callbackName;
    document.body.appendChild(script);
}

jsonp('http://www.helloword.com', function(data) {
   alert(data);
});

In interest of simplicity, this does not include error handling if the request fails. Use script.onerror if you need that.

Paul Draper
  • 78,542
  • 46
  • 206
  • 285
  • @ Paul Draper: My callbacks are not getting hit. Please look at my code:function pingUrlUsingJSONP(url, callback,onLoad,onError) { var tempCallback = 'jsonp_callback_' + Math.round(100000 * Math.random()); window[tempCallback] = function (data) { delete window[tempCallback]; document.body.removeChild(script);callback(data); }; var script = document.createElement('script'); script.type = 'text/html';script.onerror = onError; script.onload = onLoad;script.async = true; script.src = url + (url.indexOf('?') >= 0 ? '&' : '?') + 'callback=' + tempCallback; document.body.appendChild(script); } – Anantha Jun 06 '15 at 16:18
  • @Paul Drapper can you help me here, http://stackoverflow.com/questions/36302891/convert-jquery-ajax-to-pure-javascript-ajax if ok, thanks – mmativ Mar 30 '16 at 08:20
  • Why create a new callbackname each time? – RyanDay May 04 '18 at 03:54
  • 1
    @RyanDay, because jsonp() can be called with different urls, etc. – Paul Draper May 06 '18 at 01:04
  • This works on my side but how safe is it? And will it fail if its used every x seconds? Is there a php alternative (curl for example)? – Toniq Dec 22 '22 at 21:53
1

I know you already got the answer for but if anyone else out here wanted an example of one using promises here's one.

function jsonp(url) {
    return new Promise(function(resolve, reject) {
        let script = document.createElement('script')
        const name = "_jsonp_" + Math.round(100000 * Math.random());
        //url formatting
        if (url.match(/\?/)) url += "&callback="+name
        else url += "?callback="+name
        script.src = url;

        window[name] = function(data) {
            resolve(data);
            document.body.removeChild(script);
            delete window[name];
        }
        document.body.appendChild(script);
    });
}
var data = jsonp("https://www.google.com");
data.then((res) => {
    console.log(res);
});
Mat Weaver
  • 11
  • 2
1

For google api I was forced to add callback and also v=1.0 parameter to url. Without v=1.0 parameter I get CORB error (for my version and also other answers code - however jQuery $.ajax with dataType: "jsonp" add this parameter - so I add it too and start working )

Cross-Origin Read Blocking (CORB) blocked cross-origin response https://ajax.googleapis.com/ajax/services/feed/load?callback=jsonp1555427800677 with MIME type text/javascript. See https://www.chromestatus.com/feature/5629709824032768 for more details.

Below is promise version of my solution

function jsonp(url) {
  return new Promise(function(resolve, reject) {
    var s = document.createElement('script');
    var f="jsonp"+(+new Date()), b=document.body;
    window[f] = d=>{ delete window[f]; b.removeChild(s); resolve(d); };
    s.src=`${url}${url.includes('?')?'&':'?'}callback=${f}&v=1.0`;
    b.appendChild(s);
  })
}

async function send() {
    let r = await jsonp("http://ajax.googleapis.com/ajax/services/feed/load");
    console.log(r);
}
<button onclick="send()">Send JSONP</button>
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
0
function JsonpHttpRequest(url, callback) {
    var e = document.createElement('script');
    e.src = url;
    document.body.appendChild(script); // fyi remove this element later /assign temp class ..then .remove it later
    //insetead of this you may also create function with  callback value and  use it instead
    window[callback] = (data) => {
        console.log(data);  // heres you data
    }
}
// heres how to use
function HowTouse(params) {
    JsonpHttpRequest("http://localhost:50702/api/values/Getm?num=19&callback=www", "www")
}
Ruslan
  • 6,090
  • 1
  • 21
  • 36
kunal verma
  • 456
  • 5
  • 13
-4

You can not able to do Cross Scripting using XMLHttpRequest.If you want to cross domain with out Jquery, you must create a new script node and set the src attribute of it.

limengjun
  • 183
  • 4
  • 3
    "You can not able to do Cross Scripting using XMLHttpRequest" — Not true. "If you want to cross domain with out Jquery" — jQuery is irrelevant, it is a library, it does nothing you can't do yourself. "you must create a new script node and set the src attribute of it" — Not true, there are other means to make cross origin requests. Also, that's only the last third of how you make a JSONP request, you haven't addressed defining a function or setting the callback argument. – Quentin Apr 01 '14 at 08:39
  • Do you know how jQuery implement crossdomain request?How you can make crossdomain request by XMLHttpRequest?Jsonp has no relationship with XMLHttpRequest – limengjun Apr 02 '14 at 09:44
  • 1
    jQuery has at least three different ways to make cross-origin requests. Ways to make cross-origin requests using XHR are described in the question I marked this as a duplicate of. – Quentin Apr 02 '14 at 09:45