Starx
Starx

Reputation: 78971

Cross Site AJAX Request

What I am exactly trying to build is, an INTERFACE through which a user can send post request to my site and display the response on his browser.

For example

$.post(
     'http://www.mysite.com/thirdpartyrequest.php',
     { param1: value1, param2: value2 },
     function(data) {
         $("#universalid").html(data);//Update with the response
     }
);
//however it is not allowed.

Any Idea how to do such Cross Site Ajax Request

Upvotes: 0

Views: 354

Answers (1)

Martin Algesten
Martin Algesten

Reputation: 13620

Your best bet is to use JSONP. Check out:

http://api.jquery.com/jQuery.getJSON/

http://en.wikipedia.org/wiki/JSON

If you have a server providing data such as:

http://my.server.com/somedata.json

{
   'some': ['fancy', 'json' ],
   'structure: 'here'
}

You turn this into jsonp by providing a callback parameter in the request url - the de facto standard name for it is callback. Then on the server, you need to check this parameter and wrap your result in that callback (effectively turning it into javascript instead of json).

http://my.server.com/somedata.json?callback=receive_this

receive_this({
   'some': ['fancy', 'json' ],
   'structure: 'here'
});

(For the niggly, the response mime type for json should be application/json whilst for jsonp it should be application/javascript)

The client will now (conceptually) load the json like this:

<script type="text/javascript">

   var receive_this = function(json) {

     // do some stuff with data here.

   };

</script>

<script type="text/javascript" src="http://my.server.com/somedata.json?callback=receive_this"></script>

In practice you use something like jQuery to dynamically insert the jsonp request script tag into the DOM. jQuery defaults to calling the callback request parameter callback.

$.ajax({
  url: 'http://my.server.com/somedata.json',
  dataType: 'jsonp',
  success: receive_this
});

Upvotes: 4

Related Questions