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);
        }
    }   
}
3
  • possible duplicate of Ways to circumvent the same-origin policy Commented Apr 1, 2014 at 8: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. Commented Apr 1, 2014 at 8:38
  • you mean If I make Get reqeusts, it is possible? Commented Apr 1, 2014 at 9:10

5 Answers 5

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.

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

5 Comments

@ 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); }
@Paul Drapper can you help me here, stackoverflow.com/questions/36302891/… if ok, thanks
Why create a new callbackname each time?
@RyanDay, because jsonp() can be called with different urls, etc.
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)?
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);
});

1 Comment

Try running your code. It doesn't work because google.com doesn't return JSONP (at least, not at that URL)
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>

Comments

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")
}

Comments

-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.

3 Comments

"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.
Do you know how jQuery implement crossdomain request?How you can make crossdomain request by XMLHttpRequest?Jsonp has no relationship with XMLHttpRequest
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.