onclick on DIV, load content from database on other div

前端 未结 1 1851
夕颜
夕颜 2021-01-28 12:45

My concept is to load contents of a div on other div in html. In short I want to learn how the new Facebook inbox works, when we click on a message on the right, the contents a

相关标签:
1条回答
  • 2021-01-28 13:50

    if you are using jquery you can use onclick event on a div.

    This is the HTML/JS this work like this.

    <!doctype html>
    <html>
        <head>
            <title>Document Title</title>
            <script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
            <script>
                $('.clickable').on('click', function(){
                    var data_id = $(this).data('id');
                    $.ajax({
                        url: 'ajax.php',
                        type: 'POST',
                        data: {id: data_id},
                        dataType: 'json',
                        success: function(data){
                            $('#more-info').html(data.html);
                        },
                        error: function(jqXHR, textStatus, errorThrown){
                            $('#more-info').html('');
                            alert('Error Loading');
                        }
                    });
                });
    
                });
            </script>
        </head>
        <body>
            <div id="item-one" class="clickable" data-id="123">Click me</div>
            <div id="item-two" class="clickable" data-id="456">Click me</div>
            <div id="more-info"></div>
        </body>
    </html>
    

    and let say we have a PHP file named ajax.php will return a json like we especified before in the ajax function dataType: 'json' and we are sending an ID through POST so here are a example you have to work it on it.

    ajax.php

    <?php
    $id = (int)$_POST['id'];
    $query = "SELECT * FROM messages WHERE message_id = {$id} LIMIT 1"; //expecting one row
    $result = mysql_query( $query );
    $message = mysql_fetch_assoc( $result ); //expecting just on row
    
    $json = array();
    $json['html'] = '<p>' . $message . '</p>';
    
    header('Content-Type: application/json');
    echo json_encode( $json );
    ?>
    
    0 讨论(0)
提交回复
热议问题