游.程 2017-04-11 18:31 采纳率: 0%
浏览 63

AJAX随机数

I would like to practice on using AJAX. I have a MySQL database, and I have inserted some names in the column storeName. I made a SQL query that output random text in column in the database. That is working fine, but only when I refresh my browser:

<?php
    $sql ="SELECT * FROM stores ORDER BY RAND ( ) LIMIT 1";
    $res = $mysqli->query($sql);
    //print($res);
    if ($res->num_rows > 0) {
    // output data of each row
    while($row = $res->fetch_assoc()) {
        echo "Storename: " . $row["storeName"]. "<br>" .     
    }
} else {
    echo "0 results";
}
?>

I would like to make an AJAX function, that calls my SQL query without I have to refresh my browser. I tried to make the following code, but when I hit the shuffle button, nothing is happening. What am I doing wrong here?

<body>
<div id="shuffle" >
  <h4>Shuffle Stores</h4>
    <!-- This php function loads everytime I refresh the browser -->
    <?php include 'function/select_shuffle.php' ?>

      <form action="function/select_shuffle.php" method="post">
        <button>shuffle</button>
      </form>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <!-- Shuffle AJAX method-->
    <script>
        $(document).ready(function(){
            $("button").click(function(){
                $.ajax({url: "function/select_shuffle.php", success: function(result){
                    $("#shuffle").html(result);
                }});
            });
        });
    </script>
</body>

AJAX

@Sehdev: AJAX_1

  • 写回答

2条回答 默认 最新

  • weixin_33682719 2017-04-11 18:43
    关注

    You don't need to include select_shuffle.php file in your current page if you are making an ajax call.

    Please try the following code. Also you can check your console for any ajax error. Right click on your page and choose Inspect. Then click on "Network" tab and after that click on XHR heading. Here you can track your ajax request. You can check header, response or any ajax error.

    <body>
    <div id="shuffle" >
    </div>
    <div>
      <h4>Shuffle Stores</h4>
          <button id="btn">shuffle</button>
    </div>
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <!-- Shuffle AJAX method-->
        <script>
            $(document).ready(function(){
                $("#btn").click(function(){
                    $.ajax({
                        url: "function/select_shuffle.php", 
                        success: function(result)
                        {
                            $("#shuffle").html(result);
                        }
                    });
                });
            });
        </script>
    </body>
    
    评论

报告相同问题?