views:

43

answers:

4

I want to post to an external php file and get the result. It a php that i have hosted in my server online. I want the static page in my localhost post by ajax and load the html in a div. But I'm not able to do this.

$.post("http://www.site.com/index.php", { font: "panchami", input: "hi" } );

Is there anything wrong in this?

+3  A: 

The Same Origin Policy prevents Ajax calls to external domains.

Popular workarounds include

  • JSONP
  • Embedding the data in an iframe instead
  • Using a server-side proxy the does the fetching (see @BrunoLM's answer for a PHP example; it is possible in any server-side language)
  • YUI's Get as shown in @Alex's answer

depending on what your use case is.

Pekka
A: 

Or using GET, for example:

http://developer.yahoo.com/yui/get/

Alex
+2  A: 

Javascript doesn't allow cross domain requests.

What you can do is a PHP file on your server that reads the contents of the other site:

<?php echo file_get_contents($_REQUEST['url']); ?>

Then make requests to your file, like so:

$.post("proxy.php?url=external_url", ...);
BrunoLM
The PHP proxy approach is a very attractive one, but note that the code shown can be misused as a generic proxy, which is bad. You will want to build in some security measures, e.g. check for the `REFERER` or a limited list of possible target URLs
Pekka
A: 

This kind of request is dangerous, it is called a Cross-Site request and is forbidden by most browsers. If you look in your error console you should see a message to that effect.

If you really have no alternative then you can consider using iframes, the src attribute can be outside the current domain and you can parse the information using javascript.

Hope that helps :)

sillyMunky