views:

66

answers:

1

hi,

i'm using this code to post to a php page:

var qreq = ".....myurl.php";
$.post(qreq, function(data){alert(data);});

in my PHP file i have this:

......
$prevtopic = $row["topic_id"];
echo $prevtopic;

the alert comes up, but is blank. for some reason data is empty even though i'm echoing from the PHP file. i also tried just echoing "hi" but that didn't work either. what am i doing wrong?

thanks.

+2  A: 

You cannot make a request cross-domain like this, what's blocking you is called the same-origin policy, in place to prevent malicious cross-domain requests (even if your's doesn't have evil intent, it's still blocked).

You can use JSONP for this situation, but not get normal html/text content as you have it. Here's a short writeup with a better description on JSONP, or here for a full example but you need to return JSONP from PHP.

As for the why? It's because http://evil.com/ shouldn't be able to make requests to http://mybank.com without some checks in place, that's why the policy exists.

Nick Craver
Cross-domain GET requests are allowed :)
Anpher
everything in the php executes correctly through this .post, and stuff is inserted into my database. how come this works despite the policy? does the policy just prevent data from being transmitted from the php to js?
vee
@vee - The policy allows you to hit the server, but blocks the response, this is why `data` is empty.
Nick Craver
@Anpher: Not with AJAX, if it's an image, or actually loading a script, iframe, etc sure. But, my page isn't allowed to fire up a request to your gmail page, and get the username field back (if you have auto-completion for example, which most people do)...the server will get the request, but my page won't get the data back...I'm hoping this is for obvious reasons given my examples.
Nick Craver
the "full example" worked, thanks!
vee