skip to Main Content

I am trying to display in a bootstrap modal the relevant image and information from a mysqli database table named prints and then display in the modal the image, title etc… the ajax call is working and loading the div where the response should go but none of the rest of the response is populating the modal?

my code is as follows:

database connection php: `

     <?php
     $dbhost = '*';
     $dbuser = '*';
     $dbpass = '*';
     $dbname = '*';
     $conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);

     if(! $conn ) {
        die('Could not connect: ' . mysqli_error());
     }
     //echo 'Connected successfully';

  ?>

This connects without errors and is called when needed

my main page where the database is being used to display thumbnails from the relevant table to then click and use a the modal pop up is as follows:

<?php include 'CreateDb.php';
ini_set('display_errors', 'on');
error_reporting(E_ALL);
$SQLprintsall = 'SELECT * FROM prints';
$printsall = mysqli_query($conn, $SQLprintsall);

?>
<div id ="shop-header">
  <div id="cont-cart">
  <p>BUY PRINTS</p>
  <ul class="cart-actn">
    <li><a class="fa fa-pound-sign" href="#"></a></li>
    <li><a class="fa fa-shopping-cart" href="#"></a></li>
  </ul>
</div>
<ul class="shop-filters">
  <li class="filter-item">All</li>
  <li class="filter-item"><a href="#">Landscapes</a></li>
  <li class="filter-item"><a href="#">Animals</a></li>
  <li class="filter-item"><a href="#">Europe</a></li>
  <li class="filter-item"><a href="#">Scotland</a></li>
  <li class="filter-item"><a href="#">England</a></li>
  <li class="filter-item"><a href="#">Asia</a></li>
  <li class="filter-item"><a href="#">Canada</a></li>
</ul>
</div>
<!--thumbnail images Loop-->
<div id="shop-thumbs">
<?php while($prints = mysqli_fetch_array($printsall)) : ?>
<div id="image-shop" class="image-holder">
  <button type="button" data-id="<?php echo $prints['image']; ?>" class="img-btn btn-success 
printinfo" >
  <img src="<?=$prints['image_href']; ?>">
  </button>
</div>
<?php endwhile; ?>
<!-- Modal -->
<div class="modal fade" id="empModal" role="dialog">
<div class="modal-dialog">

 <!-- Modal content-->
 <div class="modal-content">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal">&times;</button>
  </div>
  <div class="modal-body">

  </div>
  <div class="modal-footer">
   <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
  </div>
 </div>
</div>
</div>
<script>

$(document).on('click', '.printinfo', function(){

 var printinfo = $(this).attr('data-id');
 alert("'.$printinfo.'");

 // AJAX request
 $.ajax({
  url: 'wp-content/themes/LEP/Modals/landscape-product-1.php',
  type: 'post',
  data: {printinfo: printinfo},
  success: function(response){
    console.log(printinfo);
    alert(response);
    // Add response in Modal body
    $('.modal-body').html(response);

    // Display Modal
    $('#empModal').modal('toggle');
  }
});
});

</script>

</div> <!-- end of containder from header.php -->

This then calls the modal pop up which is as follows

<?php
include "CreateDb.php";

$printinfo = 0;
if(isset($_POST['printinfo'])){
$printinfo = mysqli_real_escape_string($conn,$_POST['printinfo']);
}
$sql = "SELECT * FROM prints WHERE id =" .$printinfo;
$result = mysqli_query($conn,$sql);

$response = "<div class='modal-holder'>";

while( $prints = mysqli_fetch_array($result)){
$id = $prints['image'];
$image = $prints['image_href'];
$title = $prints['image_title'];

$response .= "<div>";
$response .= "<h1>".$title."</h1>";
$response .= "</div>";

$response .= "<div>";
$response .= "<img src=".$image_href.">";
$response .= "</div>";

}
$response .= "</div>";

echo $response;

?>

Everything works on the click but the modal doesnt load any of the reponse apart from the div that contains the response data?

The site is as above at http://landscapephotoprints.co.uk

any help would be greatly appreciated

Many thanks

3

Answers


  1. Chosen as BEST ANSWER

    I revised the original AJAX request to correctly pass the data as JSON objects and then use the data in the success function, rather than using PHP to display responses. As recommended by Velome I went down the JSON route and found a solution much quicker than trying to edit my original PHP responses

    $(document).on('click', '.printinfo', function(){
    
     var printinfo = $(this).attr('data-id');
         imageinfo = $(this).find().closest('img').attr('src');
     alert(printinfo);
     $('.modal-h1').html('');
     // AJAX request
     $.ajax({
      url: 'wp-content/themes/LEP/Modals/landscape-product-1.php',
      type: 'post',
      dataType: 'json',
      data: { printinfo: printinfo},
      success: function(data){
        console.log(data);
        console.log(data[0].href);
        console.log(data[0].id);
        console.log(data[0].title);
        alert(data);
        $('.modal-header').prepend('<h1 class=modal-h1>' + data[0].title +'</h1>');
        $('#modimg').attr('src', data[0].href);
    
        $('#myModal').modal('toggle');
        // Display Modal
        }
    });
    });
    

    And changed the while loop select and setup the array to be returned

     $printinfo = $_POST['printinfo'];
    
     $sql = "SELECT * FROM prints WHERE image ='".$printinfo."' LIMIT 1";
     $result = mysqli_query($conn, $sql);
     $return_arr = array();
    
     while($prints = mysqli_fetch_array($result)) : {
    
    
      $id = $prints['image'];
      $href = $prints['image_href'];
      $title = $prints['image_title'];
    
      $return_arr[] = array("id" => $id,
                      "href" => $href,
                      "title" => $title);
    
    
    } endwhile;
    
    $myJson = json_encode($return_arr);
    echo $myJson;
    exit;
    

  2. Problem is the way you do it, your code after "This then calls the modal pop up which is as follows" is not the way to do it.

    You should never get HTML code/tags with an Ajax Request.
    You should only get the "pure" data and integrate it with javascript in the DOM.

    The ideal way after loading your PHP page from the server is that your JS Ajax queries only get non-html data as response, so in this exemple your html code to display the pic should already be in the div at the begining, maybe with a dumy pic. Your Ajax request should just receive the url of the pic (echo($picUrl) on server side) OR (even better) multiple infos like url+title+description+place as JSON (just create a PHP array on server side and use JSON_ENCODE($myArray)).


    To be honest JSON is probably the way you should go to be able to send img url + all kind of other info to include in your modal.

    It would give you for exemple something like that {picSrc = "./img/pic043.png", title = "Great pic", date= "2020-11-18"} if you encode this array :

    $result = [ "picSrc" => "./img/pic043.png", 
                "title" => "Great pic", 
                "date"=> "2020-11-18"];
    header('Content-Type: application/json');
    echo json_encode($result);
    

    See detailed exemple here :https://makitweb.com/return-json-response-ajax-using-jquery-php/


    To put it easy and without JSON as in your exemple, your Ajax request to "wp-content/themes/LEP/Modals/landscape-product-1.php" should give you back the picture url as a response (or as part of the response if you use JSON).

    Also you should have already include a dumy image in the modal body like that :

     <div class="modal-body">
         <img src="./img/nopic.png" id="divImg">
     </div>
    

    So now if your Ajax call give you the picture url as response you just have to do this :

     $.ajax({
      url: 'wp-content/themes/LEP/Modals/landscape-product-1.php',
      type: 'post',
      data: {printinfo: printinfo},
      success: function(response){
     
        $('#divImg').attr('src',response); // Here response would be for exemple "./img/pic043.png"
    
        // Display Modal
        $('#empModal').modal('toggle');
      }
    

    And Boom!, you should see your pic in the modal when clicking in the galery 🙂

    Login or Signup to reply.
  3. To follow the nice job of Paul Stephen Davis, I will add some best practices stuff based on his response/code.

    header('Content-Type: application/json'); // <=== Say "it's JSON data", so for exemple if you go to the url in your browser it's correctly formated/display.
    
    $conn = mysqli_connect("localhost", "my_user", "my_password", "my_db"); // <=== It's not in your code but it's probably here IRL.
    
    if (mysqli_connect_errno()) {  // If there is an error with database connection it will send Json {error: "Failed to connect to MySQL: The error msg here."} with error code 500 (Server Intarnal Error).
      http_response_code(500);
      echo json_encode(["error"  => "Failed to connect to MySQL: " . mysqli_connect_error()]);
      exit();
    }
    
    $printinfo = $_POST['printinfo'];
    
    // Here we gonna use "Prepared Statement" so it's safer if someone is trying to do MySQL injection (aka: trying to insert stuff in the string with the variable to do unatended things).
    $sql = "SELECT * FROM prints WHERE image = ? LIMIT 1"; // Put ? where the variable is.
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $printinfo); // Bind the value to the ?.
    $stmt->execute();
    $result = $stmt->get_result();
    
    if (!$result) {  // If there is an error with query it will send Json {error: "Error with MySQL Query: The error msg here."} with error code 500 (Server Intarnal Error).
      http_response_code(500);
      echo json_encode(["error"  => "Error with MySQL Query: " . mysqli_error($conn)]);
      exit();
    }
    
    $return_arr = array();
    
    while ($prints =  $result->fetch_assoc()) : {
        $id = $prints['image'];
        $href = $prints['image_href'];
        $title = $prints['image_title'];
    
        $return_arr[] = array(
          "id" => $id,
          "href" => $href,
          "title" => $title
        );
      }
    endwhile;
    
    mysqli_close($con); // It will close the database connection (it will still be close at the end of script but its "by principle").
    
    $myJson = json_encode($return_arr);
    
    if($myJson === false || is_null($myJson)){ // <=== We check if JSON encoding want wrong.
      http_response_code(500);
      echo json_encode(["error"  => "Error encoding JSON."]);
      exit();
    }
    echo $myJson;
    exit;
    

    Keep in mind that the database native error message should be send out only in dev/debug mod, not in production because it can reveal important informations.

    Keep also in mind this is not the "shinny way" to do it, to do it better you can use a "try catch" and throw error in the error check, exemple :

    if(mysqli_connect_errno()) throw new Exception("Failed to connect to MySQL: " . mysqli_connect_error());

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search