1

I wrote an ajax code like this :

$.ajax({
            type: "POST",
            url: "post.php",
            data: {id:id},
            cache: false,
            success: function (result) {
                    $('.post').html(result);
            }
       });

this code show more post in the index.php file , when it shows the more posts main.js file that embeded in the index.php not working on the new posts.

i used this code in the post.php :

   <script src="main.js" ></script>

it worked but some of the function run two time.

how can i embed the main.js on the post.php without the above problem?

1 Answers1

0

You have to re-run those function on ajax response thats are needed for new posts. You don't have to call full main.js file again.

Or if you have any click event write like below.

$(document).on("click", '.selector', function(){
    //Here will be your code
});

You can use any event instead of click.

  • what is the difference between above code and $(".selector").click(function(){ //codes }); , first work but this not. – Daniel James Mar 23 '18 at 07:08
  • @DanielJames The code in the answer will work for dynamically-created `.selector` elements. See https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements – Barmar Mar 23 '18 at 07:12
  • `$(".selector")` search `.selector` when first time page load, and if you use `$(document)` it will search on full DOM every time. – Sourov Roy Chowdhury Mar 23 '18 at 07:13