0

Im trying to write a function that will return data from a locally hosted api so that I can get updated data by calling that function whilst using the var baseUrl = 'http://localhost:3000';

this is my get request:

var baseUrl = 'http://localhost:3000';
function getData(){
    $.ajax({
        type: "GET",
        url: baseUrl + "/jobs", 
        data: "{}",
        success: function(data){
            console.log(data);   
            return data;
        },
        dataType: 'json'
    });

}

Here is an example of setting the response of the request to a variable in a different file:

var myVariable = getData();

when I try to print myVariable it comes back as undefined. Is there a way I can get the returned json object so that I can use it in my program?

kpautler
  • 1
  • 2
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Heretic Monkey Jul 26 '18 at 21:28
  • I would highly recommend reading up on ajax and asynchronous requests. http://learn.jquery.com/ajax/ – Taplar Jul 26 '18 at 21:29
  • Also your variable is undefined, because getData does not return anything. – Taplar Jul 26 '18 at 21:30

1 Answers1

0

$.ajax is asynchronous. That means that, while the request is waiting for a response, the other JavaScript code runs so the user doesn't have to wait. (If the code waits for the response, we call it blocking the thread. Otherwise its non-blocking). As a solution, you will have to write some async code and a callback function:

var baseUrl = 'http://localhost:3000';
function getData(){
$.ajax({
    type: "GET",
    url: baseUrl + "/jobs", 
    data: "{}",
    success: function(data){
        // call the 'callback function'
        myCode(data);
        // the return statement would only return this functions, not the $.ajax method
    },
    dataType: 'json'
});

}

function myCode(data) {
    // use data
}
Uncreative Name
  • 311
  • 2
  • 9