2

Is it possible to load JS for each div. Now it only loads for the first div.

There are multiple posts in same page. I need to load the post.php inside every #box div.

Is it possible in this way or is there some better way to do this ?

<h2>title: <?php echo $post_title ?></h2>
<div id="box" >
  <script type="text/javascript" >
   $(document).ready(function(){
       $('#box').load('post.php?id=<?=$post_id?>')
   });
  </script>
</div>
CodeGodie
  • 12,116
  • 6
  • 37
  • 66
Lady Lancer
  • 105
  • 1
  • 7
  • Ids are supposed to be unique. Try using `class="box"` instead. – Will Reese May 18 '17 at 03:04
  • *"inside every #box div."* - The concept of doing *anything* with "every #box div" is problematic given that element IDs are supposed to be unique. Is your PHP `$post_id` supposed to be unique per div (perhaps in a PHP loop), or...? – nnnnnn May 18 '17 at 03:05
  • yes $post_id is unique for each post – Lady Lancer May 18 '17 at 03:39
  • [works well](http://stackoverflow.com/a/12524381/6521116) – LF00 May 18 '17 at 03:49
  • Possible duplicate of [How to load PHP file into DIV by jQuery?](http://stackoverflow.com/questions/12524228/how-to-load-php-file-into-div-by-jquery) – LF00 May 18 '17 at 03:49

2 Answers2

2

Id's are supposed to be unique, so use class instead like:

<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
...

$('.box').load('post.php?id=<?=$post_id?>');

The above statement will load the content in every div having class box

CodeGodie
  • 12,116
  • 6
  • 37
  • 66
Mayank Pandeyz
  • 25,704
  • 4
  • 40
  • 59
  • 1
    This is definitely the right approach, however since the post ID is going to be different on every div, this would need to be a little more complex - for example, writing the post ID as an HTML attribute on the DIV and using that in the load() call. – PMV May 18 '17 at 04:11
0

You can do this, you have use <div id="box">, merge this div with your id like this <div id="box <?php echo $post_id;?>"> so each time it will genrate unique div and it will be easy solution for you to do.

In jquery you need to give the id so this will help out

Aman
  • 19
  • 2