Tadgh
Tadgh

Reputation: 2049

Javascript breaks when I update html with Ajax

Having a problem with a webapp i've been working on lately, and it has to do with ajax reloading breaking javascript.

I have the following Ajax Call

$.ajax({
                type: "POST",
                url:  "/sortByIngredient/",
                data: JSON.stringify(
                {
                    selectedIngredients: tempDict
                }),
                contentType: "application/json; charset=utf-8",
                success: function(data){
                    var curList = $("#drinkList").contents();
                    console.log(curList);
                    $("#drinkList").empty()
                    $("#drinkList").append(data)

and the following Html UL

 <div id = "drinkList" class="d-list">
                <ul>
                    <li id='someID'>some Item</li>
                    <li id='someID2'>some Item2</li>
                </ul>
            </div>

I also have a jQuery callback set to activate on clicked list items. On initial loading, all works well. Once the ajax call occurs, and replaces the contents of #drinkList with another list, formatted identically. In case anyone is curious, here is the onClick callback:

$("li").click(function()
    {
        window.currentDrink = $(this).attr("id");
        console.log(window.currentDrink);
         $.ajax({
            url: "/getDrink/" + $(this).attr("id"),
            type: "get",
            success: function(data){
                $("#ingDiv").html(data);
            }
        });
    });

After I make that Ajax call, the list modifies correctly, but after that, no more javascript seems to work. For example,the console.log is not called when i click on a list item, and the proper view doesnt update(#ingDiv, as shown in the above call)

Is my changing the HTML through Ajax breaking the javascript somehow? Am I missing something obvious? If it isn't clear already, I am not a web developer.

Upvotes: 1

Views: 2082

Answers (1)

Adil Shaikh
Adil Shaikh

Reputation: 44740

use event delegation like this -

$('#drinkList').on('click','li',function(){
     // do your stuff here
});

As you are not a web developer - This is what your code should look after changes

$('#drinkList').on('click', 'li', function () {
    window.currentDrink = $(this).attr("id");
    console.log(window.currentDrink);
    $.ajax({
        url: "/getDrink/" + $(this).attr("id"),
        type: "get",
        success: function (data) {
            $("#ingDiv").html(data);
        }
    });
});

Upvotes: 5

Related Questions