views:

40

answers:

4

Hi guys,

The JSON function below is not returning anything...

$.getJSON(formUrl, function(data) {
                alert(data)
              $('.response').html('<p>' + data.title + '</p>'
                + '<p>' + data.description + '</p>');
            });

the formUrl is correct and returning data in the form of

{"title":"Smashing Magazine","description":"Smashing Magazine is focused on design and web-development. We deliver useful information, latest trends and techniques, useful ideas, innovative approaches and tools."}

Can someone point out what I'm doing wrong? I'm alerting the data and its empty as well...

Thanks!

+2  A: 

Are you calling $.getJSON with a cross-domain URL (ie. from localhost to somewhere else)? That won't work unless you use the JSONP dataType.

sewa
its on my localhost but i'm referring to it absolutely.. ie. formUrl = "http://localhost:8888/NewMT/tools/fetch.php?url=" + $(this).val,would this affect it?
Fearghal
I believe cross-port access don't work either. Are you serving your page from localhost:8888 aswell?
sewa
yes......... ;(
Fearghal
Yes, changed port is not Same Origin, so because of the Same Origin Policy, it fails.
Cipi
A: 

Since it's not of the same origin, you need to add the Access-Control headers to the JSON response.

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET');
BalusC
A: 

Do not break the string in two lines, it will result in error and may be the reason of Javascript not running.

Try something like this: (Notice how I did not break the content inside html() in two lines)

$.getJSON(formUrl, function(data) {
                alert(data);
              $('.response').html('<p>' + data.title + '</p>' + '<p>' + data.description + '</p>');
            });
Vikash
A: 

Try to configure your server to deliver the page fetch.php with a contentType application/json

Also just for a test, you can try to put your JSON into a .../fetch.js file and call it with $.getJSON. It should work, as .js files are application/javascript by default on most servers.

Mic