0

On my click event, I am trying to open a bootstrap modal. Modal has some values, which I am trying to get from ajax call using getJSON. Problem is that the getJSON is fired at last when the jQuery function ends.

Here is my code:

$('.poplinks').popover().parent().on('click', '.insert-submission', function () {
            var baKey = 8701;
            var obj;

            $.getJSON('/urltogetobjectwithvalue/', {id: baKey}, function (result) {
                debugger; //it comes here at last after modal('show') executes
                obj = result;
            });

            debugger; //first it come here
            $("#span_unk_sub_baid").html(baKey);
            if (obj !== undefined)
                $("#span_unk_sub_baid").append(' Eff Date: ' + obj.EffectiveDate);

            $('#dialog_ins_purc').modal('show'); //now it will go to $.getJSON
        });

I want to show some values which I am getting from JSON call. After the modal is loaded, then it goes to get values. How to I make sure, json call is made in the same sequence I want. Please help.

sarojanand
  • 607
  • 1
  • 11
  • 30
  • 1
    No, it's fired as soon as you call it, *however* since AJAX (Asynchronous Javascript And XML) is asynchronous (you guessed it), it continues the code while waiting for a response, hence it first calls the *callback* when your *server* responds which is after your browser has finished the rest of the anonymous function. Put the code you want to execute when you've gotten the result into your callback (`function (result)`) anonymous function instead and you're good to go. – h2ooooooo Apr 20 '14 at 18:49
  • possible duplicate of [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – Quentin Apr 20 '14 at 18:54

2 Answers2

1

JavaScript is an event driven language which means it can work Asynchronously

Ajax - is the way for accessing a server in an asynchronous way.

functions like getJSON works in an async way (using AJAX) - which means that instead of blocking the whole script until it gets the result from the server - it starts an action (in this case requesting a resource from the server) and receives a function to call (usually referred as "callback") whenever some event occur (in this case the request got to its end - i.e. you got the response from the server)

If it was working the way you imagined it should work - there was no need to pass the function like you did and you could instead write:

obj = $.getJSON('/urltogetobjectwithvalue/', {id: baKey}); //WRONG CODE - DON'T USE IT

There is a good explanation about async programming in Javascript (using setTimeout which also works asynchronously) in this question as well

In order to get things in the order that I guess you wanted you should do something like:

$('.poplinks').popover().parent().on('click', '.insert-submission', function () {
    var baKey = 8701;
    var obj;

    function afterResponse(){
        $("#span_unk_sub_baid").html(baKey);
        if (obj !== undefined)
            $("#span_unk_sub_baid").append(' Eff Date: ' + obj.EffectiveDate);
        $('#dialog_ins_purc').modal('show');
    }

    $.getJSON('/urltogetobjectwithvalue/', {id: baKey}, function (result) {
        obj = result;
        afterResponse();
    });
});
Community
  • 1
  • 1
Yaron U.
  • 7,681
  • 3
  • 31
  • 45
  • what you are suggesting I should be using? – sarojanand Apr 20 '14 at 20:09
  • 1
    if you have something that you want to happen after you get the result from the server - it should go inside the callback function (or in another function that will be called from the callback function). I've edit the answer with an example – Yaron U. Apr 20 '14 at 20:12
  • "function afterResponse()" should be inside the click event or I can put it outside? – sarojanand Apr 24 '14 at 21:47
  • The `baKey` variable lives only inside the function so it must be inside the click handler - if you want to take it out you'll need to take the `baKey` out as well. Same applies for `obj` variable but as opposed to`baKey` you can ignore`obj` easily by sending the result a parameter to the `afterResponse` callback – Yaron U. Apr 25 '14 at 09:37
  • can I pass baKey and obj both as parameter to afterResponse callback like afterResponse(obj, baKey)? – sarojanand Apr 26 '14 at 17:14
  • If the server returns them as part of the response you'll get them inside `result` – Yaron U. Apr 26 '14 at 23:17
-2

Instead of using short hand use

$.ajax({
    type:'GET',
    async:false,
    url:"your url",
    dataType:'JSON',
    data:{id,baKey}
    success:function(result)
    {
      debugger;obj = result;
    }
});

Async is default set to true.So your js executes the code after this ajax call and does not wait for the server to return with a response.If it is set to false js waits for the server to respond back with the data and proceeds with further execution.

Tyranicangel
  • 189
  • 2
  • 16