esafwan
esafwan

Reputation: 18029

Jquery Post to external php

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?

Upvotes: 0

Views: 3585

Answers (4)

Pekka
Pekka

Reputation: 449425

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.

Upvotes: 3

sillyMunky
sillyMunky

Reputation: 1278

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 :)

Upvotes: 0

BrunoLM
BrunoLM

Reputation: 100331

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", ...);

Upvotes: 2

Alex
Alex

Reputation: 7374

Or using GET, for example:

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

Upvotes: 0

Related Questions