Question

Attempting something a bit complicated and I hope it is possible, or someone might suggest a way to do it.

On site A I have a database with booking information.

On site B I want to show people when these bookings are taking place.

So on site A I create a php page which takes all of that data and puts it into JSON.

I then create a js script to run an ajax call to that php page, return the information and use javascript to create a table and build it wherever the script was called.

Kind of like twitter's widget.

Now what I want to do, is have a couple of lines of code pasted into site B, which calls the js script on site A, which runs the ajax command, then gets the data, creates the table I mentioned and puts it on site B.

Is that possible? Will the script make the ajax call on site A before passing it to site B? Or will it not be able to do the ajax call because it is put on site B first and I can't call to site A from site B?

Was it helpful?

Solution

It is possible but the way is a bit different from you suggested.

Firstly to answer your questions: When you include that "data fetcher" script from site A on site B, it will be executed on Site B. It will try to perform ajax call to site A and will fail because of same-origin policy.

The way to accomplish this is via JSONP.

You need to first create a php page, which produces some json data and calls a predefined javascript function like:

fetcher.php:

<?php
$data = fetchCustomerBookings($_GET['customerid']);
echo "renderBookings(".json_encode($data).")";
?>

Then you can include this script on Site B with an ordinary script tag like:

<script type="text/javascript" src="http://site-a.com/fetcher.php?customerid=XXX"></script>

There you need to have defined renderBookings javascript function already.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top