Refresh currently selected tab on Ajax success

2.1k views Asked by At

I have a few tabs, populated from a database. Each tab contains a partial view, also populated from the database. When someone adds something to one of the collections that these partials represent, I want it to refresh the tab content, to reflect the change.

function addNewRequest(arForm) {
    username = $(".ui-tabs-selected").attr("id");
    currentUser = document.getElementById("currUser").value;
    $.ajax({
        url: 'Home/submitAdvisoryRequestForm',
        type: 'POST',
        data: arForm.serialize() + "&username=" + username + "&currUser=" + currentUser,
        success: function (response) {
            if (response == "true") {
                $("#users").tabs("load", $('#users .ui-tabs-panel:not(.ui-tabs-hide)').index() - 1);
                dialog.dialog("close");
            } else {
                alert(response);
            }
        },
        error: function (xhr, ajaxOptions, thrownError) { alert(xhr.status); alert(thrownError); }
    });

}

So by my understanding, if the ajax call is successful, it would attempt to load the tab at the currently selected index. I have watched the expression used to grab the selected tab index, and as far as I can tell, it works, even if maybe slightly hacky.

The code that should refresh the tab, $("#users").tabs("load", $('#users .ui-tabs-panel:not(.ui-tabs-hide)').index() - 1);, does nothing. Does anyone know why?

1

There are 1 answers

3
Inspector Squirrel On BEST ANSWER

F**kadoodle-doo, I figured it out. Because JQueryUI is lame and only lets you refresh AJAX loaded content, it's easier to just replace the HTML of the currently selected tab's div.

JQuery code:

function addNewRequest(arForm) {
    username = $(".ui-tabs-selected").attr("id");
    currentUser = document.getElementById("currUser").value;
    $.ajax({
        url: 'Home/submitAdvisoryRequestForm',
        type: 'POST',
        data: arForm.serialize() + "&username=" + username + "&currUser=" + currentUser,
        success: function (response) {
            if (response) {
                $('#users .ui-tabs-panel:not(.ui-tabs-hide)').html(response);
                dialog.dialog("close");
            } else {
                alert(response);
            }
        },
        error: function (xhr, ajaxOptions, thrownError) { alert(xhr.status); alert(thrownError); }
    });
}

And as a response, throw the partial view at it.

public ActionResult submitAdvisoryRequestForm(BCRTAdvisoryRequest newRequest, string username, string currUser)
{
    if (ModelState.IsValid)
    {
        var ar = new AdvisoryRequestsLogic();
        if (ar.addAdvisoryRequest(newRequest) > 0)
            return PartialView("_userAdvisoryRequests", ar.getUserAdvisoryRequests(username));
    }
    return null;
}