1
$(document).ready(function() {
      var output = "<div>";
     $.getJSON('https://search-a.akamaihd.net/typeahead/suggest/?solrformat=true&rows=20&callback=noCB&q=*%3A*+AND+schoolid_s%3A1255&defType=edismax&qf=teacherfirstname_t%5E2000+teacherlastname_t%5E2000+teacherfullname_t%5E2000+autosuggest&bf=pow(total_number_of_ratings_i%2C2.1)&sort=total_number_of_ratings_i+desc&siteName=rmp&rows=20&start=0&fl=pk_id+teacherfirstname_t+teacherlastname_t+total_number_of_ratings_i+averageratingscore_rf+schoolid_s&fq=&prefix=schoolname_t%3A%22University+of+Texas+at+Austin%22&callback=?' , function(data) {

        for (var professor in data.noCB.response.docs) {  //where the error might be
           output += "a"
        }
       output += "</div>"
   });
   document.getElementById("listt").innerHTML = output;
});

This is the url that I call to get the JSON data :

This is the url with the data :

JSON Data

I get the error - noCB is not defined .

I guess I'm trying to access the JSON object the wrong way - but I'm unsure about the right way. Please let me know - I'm a beginner.

Explorer
  • 1,491
  • 4
  • 26
  • 67
Bonny Mahajan
  • 81
  • 1
  • 10

1 Answers1

3

The response you're getting is using JSONP (not JSON). Instead of data.noCB.response.docs, you'd just use data.response.docs. noCB isn't part of the object, it's a function call (that's how JSONP works).

You also want to remove callback=noCB from the URL, so that jQuery will handle the JSONP plumbing for you.

You have a couple of other issues as well:

  1. You're trying to use output before you've filled it in. See How do I return the response from an asynchronous call? for details.

  2. Don't use for-in to loop through arrays unless you do it advisedly with safeguards; see For-each over an array in JavaScript? for details.

Finally, not an issue per se, but as long as you're using jQuery, you may as well use it for things like document.getElementById("listt").innerHTML = output; (e.g.: $("#listt").html(output);).

Example:

$(document).ready(function() {
  var output = "<div>";
  $.getJSON('https://search-a.akamaihd.net/typeahead/suggest/?solrformat=true&rows=20&q=*%3A*+AND+schoolid_s%3A1255&defType=edismax&qf=teacherfirstname_t%5E2000+teacherlastname_t%5E2000+teacherfullname_t%5E2000+autosuggest&bf=pow(total_number_of_ratings_i%2C2.1)&sort=total_number_of_ratings_i+desc&siteName=rmp&rows=20&start=0&fl=pk_id+teacherfirstname_t+teacherlastname_t+total_number_of_ratings_i+averageratingscore_rf+schoolid_s&fq=&prefix=schoolname_t%3A%22University+of+Texas+at+Austin%22&callback=?', function(data) {
    data.response.docs.forEach(function(doc) {
      output += "a";
    });
    output += "</div>";
    document.getElementById("listt").innerHTML = output;
  });
});
<div id="listt"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875