0

I am trying to write the following code using jquery. This reads json from a website and creates a string which I want to return but it always returns "undefined". What am I missing here?

  function getTenders(wardName){
  output = "";
  $.getJSON('http://192.168.1.105:3000/getTenders.json?name='+wardName, function (obj) {
    //console.log(body); // Print the google web page.
    for(var i=0; i < obj.length; i++){
      var pid = "Project id: " + obj[i].id;
      var status = "Status: " + obj[i].status;
      var title = "Title: " + obj[i].title;
      var cost = "Estimated Cost: Rs " + obj[i].estimated;
      output += pid + "\n" + status + "\n" + title + "\n"  + cost + "\n\n";
    }
    console.log("Output: "+ output) // This prints correct output 
    return output // Returning output here 
  });
}

// But this shows undefined

console.log(printTenders("Somevalue")) // This outputs undefined. How can that happen? 
vik-y
  • 449
  • 2
  • 5
  • 14
  • Is $.getJSON also an asynchronous call? – vik-y Mar 20 '16 at 02:40
  • Yes, $.getJSON is an asynchronous call. Also, your function's name is getTenders but you're console logging printTenders, so that's another issue. The link above should be able to explain returning from asynchronous calls better than I :) – Julia Nething Mar 20 '16 at 06:03

0 Answers0