1

I use pure JavaScript to make ajax call in another domain (cross-domain).

So i need to specify the dataType. But i don't know, where to specify ?.

I use the following to make ajax call with javascript:

    var xmlhttp = new XMLHttpRequest();
    var url = 'www.mydomain.com/path/to/reach';

    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == XMLHttpRequest.DONE) {
            if (xmlhttp.status == 200) {
                console.log('Log : ' + url + ' || Updated.');
            }
            else if (xmlhttp.status == 400) {
                alert('There was an error 400');
            }
            else {
                alert('something else other than 200 was returned');
            }
        }
    };

    url = url + '?callback=my_callback_method';

    xmlhttp.open("GET", url, true);
    xmlhttp.send();

Also i make dummy callback,

   function my_callback_method(res){
    //
   }

But, it won't work. I get error as Reason: CORS header ‘Access-Control-Allow-Origin’ missing.

What's wrong with my code ?

Is it possible ?

Any Solutions ?

(I need Solution for JavaScript Only !)

0

1 Answer 1

1

I get error as Reason: CORS header ‘Access-Control-Allow-Origin’ missing.

This is because you're using XMLHttpRequest and usage of XMLHttpRequest requires CORS. The JSONP technique doesn't involve usage of XMLHttpRequest. The trick in JSONP is to create a script tag and let a browser load that script:

var script = document.createElement('script');
script.src = '//domain.com/path/to/jsonp?callback=my_callback_method'

document.getElementsByTagName('head')[0].appendChild(script);

Also, you need to create a global function, in your case its my_callback_method, and call it from the jsonp script.

Certainly, you server side should have implementation that when a request to //domain.com/path/to/jsonp is obtained, it should return a js document with a call to a global function specified in callback=my_callback_method:

my_callback_method()
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.