0

Why doesn't this return a value when the function is called? I've tried it with callbacks, and I can't seem to get it to work either. It lets me console.log, but it just won't return it to the tmp variable.

var URL = "https://api.instagram.com/v1/media/popular?client_id=642176ece1e7445e99244cec26f4de1f";

function getData(){
  var tmp;
    $.ajax({
         type: "GET",
         url: URL,
         dataType: "jsonp",
         success: function(result){
          if(result.meta.code == 200){
            tmp = result.data;
            //console.log(result.data);
          }else{
            alert('fail');
            alert(result.meta.error_message);
          }
         }
    });
    return tmp;
}
console.log(getData()); // undefined?

thanks in advance!

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
user3224271
  • 1,214
  • 3
  • 13
  • 22

2 Answers2

0

The ajax method is asynchronous. This means that the calling function will continue without waiting for the ajax call to finish.

This has been explained in more depth, here: How do I return the response from an asynchronous call?

Community
  • 1
  • 1
Jordan Glue
  • 279
  • 2
  • 3
0

I recommend you following method of using Ajax in jQuery

"use strict";

var URL = "https://api.instagram.com/v1/media/popular?client_id=642176ece1e7445e99244cec26f4de1f";

$.ajax({
    type: "GET",
    url: URL,
    dataType: "jsonp",
    success: onInstagramSuccess,
    error: onInstagramError
 });

function onInstagramSuccess(result){
    if(result.meta.code == 200){
        console.log(result.data);
    }
}

function onInstagramError(result){
    if(result.meta.code == 404){
        alert('fail');
        alert(result.meta.error_message);
    }
}

Basically Ajax in Javascript is Asynchronous. It's not going to invoke success or fail method until it actually have received a result from the request.

Jason
  • 1,298
  • 1
  • 16
  • 27