Reload MySQL data inside a DIV using Ajax

前端 未结 3 1848
别那么骄傲
别那么骄傲 2020-12-20 06:31

I need to make a moderate system like the one in fmylife.com. Basically the problem I have is loading the MySQL query using Ajax (without page refreshing) in to a div. MySQL

相关标签:
3条回答
  • 2020-12-20 06:59

    in post.php:

    $sql = mysql_query("SELECT * FROM posts WHERE active ='0' LIMIT 1") or die (mysql_error());
    $row = mysql_fetch_array($sql);
    echo $row['sitepost'];
    

    JS:

    <script type="text/javascript">
    $(document).ready(function(){
       $("#yes").click(function(){
          $(".post-body").eq(0).load("post.php");
       })
    })
    </script>
    

    HTML:

    <div id="yes">YES</div>
    <div class="post-body"></div>
    
    0 讨论(0)
  • 2020-12-20 07:00

    @mgraph is close but if you want to do this on a button click

    in post.php:

    //$UserOption will be Yes/No for button clicks or empty string for first load of the page
    
    $UserOption = $_REQUEST['UserClicked'];
    
    //Id will be set if a vote has been clicked or empty string if it's the first load
    $Id = $_REQUEST['Id'];
    
    //(Do something with $UserOption)
    
    $sql = mysql_query("SELECT * FROM posts WHERE active ='0' LIMIT 1") or die (mysql_error());
    $row = mysql_fetch_array($sql);
    echo $row['sitepost'];
    

    JS:

    <script type="text/javascript">
    $(document).ready(function(){
       update(null,null);
    })
    
    function update(Id, Vote) {
        $(".post-body").eq(0).load("post.php?UserClicked=" + Vote + "&Id=" + Id);
    }
    </script>
    

    HTML:

    <div class="post-body"></div>
    
    
    <button type="button" onclick="update(1, 'Yes');">Yes</button>
    <button type="button" onclick="update(1, 'No');">No</button>
    
    
    
    <button type="button" onclick="update(2, 'Yes');">Yes</button>
    <button type="button" onclick="update(2, 'No');">No</button>
    

    Alternate HTML/JS

    <script type="text/javascript">
    $(document).ready(function(){
        $("#yes").click(function(){
            update('Yes');
        })
        $("#no").click(function(){
            update('No');
        })
        update();
    })
    
    function update(Vote) {
        $(".post-body").eq(0).load("post.php?UserClicked=" + Vote);
    }
    </script>
    
    <div class="post-body"></div>
    <button id="yes" type="button">Yes</button>
    <button id="no" type="button">No</button>
    
    0 讨论(0)
  • You can add $("html, body").animate({ scrollTop: 0 }, 500); . Thereby, when you clicked YES button, scroll move up to top. It looks nice.

    0 讨论(0)
提交回复
热议问题