Reputation: 12335
I have a jquery script as below:
$.ajax({
type: "GET",
url: "http://www.site.com/v4/ajax/get_song_info.php",
data: ({id : song_id }),
dataType: "json",
success: function(data)
{
alert( "Data: " + data );
}
});
And the associated php page:
<?php
include_once '../connect.php';
$song_id = $_GET['id'];
$query = mysql_query("SELECT * FROM songs WHERE id = '$song_id' LIMIT 1");
$song = mysql_fetch_row($query);
$song_info = array( htmlentities($song[3]) , htmlentities($song[4]) );
header('Content-Type: application/json');
echo json_encode($song_info);
?>
The php returns something like this when I call it on its own in a browser: ["Peaches","I Feel Cream (Proxy Remix)"]
However when I make the jQuery call my alert shows 'Data: null'
Upvotes: 0
Views: 615
Reputation: 1074989
I notice that you've used an absolute URL rather than a relative one. If your page isn't also being served from http://www.site.com
, you're running into the Same Origin Policy. The SOP is a security mechanism implemented by browsers.
You have a couple of options for working around this. If you're in control of the server and you don't need to support IE6 or IE7, you can implement Cross-Origin Resource Sharing. In most modern browsers, if the server is CORS-enabled, your ajax calls will just start working (the browser handles it under-the-covers). IE6 and IE7 don't have any support for CORS, though, and IE8's requires that the client-side code do something special.
Another option is JSONP, which makes use of the fact that although you can't do a cross-origin ajax call (unless you have CORS), it's perfectly okay for a page to load a script from a remote host. So you load the script, which includes the data and which calls you back to let you know it's there. The advantage of JSONP is that it works with all major browsers, right now. And jQuery has JSONP support built into its ajax
call.
Upvotes: 1