简体   繁体   English

如何使用AJAX在select选项上执行PHP查询?

[英]How do I execute a PHP query on select option choice using AJAX?

Okay I know this has been answered before ( Execute PHP script on same page after selecting a dropdown list option using Ajax or JavaScript ) but the answers weren't very helpful for someone who has never used AJAX before. 好的,我知道之前已经回答了这个问题( 在使用Ajax或JavaScript选择下拉列表选项后在同一页面上执行PHP脚本 ),但答案对于之前从未使用过AJAX的人来说并不是很有帮助。 How do I run a query like the one created if someone selects an option from the drop down? 如果有人从下拉列表中选择一个选项,如何运行创建的查询?

<head>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>

<h3>Subject</h3>
<select name="allbooks" >
              <option value="none" ></option>
              <option value="allbooks" >All Books</option>
    </select>

<?php 
$query = "SELECT * FROM books" or die("Error in the consult.." . mysqli_error($connection)); 
    $books = $connection->query($query);
?>

First is, you have to trigger the AJAX request by using Javascript. 首先,您必须使用Javascript触发AJAX请求。 But I'll be guiding you by using jQuery (a Javascript library). 但我会用jQuery(一个Javascript库)来指导你。

Your HTML: 你的HTML:

<select name="allbooks" id="allbooks">
  <option value="none" ></option>
  <option value="allbooks" >All Books</option>
</select>
<div id="show">
  <!-- ITEMS TO BE DISPLAYED HERE -->
</div>

After that, download jQuery . 之后,下载jQuery

Then lets do the script: 然后让我们做脚本:

<script src="jquery-1.9.1.min.js"></script> <!-- CHANGE THE JQUERY FILE DEPENDING ON THE VERSION YOU HAVE DOWNLOADED -->
<script type="text/javascript">
  $(document).ready(function(){ /* PREPARE THE SCRIPT */
    $("#allbooks").change(function(){ /* WHEN YOU CHANGE AND SELECT FROM THE SELECT FIELD */
      var allbooks = $(this).val(); /* GET THE VALUE OF THE SELECTED DATA */
      var dataString = "allbooks="+allbooks; /* STORE THAT TO A DATA STRING */

      $.ajax({ /* THEN THE AJAX CALL */
        type: "POST", /* TYPE OF METHOD TO USE TO PASS THE DATA */
        url: "get-data.php", /* PAGE WHERE WE WILL PASS THE DATA */
        data: dataString, /* THE DATA WE WILL BE PASSING */
        success: function(result){ /* GET THE TO BE RETURNED DATA */
          $("#show").html(result); /* THE RETURNED DATA WILL BE SHOWN IN THIS DIV */
        }
      });

    });
  });
</script>

Then lets create the get-data.php which will receive the data sent through AJAX. 然后让我们创建get-data.php ,它将接收通过AJAX发送的数据。

if(!empty($_POST["allbooks"])){
  /* DO YOUR QUERY HERE AND GET THE OUTPUT YOU WANT */
  echo $output; /* PRINT THE OUTPUT YOU WANT, IT WILL BE RETURNED TO THE ORIGINAL PAGE */
}

You can check this example - JSfiddle . 你可以查看这个例子 - JSfiddle

 var id="1";
 $.ajax({
    type: 'POST',
    url: 'yourphppage',
    dataType: "json",
    data: {
        idofrow:id
    },
    success: function(data) {
        alert(data);
    },
    error: function(data) {
        alert(data);
    }
});

This is a samle of ajax request you can use this and just change the other fields as need when the query is success you can retrieve that data in the success you can manipulate what data you want to use you can return json , text . 这是ajax请求的一个小问题,您可以使用它,只需在查询成功时根据需要更改其他字段,您可以成功检索该数据,您可以操作您想要使用的数据,您可以返回jsontext

In your php page you can retrieve the id as 在您的php页面中,您可以将ID检索为

$id = ($_POST['idofrow']);

you can then you this id to select like this 你可以这个id来选择这样的

SELECT * FROM table where rowid = $id

and you can just echo the result. 你可以回应结果。

for additional info just check on this documentation 有关其他信息,请查看此文档

Check this simple tutorial Hope this will help. 检查这个简单的教程希望这会有所帮助。

      <html>
    <head>
    <script>
    function showUser(str) {
        if (str == "") {
            document.getElementById("txtHint").innerHTML = "";
            return;
        } else { 
            if (window.XMLHttpRequest) {
                // code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp = new XMLHttpRequest();
            } else {
                // code for IE6, IE5
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange = function() {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                    document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
                }
            }
// getuser.php is seprate php file. q is parameter 
            xmlhttp.open("GET","getuser.php?q="+str,true);
            xmlhttp.send();
        }
    }
    </script>
    </head>
    <body>

    <form>
    <select name="users" onchange="showUser(this.value)">
      <option value="">Select a person:</option>
      <option value="1">Peter Griffin</option>
      <option value="2">Lois Griffin</option>
      <option value="3">Joseph Swanson</option>
      <option value="4">Glenn Quagmire</option>
      </select>
    </form>
    <br>
    <div id="txtHint"><b>Person info will be listed here...</b></div>

    </body>
    </html>

The getuser.php file getuser.php文件

   <!DOCTYPE html>
    <html>
    <head>
    <style>
    table {
        width: 100%;
        border-collapse: collapse;
    }

    table, td, th {
        border: 1px solid black;
        padding: 5px;
    }

    th {text-align: left;}
    </style>
    </head>
    <body>

    <?php
// don't use intval if your select value is not numberic
    $q = $_GET['q'];

    $con = mysqli_connect('localhost','peter','abc123','my_db');
    if (!$con) {
        die('Could not connect: ' . mysqli_error($con));
    }

    mysqli_select_db($con,"ajax_demo");
    $sql="SELECT * FROM user WHERE id = '".$q."'";
    $result = mysqli_query($con,$sql);

    echo "<table>
    <tr>
    <th>Firstname</th>
    <th>Lastname</th>
    <th>Age</th>
    <th>Hometown</th>
    <th>Job</th>
    </tr>";
    while($row = mysqli_fetch_array($result)) {
        echo "<tr>";
        echo "<td>" . $row['FirstName'] . "</td>";
        echo "<td>" . $row['LastName'] . "</td>";
        echo "<td>" . $row['Age'] . "</td>";
        echo "<td>" . $row['Hometown'] . "</td>";
        echo "<td>" . $row['Job'] . "</td>";
        echo "</tr>";
    }
    echo "</table>";
    mysqli_close($con);
    ?>
    </body>
    </html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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