0

I am written the bookmarklet, which takes pictures and videos from a site and must send it to my server via AJAX. The problem is in crossdomain AJAX request - I have got an error:

XMLHttpRequest cannot load http://mysite.com/community/bookmarklet/. Origin http://www.some-nice-site.com is not allowed by Access-Control-Allow-Origin.

How to solve data sending to my server from third-part sites?

Note: I use only plane javascript, this is the stipulation of development.

my code:

function getXmlHttp(){
  var xmlhttp;
  if (typeof XMLHttpRequest!='undefined') {
    xmlhttp = new XMLHttpRequest();
  } else {      
    try {
      xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (E) {
        xmlhttp = false;
      }
    }  
  };  
  return xmlhttp;
};

function vote(data) {
  var req = getXmlHttp();
  req.onready = function() {
    if (req.readyState == 4 & req.status == 200) {
      alert('OK');
    }
  }
  req.open('GET', 'http://mydomain.com/community/bookmarklet/');
  req.send(JSON.stringify(data()));
};

function dataProcessing(){
  //some processing
  return data;
};

// I tried it, but not deeply understand.
function JSONPresponse(){
  document.getElementById('popup_body').innerHTML = 'done!';
};
(function(){
  function pasteIt(){
    // this function is builds the form, which get data for dispatch to my server.
  };

  pasteIt();
  document.getElementById('my_button').addEventListener('click', function()    {vote(dataProcessing)}, false);
}());
I159
  • 29,741
  • 31
  • 97
  • 132
  • A tricky hack might be to use a hidden `iframe` and append the `stringify`-ed text to the `src` URL. Just saying.. – Some Guy Dec 19 '11 at 12:19
  • 2
    You'll have to use [JSONP](http://en.wikipedia.org/wiki/JSONP) for this. – jabclab Dec 19 '11 at 12:22
  • 1
    Instead of using the XHR you'll have to dynamically create a ` – jabclab Dec 19 '11 at 16:09

2 Answers2

0

It is quite clear... the site you are attempting is prohibiting connection from outside world. You can try by modifying your http headers in request. See:

Community
  • 1
  • 1
check123
  • 1,989
  • 2
  • 22
  • 28
0

As @jakeclarkson told - JSON-P is the solution, not the only, but useful for me.

XMLHttpRequest is not needed anymore. Instead it vote(data) function creates the script to build URL with params:

function vote(data) {
  var script = document.createElement('script'),
  data = JSON.stringify(data());
  script.type = 'text/javascript';
  script.src = 'http://mysite.com/api/bookmarklet/?vids='+encodeURIComponent(data);
  document.getElementsByTagName('head')[0].appendChild(script);
};

The script is fulfilled, so URL is called and params already in the server.

I159
  • 29,741
  • 31
  • 97
  • 132