0

I am trying to use my response from the ajax call to loop through the response outside of the ajax call. In the code I have I only see the object it self and it starts to for-loop through the decription of the object not what is in it. And how do I stop it from refresh the page afterwards?

$(document).ready(function() {
    var jsonResult;
    $.ajax({
        type: 'GET',
        url: 'http://example.com/test.json',
        data: {
            get_param: 'value'
        },
        dataType: "json",
        success: function(data) {
            jsonResult = data;
        }
    });
    $("#form").submit(function(jsonResult) {
        var userAnswer = $("#useranswer").val();
        for (var key in jsonResult) {
            if (jsonResult[key] === userAnswer) {
                $("#confirmed").html("Yes");
                break;
            } else {
                $("#confirmed").html("No");
            }
        }
        return false;
    });
});
A88amanda
  • 5
  • 1
  • 3

1 Answers1

0

the easiest shortcut is to put an async = false in ajax property

the problem here is the jsonresult is initialized before the ajax call is completed

a synchronus call is shortcut but not recomended at all it will block all other calls to server you can also try a callback function too

RAHUL S R
  • 1,569
  • 1
  • 11
  • 20
  • Thanks! The problem now is that the key starts at 0. Even though I dont have a 0 in my jsonResult. I guess that's the index, but I'd like to compare to the value that index 0 has. Do you have any idea how I do that? – A88amanda Mar 23 '17 at 08:44
  • the key is index of the array thats why its 0 , uoy can assign something like this.value and this .text instead of indexing the array if the jsonresult is an object like {'value' = '1','text'=' some text '} just look at the network monitering tool in browser and chck the response – RAHUL S R Mar 23 '17 at 09:07
  • 1
    @A88amanda Never *ever* use `async: false`. It's horrendous practice. In fact if you check the console the browser will give you a warning telling you not to do it. See the question I marked as duplicate for a much, much better solution – Rory McCrossan Mar 23 '17 at 09:16
  • Thanks, turned out I didn't need async or callback. But thank to you both. It was very helpful! – A88amanda Mar 23 '17 at 09:52