How to execute JavaScript function in an Ajax() Response

1.7k Views Asked by At

I have a home page that load the ajax() response and post it to UL as LI content, with the same page I have script function that can select the LI content with trigger for another function, but isn’t working.

PAGE 1

HTML

<ul id="feature-deals" class="list-products allShopping-deals">         
</ul>

SCRIPT

$(document).ready(function(){
    $.ajax({
        url: "Product/Shopping-Trending-Items.php", 
        success: function(result){
            $(".allShopping-deals").html(result);
        }
    });

$(".products").click(function (){   
        alert ($('.pid', this).text());

PAGE 2

HTML

  <li class="products">
<span class="pid">1234</span>
</li>

page 1 == home page w/(ajax() load function + click function) ----> page 2 == Li content holding pid and waiting to load by ajax() ----> target output is to alert the pid value but the script is in page 1

2

There are 2 best solutions below

1
On BEST ANSWER

You should delegate event:

$(".allShopping-deals").on('click', '.products', function(){
    alert($(this).find('.pid').text());
});
2
On

You have a timing issue. The ajax call is made but the statement for assigning the click event will not wait for the result and executes. The ajax call is asynchronous.

Put the assigning of the click event inside success handler of the ajax call.

success: function(result){
            $(".allShopping-deals").html(result);
            $(".products").click(function (){   
                alert($(this).find('.pid').text());
            }
        }