Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
227 views
in Technique[技术] by (71.8m points)

javascript - 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. 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);
?>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First is, you have to trigger the AJAX request by using Javascript. But I'll be guiding you by using jQuery (a Javascript library).

Your 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.

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...