1

in order to avoid that the webpage is fully reloaded whenever an internal link is clicked, I'm using jQuery and AJAX.

$(".ajax").click(function(e){
    e.preventDefault(); // do not follow link
    var requestPage = "content.php?" + jQuery(this).attr('href').split("?")[1];
    $.get(requestPage, function(data){
        $("#content").html(data);
    });
});

Some of these links are generated by the content.php, looking like

<li><a class="ajax" href="home.php?x=1&y=A" title="Link A">Link A</a></li>
<li><a class="ajax" href="home.php?x=1&y=B" title="Link B">Link B</a></li>
<li><a class="ajax" href="home.php?x=1&y=C" title="Link B">Link C</a></li>

Now my proplem is, the first time after refreshing the page (by using F5) it works fine, the second time the click function is not invoked at all.

Some similar links in the home.php (so they are not regenerated) use this click function as well, no issue with them.

Can anyone help please?

Explicat
  • 1,075
  • 5
  • 16
  • 40

1 Answers1

1

You can't attach an event such as click() to the dom that loading dynamically. So, It should be on() event delegation. In older versions of jQuery you can use live() or delegate() instead of on().

$(document).on("click",".ajax",function(e){
      e.preventDefault(); // do not follow link
    var requestPage = "content.php?" + jQuery(this).attr('href').split("?")[1];
    $.get(requestPage, function(data){
        $("#content").html(data);
    });
});
Gökhan Girgin
  • 1,164
  • 8
  • 12