0

I'm starting out on jquery and ran into a small problem where $.ajax(...) is not working. Actually the whole jquery, javascript business has been tough because of sorting out the problem in case the script doesn't work. this is my code...

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
/*  $.ajax({url:"http://reddit.com/r/nyc.json", success:function(result){
    $("div").text("helloz");
    }});*/
        $("div").text("hello");
});
</script>
</head>
<body>

<div><h2>Let AJAX change this text</h2></div>
<button>Change Content</button>
</body>
</html>

as you can see in the code, I have commented out the .ajax function and instead put some other snippet and it works, proving that jquery is loaded fine and the ready function is working well. However, the .ajax function is not working. My internet connection is working fine and the code works perfectly if I paste this code in w3cschool's tryit editor. Can someone please help me.

Also, any general strategies to solve such bug chases would be really helpful. I have chrome browser but when i open the javascript console, it shows everything as working fine...

shashydhar
  • 801
  • 3
  • 8
  • 26
  • 2
    For a cross-domain request you can't use JSON. Your dataType has to be jsonp. Take a look at this, it should help: http://stackoverflow.com/questions/8191105/how-to-extract-url-data-from-reddit-api-using-json – nbrooks Jul 16 '12 at 05:08
  • @zerkms Yep, but can't delete comment on mobile app. – Dave Newton Jul 16 '12 at 05:11

1 Answers1

6

The problem is url:"http://reddit.com/r/nyc.json", that is not your domain, so the Same origin policy comes out.

You need to make a proxy in your server. Or if the site supports jsonp, you could use jsonp instead.

$.getJSON('http://www.reddit.com/r/nyc.json?jsonp=?', function(data) {
   console.log(data);
});​

The demo.

xdazz
  • 158,678
  • 38
  • 247
  • 274
  • thanks a lot! It worked like a charm. Also thanks for linking the answer to jsfiddle. I didn't know about it and it seems pretty helpful! – shashydhar Jul 16 '12 at 05:26