0

I am trying to learn JS by building a random Quote Machine but this problem has been bugging me. I saw the other answers but I really couldn't understand them due to lack of context. Any help will be appreciated. The code is:

$(document).ready(function () {


$("#btn").click(function () {
getQuote();                 //This should execute first, then the next lines
var quoteData = jSonify();
var quote = quoteData[0];
var author = quoteData[1];
console.log(quote);
console.log(author);
console.log("Button Clicked");//This Should execute last.
});

//Get them quotes
function getQuote() {
    $.ajax({
        url: 'https://andruxnet-random-famous-quotes.p.mashape.com/?cat=famous',
        type: 'GET',
        data: {},
        datatype: 'json',
        success: function (data) { jSonify(data); },
        error: function (err) { alert(err); },
        beforeSend: function (xhr) {
            xhr.setRequestHeader("X-Mashape-Authorization", "qKPbfOzWKemsh2qi30QgbOA1WufXp1ok1NsjsnAkvh6yVJfaAk");
        }
    });
}

//Convert to jSon
function jSonify(rawData) {
    var jSonified = jQuery.parseJSON(rawData);
    var quote = jSonified.quote;
    var author = jSonified.author;
    console.log(quote);
    console.log(author);
    return [quote, author];
}});
Lord_Rhaziel
  • 81
  • 1
  • 5

2 Answers2

2

getQuote() won't be done by the time JavaScript runs the next line, var quoteData = jSonify();. This is because it has a $.ajax call inside of it, which could take a long time to complete.

getQuote won't be done until the success method in the $.ajax method is called.

So what you need to do is pass a callback into getQuote, like so:

$("#btn").click(function () {
    getQuote(function() {
        var quoteData = jSonify();
        var quote = quoteData[0];
        var author = quoteData[1];
        console.log(quote);
        console.log(author);
        console.log("Button Clicked");
    });
});

//Get them quotes
function getQuote(done) {
    $.ajax({
        url: 'https://andruxnet-random-famous-quotes.p.mashape.com/?cat=famous',
        type: 'GET',
        data: {},
        datatype: 'json',
        success: function (data) { jSonify(data); done(); }, // Call the callback!
        error: function (err) { alert(err); },
        beforeSend: function (xhr) {
            xhr.setRequestHeader("X-Mashape-Authorization", "qKPbfOzWKemsh2qi30QgbOA1WufXp1ok1NsjsnAkvh6yVJfaAk");
        }
    });
}

The callback will only be called once the ajax has actually finished. Once it's called, the rest of the computation will take place.

thedayturns
  • 9,723
  • 5
  • 33
  • 41
  • I learned about callback function when trying to solve this but somehow I could not figure out how to use this in my own code. Thank you for teaching me. I will try this now and hopefully grasp this concept of callback functions. – Lord_Rhaziel Jan 21 '17 at 07:28
  • I finally get it. I am calling getQuote with another function as a parameter and when getQuote runs the 'success' part, which contains a call to the parameter it runs the parameter which is itself a function,which is what I needed. Wow, neat !! Thank you again. – Lord_Rhaziel Jan 21 '17 at 14:37
1

you can embed later to be called statements inside ajax success

$(document).ready(function () {


$("#btn").click(function () {
getQuote();                 //This should execute first, then the next lines

});

//Get them quotes
function getQuote() {
    $.ajax({
        url: 'https://andruxnet-random-famous-quotes.p.mashape.com/?cat=famous',
        type: 'GET',
        data: {},
        datatype: 'json',
        success: function (data) {          
            var quoteData = jSonify(data);
            var quote = quoteData[0];
            var author = quoteData[1];
            console.log(quote);
            console.log(author);
            console.log("Button Clicked");//This Should execute last.
        },
        error: function (err) { alert(err); },
        beforeSend: function (xhr) {
            xhr.setRequestHeader("X-Mashape-Authorization", "qKPbfOzWKemsh2qi30QgbOA1WufXp1ok1NsjsnAkvh6yVJfaAk");
        }
    });
}

//Convert to jSon
function jSonify(rawData) {
    var jSonified = jQuery.parseJSON(rawData);
    var quote = jSonified.quote;
    var author = jSonified.author;
    console.log(quote);
    console.log(author);
    return [quote, author];
}});
Chandan Rai
  • 9,879
  • 2
  • 20
  • 28
  • I could do that, in fact that was the solution I came up with too. But I wanted the code to be structured better/modularity so I discarded it. Thanks for the help. – Lord_Rhaziel Jan 21 '17 at 07:19