views:

309

answers:

1

Hello there,

Here is the issue. Suppose there is a DOMAIN A which is going to be the server containing a PHP Script file. The data from Domain A is to be accessed by a Client at DOMAIN B.

I know it cannot be accessed directly using JavaScript. So what I did is, in Domain A I created a a JavaScript file as front-end for the PHP Script which AJAXes the PHP and returns the data. But unfortunately it din't work

I came across an example having PHP as a Middle Man in the client side. But I donot want to keep any server side PHP code as a middle man in the client side. I just want to give out the Javascript to the client domain.

http://stackoverflow.com/questions/578095/how-to-get-data-with-javascript-from-another-server

DOMAIN A

PHP - data.php

<?php echo "Server returns data"; ?>

JS - example.js

Does the Ajax to the PHP

function getData()
{
   //assume ajax is done for data.php and data is retrieved, now return the data
   return ajaxed_data;
}

Domain B

JS

Client includes the example.js file from Domain A in his HTML

<script type="text/javascript" src="http://www.DomainA.com/example.js"&gt;&lt;/script&gt;
<script type="text/javascript">
     alert(getData());
</script>

I hope I have made myself understandable ! Can this be established ? Its something like Google friend connect, what I mean is, just provide JavaScript to the client and thats it. Every thing carried out in server side

Thankx for providing this forum

+3  A: 

You could use JSONP. jQuery has a good support for it.

DOMAIN A - data.php:

<?php
    $data = '{ "data" : "Server returns data" }';
    echo $_GET['jsoncallback'] . '(' . $data . ');';
?>

DOMAIN B - client:

$.getJSON('http://domainA.com/data.php?jsoncallback=?', function(json) {
    alert(json.data);
});
Darin Dimitrov
Thanx for the solution, but it seems that it is not working across cross domains. If the server and client are in the same domain, its working, else no.
Shoaib
Could you define *not working*? The jQuery page I've linked to has a proof of concept example with pictures from Flickr showing cross domain ajax with JSONP. Can you show your code so far? Is a request sent to your php page? What does FireBug console show? I've just realized that I made a small typo in my post by using the `message` property in the js callback instead of `data`. I've fixed my post accordingly.
Darin Dimitrov
The problem remains the same i think ! Javascript can't access the server in cross domain directly. It needs an intermediate. I Used ajax from jQuery. JSON also giving the same response. null data is being retrieved.
Shoaib
thanx.. Its working now. I guess it was just the typo that caused the problem. Thanx a lot
Shoaib