Why after jquery ajax post (with a link as event) that link doesnt work a 2nd time?

StackOverflow https://stackoverflow.com/questions/23601936

  •  20-07-2023
  •  | 
  •  

Question

That is my problem.

I started a fresh solution to get clean code and find out what the problem could be.

There is a simple table with 10 users, all of them haves a 'delete' link that calls a jQuery function. That jQuery function deletes the user and then refreshes the div that contains a table with remaining users.

It works fine except that when you want to use the link for a 2nd time, it doesn't do anything.

Here is all the code you need, you can recreate situation with a fresh "MVC4" Basic visual studio solution.


first of all, I am using "cdn" to get "json" scripts from here :

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>

This is my "Index.cshtml" page :

<script>
    $(function () {

        $(".PruebaPost").click(function (e) {

            e.preventDefault();

            var values = {
                id: this.id
            };

            $.ajax({
                url: "@Url.Action("BorrarUsuario","Principal")",
                type: "post",
                data: values,
                success: function () {
                    alert("success");
                    $("#TodosLosUsuarios").html(
                           $.get('@Url.Action("IndexPartial")',{}, function(data) { 
                               $("#TodosLosUsuarios").html(data);
                           })
                    );
                },
                error: function () {
                    alert("failure");
                    $("#TodosLosUsuarios").html('There is error while submit');
                }
            });
        });
    });

</script>
<div>my header that must not change: @DateTime.Now.ToString()</div>

    <div id="TodosLosUsuarios">
        @Html.Partial("IndexPartial")
    </div>
<div>this is a footer, that will never be replaced</div>

This is the code inside "IndexPartial.cshtml" :

@model WebParaPrubeas.Models.CoolUsersModel

<table>

    <tr>
        <td><b>IdCoolUser</b></td>
        <td><b>LastName</b></td>
        <td><b>FirstName</b></td>
    </tr>

    @foreach (var item in Model.CoolUsers)
    {
        <tr>
            <td>@item.IdCoolUser</td>
            <td>@item.LastName</td>
            <td>@item.FirstName</td>

            <td><a href="#" class="PruebaPost" id="@item.IdCoolUser">Erase!</a></td>
        </tr>
    }

</table>

this is my model code :

namespace WebParaPrubeas.Models
{
    public class CoolUsersModel
    {
        public List<CoolUser> CoolUsers { get; set; }
    }

    public class CoolUser {

        public Int32 IdCoolUser { get; set; }

        public String LastName { get; set; }

        public String FirstName { get; set; }
    }
}

And this is my controller, with a simple test repository saved on Session, just for test purposes, it will be called only the first time if session is null.

public class PrincipalController : Controller
{

    public static List<CoolUser> ObtenerUsuarios()
    {
        var resultado = new List<CoolUser>();

        for (int i = 0; i < 10; i++)
        {
            resultado.Add(new CoolUser
            {
                IdCoolUser = i,
                LastName = "LastName " + i.ToString(),
                FirstName = "FirstName " + i.ToString()
            });

        }
        return resultado;
    }


    [HttpGet]
    public ActionResult Index()
    {
        var usuarios = (List<CoolUser>)Session["CoolUsers"];

        if (usuarios == null)
        {
            usuarios = ObtenerUsuarios();
            Session.Add("CoolUsers", usuarios);
        }

        var modelo = new CoolUsersModel { CoolUsers = usuarios };

        return View(modelo);
    }

    [HttpGet]
    public PartialViewResult IndexPartial()
    {
        var usuarios = (List<CoolUser>)Session["CoolUsers"];

        var modelo = new CoolUsersModel { CoolUsers = usuarios };

        return PartialView(modelo);
    }

    [HttpPost]
    public ActionResult BorrarUsuario(Int32 id)
    {
        var usuarios = (List<CoolUser>)Session["CoolUsers"];

        var eliminar = usuarios.Single(s => s.IdCoolUser == id);

        usuarios.Remove(eliminar);

        Session["CoolUsers"] = usuarios;

        return Json(new { success = true });
    }

}

As I said before, you can test this problem by erasing any user, page will refresh with new version of users (without the erased one) but the links that perform erase of users will not be working any more.

Anybody haves a solution for this? :(

thanks!

Was it helpful?

Solution

Bind you click handler using on method.

$("#TodosLosUsuarios").on("click", ".PruebaPost", function(){
    // Do stuff
});

OTHER TIPS

Try this might this work

$("#TodosLosUsuarios .PruebaPost").click(function(){
// code here
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top