Textbox not updating from jQuery AJAX call

I had a friendly little piece of JavaScript code to return a string to the calling code:

function getDescByCode(code) {
    var returnVal;

    $.ajax({
        url: "http://www.scott.bla/api/ReturnMyStringValue",
        type: "GET",
        data: { code: code }
    })
    .done(function (data) {
        returnVal = data;
    });
    
    return returnVal;
}

This method was being called by an onchange event assigned to an MVC drop down list to update a textbox, so when a user changed the value of the DDL, the associated textbox would be changed to the value returned from the Web API call, which was called from the function above:

@Html.DropDownListFor(m => m.MyCode, 
(IEnumerable<SelectListItem>)Application["Codes"], 
"--Select--", 
new { @onchange = "$('#MyDesc').val(getDescByCode(this.value));" })
   @Html.TextBoxFor(m => m.MyDesc)

The problem was that the text box wasn’t being updated. However, if I added an alert inside the jQuery method, I could see that the data was, in fact, being returned from the Web API called as expected:

    .done(function (data) {
       alert(data);    // Worked
    });

The problem was solved by adding the “async: false” line to the AJAX call. The full working method is:

function getDescByCode(code) {
    var returnVal;

    $.ajax({
        url: "http://www.scott.bla/api/MyStuff",
        type: "GET",
        async: false,
        data: { code: code }
    })
    .done(function (data) {
        returnVal = data;
    });
    
    return returnVal;
}
Advertisements
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: