0

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

1
  • I don't understand the question. First you say "load the ajax() response and post it to UL as LI content, with the same page", but then you say they're on different pages. You can't use javascript to modify the DOM of a second page. If they are the same page, please modify your question. Commented Jun 14, 2015 at 15:58

2 Answers 2

3

You should delegate event:

$(".allShopping-deals").on('click', '.products', function(){
    alert($(this).find('.pid').text());
});
Sign up to request clarification or add additional context in comments.

1 Comment

thanks! this one also works for me :) learned exactly how to delegate
1

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());
            }
        }

2 Comments

awesome works pretty good. the other answer is also correct :) which is good in ruleof thumb for coding? delegate event or jusst putting in success?
I would go for Wolff's solution. The delegate will automatically assign the click event to newly added items. So the success handler doe not have to 'know' a click event is needed for the newly added item. I have learned something new as well :).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.