Ricky Meks
Ricky Meks

Reputation: 1

Using a unique div Id in php passed to javascript and used to run another php script

I have a div that uses some unique id from a mysql db that I have to pass to my javascript file so I could display results from another php script in a particular div with a specific id that corresponds to the one obtained from the db.

index page.

<div class="wrapper">
<?php 
    $query = mysqli_query($con, 'SELECT * FROM in_table limit 10 ');

    while($result = mysqli_fetch_array($query)){ ?>
        <img src= <?php echo $result['user_image_url']; ?> />

    <?php 
        echo $result['msg'].'</br>';
        echo '<a href="#'.$result['statusID'].'">More...</a></br>';

        echo '<div id="'.$result['statusID'].'" class="rest" style="width: 400px; height: 100px;"></div>';
    }
?>

The div is inside the while loop.

ajax.js

$('a').on('click', function(){
    var hash = this.hash.replace('#','');

    $.post('content.php', {id: hash}, function(data){
        $('div#?????').html(data);
    });

})

So how do I call that div inside?

content.php

<?php
    include('ajax.php');

    if (isset($_POST['id'])) {
        $id = $_POST['id'];
    }

    $query = mysqli_query($con, "SELECT * FROM comments where statusID = '".$id."'");

    while($row = mysqli_fetch_array($query)){
        echo $row['message'].'</br>';
    }   
?>

Upvotes: 0

Views: 153

Answers (2)

voldomazta
voldomazta

Reputation: 1340

Why don't you use the hash in the selector?

$.post('content.php', {id: hash}, function(data){
    $('div#' + hash).html(data);
});

I also heard its more lightweight and more intentionally correct to use GET when retrieving something and using POST when modifying something.


Edit:

You said you were using all integers as IDs, which is bad for DOM. Try putting some text before the IDs like so:

echo '<a href="#t'.$result['statusID'].'">More...</a></br>';
echo '<div id="t'.$result['statusID'].'" class="rest" style="width: 400px; height: 100px;"></div>';

Now the ID will be something like t1000 and NOT 1000.

Then in your JS do

$.post('content.php', {id: hash}, function(data){
    $('div#t' + hash).html(data);
});

Upvotes: 1

nitigyan
nitigyan

Reputation: 494

I think voldomazta's answer will also work. There is another way you can do this. Modify your anchor tag to include a data attribute:

echo '<a href="#'.$result['statusID'].'" data-id="'.$result['statusID'].'">More...</a></br>';

and you can use this in jQuery

$.post('content.php', {id: hash}, function(data){
        $('div#'+$(this).data('id)).html(data);
    });

If you are not aware of data attributes, they can be used flexibly defining your own attributes as data-xyz="" in HTML tags and use them in jQuery as $(...).data('xyz')

Upvotes: 0

Related Questions