3

I want to get data stored in mysql using jquery and populate it on a web page dynamically. I tried this code but it isnt working.

<html>
<head>
  <script src="jquery-1.7.2.js"></script>
</head>
<body>
<pre>
<script>
  var url = "https://natiweb-natiweb.rhcloud.com/game.php";

  $.getJSON(url,function(data){
    $.each(data,function(i,user){
      alert("inside JSON");
      alert(user.appname+"\n"+user.applink);
      var a = document.createElement('a');
      var linkText = document.createTextNode(user.appname);
      a.appendChild(linkText);

      a.title = linkText;
      a.href = user.applink;
      document.body.appendChild(a);
      var b = document.createElement('br');
      document.body.appendChild(b);

    });
  }
);


</script>
</pre>
</body>
</html>

It never executes getJSON query. i dont know whats wrong. "Inside JSON" doesnt get printed. I tried writing same script code using a dedicated js file and it worked. I want it to work inside body as i have to create links dynamically by getting links from mysql.

Nick Andriopoulos
  • 10,313
  • 6
  • 32
  • 56
user2291144
  • 65
  • 4
  • 14
  • First of all, you should always wrap your code in $(document).ready(function() { or the shortcut, $(function() {}. Perhaps jQuery hasn't finished loading before you call the $.getJSON? –  Apr 17 '13 at 14:29
  • @jqueryrocks you don't need the dom to be ready to make an ajax request. – Kevin B Apr 17 '13 at 14:31
  • 3
    I'm guessing that `https` link is not to your own site, and that this is the usual cross origin issue. You can **not** retrieve data from other domains unless the service supports JSONP or CORS, and JSONP is **not** the same as JSON. If it is to your site, chain in a fail function to see where it fails. – adeneo Apr 17 '13 at 14:35
  • 1
    From the JQuery docs 'Important: As of jQuery 1.4, if the JSON file contains a syntax error, the request will usually fail silently.', just a thought -- have you validated the JSON you are getting back? – gbtimmon Apr 17 '13 at 14:35

2 Answers2

1
  • First, execute your code after document is ready:

     $(function(){
        /* your code */
     });
    

or

     $(document).ready(function(){
        /* your code*/
     });
  • Secondly, use $.ajax, pass in error call back to check whether there's any exceptions.
Stone Shi
  • 106
  • 4
0

+1 adeneo - If you look in the developer console for chrome you'll see you're getting the CORS error. Other than that, your code should work. The JSON returned is fine and your code seems to do the right thing with it, but you're not getting the JSON.

See the answer in this SO XmlHttpRequest error: Origin null is not allowed by Access-Control-Allow-Origin for a good explanation of the resolutions.

Community
  • 1
  • 1
cirrus
  • 5,624
  • 8
  • 44
  • 62