Search code examples
jquerymodel-view-controllerselect-options

MVC Select Option Value Assign


I am new to Web development, and here is my problem.

I have 2 functions inside my JS file.

  1. GetTransactionCodeList
  2. GetSelectedTransactionCodeFromDB

Both functions are called inside $(document).ready()

$(document).ready(function () {
GetTransactionCodeList();
GetSelectedTransactionCodeFromDB();})

The application should fill up the $('#Select') Option List completely in GetTransactionCodeList() before the value from GetSelectedTransactionCodeFromDB() is assigned to $('#Select').

But, what I am facing right now is the GetSelectedTransactionCodeFromDB() is start to assign the value to $('#Select') before the Option is completely fill-up.

Do anyone of you know what is happening here? I have tried to use something like function().Then(Function2()) (sorry I have forgotten what is this called already) method in JS but it doesn't help in this scenario.

Appreciate your advice.

** This project is on MVC Web Application.


Solution

  • Three ways:

    Call func2 on success of func1

    function func1() {
    $.ajax({ ... }).done(func2);
    }
    

    Use Deferred API to call func2 when funky completes:

    e.preventDefault();
    $.when(func1).then(func2);
    

    Make func1 synchronous (not recommended):

    function func1() {
       $.ajax({url: '', async: false});
    }
    

    ref : Jquery continue another ajax function after the first ajax function call is fully complete