RGS
RGS

Reputation: 4253

AJAX loaded content use .ON or add the script in the ajax request page?

I have a view more option in my website index page that I load using a AJAX. this will bring more content to user from page_ajax.php.

The problem is this DOM content need a JQUERY click event.

<span class=productinfo>product info</span>

My question is, where should I add the <script> tag? in the index.php page or in the page_ajax.php (that will load jquery in each call)?

If I add in index.php jquery will not work, should I add the script tag in page_ajax.php? or should I use .ON in index jquery? how would it be? Can someone give me an example?

<script>
$(function() {
$(".productinfo").click(function(){

var element = $(this);
var I = element.attr("data-id");
var info = 'id=' + I;

 $.ajax({
   type: "POST",
   cache: false,
   url: "/product.php",
   dataType: "json",
   data: info,

  success: function(data) {
    alert(data);
  }

 });
return false;
});
});
<script>

Upvotes: 0

Views: 21

Answers (1)

Eduard
Eduard

Reputation: 3576

Those elements are dynamically loaded so jQuery doesn't know about them when it delegates that handler.

So you'd have to delegate the event to a parent like this:

$( document.body ).on('click', '.productinfo' , function(e){

    var element = $(this);
    var I = element.attr("data-id");
    var info = 'id=' + I;

    $.ajax({
        type: "POST",
        cache: false,
        url: "/product.php",
        dataType: "json",
        data: info,

        success: function(data) {
            alert(data);
        }

    });

    return false;

});

Upvotes: 1

Related Questions