Will
Will

Reputation: 681

jQuery select the appended element in an ajax call dose not work

In the code, .moneychoose is the div in moneychoose.jsp. $(".moneychoose") can not be selected in the ajax call.

$("input[name='money']").on("click", function() {
    if ($("#money").find(".moneychoose")) {
        $(".moneychoose").remove();
    }

    //append external html
    $.get("moneychoose.jsp", function (data) {
        $("#money").append(data);
    });

    $.ajax({
        type: "POST",
        url: "src/province_price.json",
        data: '',
        dataType: "json",
        async: "false",
        success: function(response) {
            console.log($(".moneychoose"));
        },
        error: function(qXhr, status, error) {
            alert(status + ':' + error + ':' + qXhr.responseText);
        }
    });
});

But if i add console.log($(".moneychoose")) after "append external html", $(".moneychoose") in ajax call can be selected. why? however, the $(".moneychoose") after "append external html" still can not be selected.

$("input[name='money']").on("click", function() {
    if ($("#money").find(".moneychoose")) {
        $(".moneychoose").remove();
    }

    //append external html
    $.get("moneychoose.jsp", function (data) {
        $("#money").append(data);
    });

    console.log($(".moneychoose"));

    $.ajax({
        type: "POST",
        url: "src/province_price.json",
        data: '',
        dataType: "json",
        async: "false",
        success: function(response) {
            console.log($(".moneychoose"));
        },
        error: function(qXhr, status, error) {
            alert(status + ':' + error + ':' + qXhr.responseText);
            }
    });
});

Upvotes: 0

Views: 374

Answers (1)

runspired
runspired

Reputation: 2693

Your confusion is because console.log is not synchronous. Your error is because you have a race condition between two AJAX requests.

//append external html
$.get("moneychoose.jsp", function (data) {
  $("#money").append(data);
});

And

 $.ajax({
        type: "POST",
        url: "src/province_price.json",
        data: '',
        dataType: "json",
        async: "false",
        success: function(response) {
            console.log($(".moneychoose"));
        },
        error: function(qXhr, status, error) {
            alert(status + ':' + error + ':' + qXhr.responseText);
        }
    });

In order to ensure that .moneychoose is available in the success callback of $.ajax, you will either need to use a Promise that resolves once both requests have succeeded, or you will need to wait to execute one of the requests until the other has finished.

Upvotes: 5

Related Questions