0

I have doubt regarding the execution order for a jquery function i created for my project. The function is given below.

$('#s_cust').change(function(event) {
                var custId = $("select#s_cust").val();
                $.get('ContactAjax', {
                    custId: custId
                }, function(jsonResponse) {
                    alert("jsonresp: " + jsonResponse);
                    cconjson = jsonResponse;
                    var select = $('#s_ccon');
                    $(select).find('option').remove();
                    $('<option>').text("Select").appendTo(select);
                    $.each(jsonResponse, function(key, value) {
                        $('<option>').val(key).text(value).appendTo(select);
                    });
                });
                if (cconjson != null) {
                    for (var j = 1; j <= i; j++) {
                        var select1 = $('#s_ccon' + j);
                        $(select1).find('option').remove();
                        alert("test");
                        $('<option>').text("Select").appendTo(select1);
                        $.each(cconjson, function(key, value) {
                            alert("key: " + key + " value:" + value);
                            $('<option>').val(key).text(value).appendTo(select1);
                        });
                    }
                }
            });

"'#s_ccon' + j" is given because I'm dynamically generating a text box based on the click of a button.

The problem that I have got while using this function is that, after refresh of the form page I change the value in my select list, s_cust, it goes into the ajax call retrieves my data and populate the s_ccon correctly. When I change value of s_cust again it executes the if loop first, then goes back and does the ajax function get, I understood this beacause the first alert that comes after the second change is alert("test"), then the alert("key: " + key + " value:" + value), after this alert("jsonresp: " + jsonResponse).

I don't know why this happens, please tell me the mistake I have made here.

Muthukumar
  • 8,679
  • 17
  • 61
  • 86
Manesh
  • 586
  • 3
  • 14
  • 31
  • Another option instead of `alert()` is `console.log()`. Just saying because I used to do the same thing with the *alert* function... – tgogos Nov 07 '14 at 07:12
  • 1
    The ajax call is async. The response comes back sometime later. Any code that uses the result MUST be INSIDE the completion callback, NOT after it. Read [this](http://stackoverflow.com/a/14220323/816620) for more info. – jfriend00 Nov 07 '14 at 07:26
  • @Thanks jfriend00 for the knowledge, your solution worked for me. – Manesh Nov 07 '14 at 07:31

2 Answers2

0

Since Ajax is asynchronous java script does not wait for the ajax request to come back to solve this problem as mention in the question above I had to put the condition evaluation regarding ajax inside the json response function itself, so finally my code looks like this.

  $('#s_cust').change(function(event) {
            var custId = $("select#s_cust").val();
            $.get('ContactAjax', {
                custId: custId
            }, function(jsonResponse) {
                alert("jsonresp: " + jsonResponse);
                cconjson = jsonResponse;
                var select = $('#s_ccon');
                $(select).find('option').remove();
                $('<option>').text("Select").appendTo(select);
                $.each(jsonResponse, function(key, value) {
                    $('<option>').val(key).text(value).appendTo(select);
                });
                if (cconjson != null) {
                   for (var j = 1; j <= i; j++) {
                       var select1 = $('#s_ccon' + j);
                       $(select1).find('option').remove();
                       alert("test");
                       $('<option>').text("Select").appendTo(select1);
                       $.each(cconjson, function(key, value) {
                          alert("key: " + key + " value:" + value);
                          $('<option>').val(key).text(value).appendTo(select1);
                       });
                   }
                }
            });

        }); 
Manesh
  • 586
  • 3
  • 14
  • 31
-1

According to the documentaion of jQuery, $.get is an asynchronous function. It is equivalent to

$.ajax({
  url: url,
  data: data,
  success: success,
  dataType: dataType
});

So you cannot predict the order of execution.

If you want it to happen in a synchronous manner, use $.ajax directly and turn off async.

$.ajax({
      url: url,
      data: data,
      async: false, 
      success: success,
      dataType: dataType
    });

Also agree, that it is recommended to place all the code inside the success callback and follow the async process.

Muthukumar
  • 8,679
  • 17
  • 61
  • 86
  • 1
    Recommending `async: false` is a bad recommendation and will just lock up the browser. Much better to just fix the code to work with properly with an async response which is pretty much required when working with Ajax calls. – jfriend00 Nov 07 '14 at 07:28