BlackFire27
BlackFire27

Reputation: 1550

Javascript request across domains

I am trying to make a request across domains like that:

    var script=document.createElement('script');
    script.setAttribute('src',"http://www.example.com/wordpress/register/?callback=callbackF&ver=2.5&url="+encodeURIComponent(window.location.href));
    script.setAttribute("type", "text/javascript");
    script.setAttribute("id", "spark_grazit_script");
    document.getElementById("spark_static_widget").parentNode.appendChild(script);

As the script will be created, it will be appended to the div that i have and there will be a request. At the end of the request:

   function callbackF(data){
            console.log('Response has finished'+data);
        }

That function should be triggered at the end of the request. All I want is to get the callback function called.

I dont get a cross domain error. But I get this error:

Uncaught SyntaxError: Unexpected token : 

Is there a way to achieve what I want without resorting to html5 or jsonp. Can I somehow still get a response with ajax?

UPDATE: The response is a simple json object

This is the response:

{ "userid":"24645", "token":"40A164ECA4DE4A4F", "script":"<script type='text/javascript'>var dbnwid=16211; var dbnpid=23113; var dbnwebid=19459; var dbnlayout=21; var dbncolor='#000000'; var dbntitlefontsize='14'; var dbnbgcolortype=1; var dbnheader='You might enjoy reading:'; var dbnremindercolor=2; var dbn_protocol = (('https:' == document.location.protocol) ? 'https://' : 'http://'); </script>"}

Upvotes: 1

Views: 76

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074385

Is there a way to achieve what I want without resorting to html5 or jsonp. Can I somehow still get a response with ajax?

You're not using ajax. You're doing JSONP (or something functionally identical).

The response from http://www.eya.com/wordpress/register/?callback=callbackF&ver=2.5&url= must be a valid script fragment. From your error message, it isn't. (What I get back when I try it is a 404 page, which would tend to be an invalid script.)


Update: Your response is a valid JSON object, but not a valid JavaScript fragment, because the opening { looks like the beginning of a block rather than the beginning of an object literal to the parser, because it doesn't appear where an expression is expected.

To make it work the way you describe (which is JSONP), the response must wrap that object in the call to the callback named in the URL, like this:

callbackF({ "userid":"24645", "token":"40A164ECA4DE4A4F", "script":"<script type='text/javascript'>var dbnwid=16211; var dbnpid=23113; var dbnwebid=19459; var dbnlayout=21; var dbncolor='#000000'; var dbntitlefontsize='14'; var dbnbgcolortype=1; var dbnheader='You might enjoy reading:'; var dbnremindercolor=2; var dbn_protocol = (('https:' == document.location.protocol) ? 'https://' : 'http://'); </script>"})

More about JSONP here.

Upvotes: 2

Related Questions