AlexGH
AlexGH

Reputation: 2805

Update list and then show updated list using JQuery

I'm not very experienced with JQuery and I'm beginning to work with WebAPI, inside my .js file I have some functions that call methods from StudentsAPIController(my WebApi controller):

$(document).ready(function () { GetAll(); GetStudent(); AddStudent(); UpdateStudent()})

function ShowList() {
    $.ajax({
        type: "get",
        url:"/api/StudentsAPI"
    }).success(function (result) {
        var Output = "";
        for (var i = 0; i < result.length; i++) {
            Output += "<hr>";
            Output += "<b> Name: </b>" + result[i].Name + "<br/>";
            Output +="<b> LastName: </b>" + result[i].LastName + "<br/>"
        }
        $("#lblMessage").html(Output);
    })
    .error(function () {
        $("#lblMessage").html("An error occurred")
    })
}

and

  function UpdateStudent () {
$("#btnUpdateStudent").click(function () {
    var student = { StudentID:2, Name: "Prika", LastName: "Prika" }
    $.ajax({
        type:"put",
        url: "/api/StudentsAPI/2",
        data: student
    }).success($("#lblMessage").html(ShowList()))
    .error(function (xhr, ajaxOptions, thrownError) {
        $("#lblMessage").html("Error: An error occurred")
    })
    return false;
})
        }

The UpdateStudent() function is working well(is updating in the table) but once it success I want to show an updated list of all students in the table, including the just updated, what I'm getting now is a list of all students of the table, but that list doesn't include the last updated student(The list is not updated). I know that the function that I have for that: ShowList() is getting the list when the page is loaded but not after the UpdateStudent() function is called. If I refresh the page it shows the last list not the updated list, what can I do to fix it???

Upvotes: 0

Views: 247

Answers (1)

Shyju
Shyju

Reputation: 218752

You should call the ShowList() method on the success event of your ajax call like this.

function ShowList() {
     // Add here your existing code(ajax call code) to get data from api endpoint
}

function UpdateStudent () {

    var student = { StudentID:2, Name: "Prika", LastName: "Prika" }
    $.ajax({
        type:"put",
        url: "/api/StudentsAPI/2",
        data: student
    }).success(function(){
        ShowList();
    });
    .error(function (xhr, ajaxOptions, thrownError) {
        $("#lblMessage").html("Error: An error occurred")
    })
    return false;
}


$(function(){
    //Call other methods also here as needed.
    UpdateStudent();

    // bind the click event to UpdateStudent method
    $("#btnUpdateStudent").click(function () {
           UpdateStudent();
    });
});

Upvotes: 1

Related Questions