简体   繁体   中英

onclick on DIV, load content from database on other div

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 and fetched from the database and loaded in the center column. I know its done by some AJAX may be but unable to figure out how it is possible.

Thanks in advance.

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 );
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM