简体   繁体   中英

Run PHP Query with Ajax return data in modal

This is my first fully attempting to use ajax. I have looked all over Google and cannot seem to find an answer. I am not even sure if what I am trying to do is possible.

I am trying to populate a modal window with data from a mysql table.

Using this javascript below, I an able to print the DATA-ID in a modal window with an HREF click:

 <script type="text/javascript">
   $(document).on("click", ".open-RestrictModal", function () {
     var myId = $(this).data('id');
     $(".modal-body #Id").val( myId );
 });
 </script>

I would like to add to this code is the ability to run a PHP/MySQL query, get the results, and print it in the modal window.

I think I have to use AJAX, but I am not sure. How can I add to the existing code the ability to send the javascript variable to an AJAX page and return the results in a modal window?

Please help.

It doesn't appear that you are even using ajax here, assuming you are using the jQuery library you can build a call like this:

function some_ajax_call(your_param) {

     $.ajax({

         type: "POST",     // We want to use POST when we request our PHP file
         url : "some/url/to/your/file.php",
         data : { query : your_param },    // passing an array to the PHP file with the param,  value you passed, this could just be a single value i.e. data: your_param
         cache: false,       // disable the cache optional

         // Success callback if the PHP executed  
         success: function(data) {
              // do somethig - i.e. update your modal with the returned data object
              $('.modal-body #id').val(data);    
         }

     });

}

You can then write you file.php file to handle the query

<?php

// Capture the variable we passed in via AJAX
$param  = $_POST['query'];  

// Build a query
$query = "SELECT * FROM some_table WHERE val ='" . $param . "'";

// I assume you know how to run a query, this would be fetching an assoc array
$results = $DB->run__query($query);

// Check we have some results, then echo back to the AJAX call
if(sizeof($results) > 0) {
    echo $results;
} 

echoing at the $results array at the end of our PHP script if we have any results will populate the data array in our success callback with the returned rows, you can then perform any DOM manipulation in the success callback to update your modal, hope this helps.

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