2

I send data from Javascript to PHP file using AJAX, but I couldn't take response data back from PHP to Javascript, knowing that Javascript code is in different domain than PHP code. Anyone has an idea to solve this problem?

regards,

6
  • How could your JS send data to PHP in the first place if it's in a different domain? Commented Jun 13, 2012 at 16:35
  • 1
    @MarcB: You can make outgoing AJAX requests to any domain, can't you? Commented Jun 13, 2012 at 16:42
  • possible duplicate of Access Control Allow Origin not allowed by Commented Jun 13, 2012 at 16:42
  • @xbonez: no, that's the whole point of the ajax security model. you can only have JS send a request to the same domain from which the code was loaded. Otherwise you could have a user's browser spam any site they wanted with ajax requests. It's not like google.com would say "oh, hey, this request came from some JS code loaded from yahoo.com. I'll just not respond" Commented Jun 13, 2012 at 16:44
  • @MarcB: How come I can make an AJAX request to another domain, in that case, in this example: jsfiddle.net/cLdGY/8. I don't think the issue is that Google would reject the incoming request. The issue is that the response sent by Google would be rejected by Yahoo saying "I don't know where this response is coming from, so I won't trust it." Commented Jun 13, 2012 at 16:53

3 Answers 3

3

To receive a response in JS cross-domain, you can either enable CORS by adding the Access-Control-Allow-Origin header. However, this can be spotty.

A better solution would be to send back your response encoded as JSONP.

Here's an example using JSONP. The API I'm calling is my own which supports JSONP responses. JSONP Example

In contrast, the following example also works. In this case, I am not using JSONP. This request works because my API is CORS enabled. However, like I said, I have found this to be spotty, and would recommend JSONP.

CORS Example

Sign up to request clarification or add additional context in comments.

Comments

1

Cross-domain javascript can be difficult. Take a look at http://easyxdm.net/wp/

Comments

0

AFAIK there isn't a way to send ajax request to a different domain for security reasons. I can think of some aproachs to workaround:

  • Call a php proxy that then make the request trough sockets or curl. Example
  • make a flash movie that call it and set a crossdomain.xml file

2 Comments

re: AFAIK there isn't a way to send ajax request to a different domain for security reasons, JSONP is the common way to do this, today. en.wikipedia.org/wiki/JSONP
i hadn't heard about it.Interesting, i wouldn't use it directly for security concerns though

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.