3

I am printing out pictures and names (in a grid view). The user will be able to click on the picture or the name, and this will open up a modal with the title of the picture/name (which will be the same) which was clicked.

<?php
    $i = 0;
    while ($row = mysqli_fetch_assoc($data)) {
        print '<li>';
        print '<a class="btn btn-default" data-toggle="modal" data-target=".bs-example-modal-lg"><img src="'.$row["image"].'" /></a><br>';
        print '<a class="btn btn-default" data-toggle="modal" data-target=".bs-example-modal-lg"><h4>'.$row['name'].'</h4></a>';
        print '</li>';
    }
?>

When the image/name is clicked, how do I store the image path or the name that was clicked to a variable and send it to php so I can run a query and get more information (based on the click) to populate the modal?

I was reading this other post: How to pass jQuery variables to PHP variable? But it is only for a single case, how would I pass variables which are printed out using a while loop?

WOuld the data-id tag of modals be useful here?

Community
  • 1
  • 1
user2883071
  • 960
  • 1
  • 20
  • 50
  • is there any unique identifier for your data? like id.because name or image src can be same for other data. – Khairul Islam Apr 26 '15 at 19:42
  • Yes, there is an id... its just that I am not too sure how to implement the search for that... for now I know how to search depending on what is being showed. – user2883071 Apr 26 '15 at 19:43

3 Answers3

1

Basically, what you need to do is this:

  1. Load your images onto the page with your php code
  2. At the same time, load the buttons/links that select each picture
  3. For each button, add a data attribute and store the database row id for each image record in that data attribute (these buttons are all also setup to open the same modal)
  4. When the user clicks the button, get the stored row id from the clicked button
  5. Make an ajax call to another php page passing in the row id
  6. On the other php page, use the id to look up the record and return all of the fields
  7. Back on the first page, when the ajax call returns, use the returned data to fill in the modal's content

Here is a working example

Also note: depending on the additional information you are getting from the database, you might just store all of the information in data attributes of the button when the first page loads and avoid the ajax call all together. Of course, if you're getting a lot of data like pdf files or something, that might not be practical.

Full code for: imagesfromdb.php (the main page):

<?php
    // remove below for production
    ini_set('display_errors',1);
    ini_set('display_startup_errors',1);
    error_reporting(-1);
    // remove above for production
    
    // change these to your own database details
    $db = new PDO('mysql:host=sotestdbuser.db.10125908.hostedresource.com;dbname=sotestdbuser;charset=utf8', 'sotestdbuser', 'Sotestuser398!'); 
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); // later, change ERRMODE_WARNING to ERRMODE_EXCEPTION so users wont see any errors
    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    
    $sql = 'SELECT id, url FROM imagebase ORDER BY id';  
    $stmt = $db->prepare($sql);
    $stmt->execute(); 
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);  
    
    $imgGroups=array();
    // check for errors 
    if($stmt->errorCode() == 0) {
        // no errors
        foreach($rows as $row) {
            $id = $row['id'];
            $url= $row['url'];
            $imgGrp ='<div class="col-sm-4">'.
                      '<div class="row">'.
                        '<div class="col-sm-12 text-center"><img src="'.$url.'" width="100" height="100" alt=""/></div>'.
                        '<div class="col-sm-12 text-center">'. //note the addition of the "data-row-id" attribute below
                          '<button type="button" class="btn btn-primary get-data" data-row-id="'.$id.'" data-toggle="modal" href="#my-modal">Select image</button>'.
                        '</div>'.
                      '</div>'.
                    '</div>';
            array_push($imgGroups,$imgGrp);
        }
    } else {
        // had errors
        $errors = $stmt->errorInfo();
        return $errors[2];
    }
    
?>
<!DOCTYPE html>
<html lang="en">
    <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <title>Images From Database Test</title>

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
    <style>
img {
    display: block;
    margin-left: auto;
    margin-right: auto
}
</style>
    </head>
    <body>
<div class="row  text-center" >
      <h1>Image From DB Test</h1>
    </div>
<div class="row" >
      <div class="col-sm-12" id="image-groups"> <?php echo join('',$imgGroups); ?> </div>
    </div>

<!-- Modal 7 (Ajax Modal)-->
<div class="modal fade" id="my-modal" >
      <div class="modal-dialog">
    <div class="modal-content modal-shadow">
          <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h4 class="modal-title" id="my-modal-title" >Help</h4>
      </div>
          <div class="modal-body">
        <div class="col-sm-12 text-center"><img src="" class="image" id="my-modal-image" width="100" height="100" alt=""/></div>
        <div class="col-sm-12 text-center description" id="my-modal-description"> </div>
      </div>
          <div class="modal-footer">
        <button type="button" id="" class="btn btn-default  reload" data-dismiss="modal">Close</button>
      </div>
        </div>
  </div>
    </div>

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css">
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> 
<!-- Latest compiled and minified JavaScript --> 
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script> 
<script>
     $(function(){
         // when the user clicks on one of the buttons, get the id from the clicked button 
         // then make an ajax call to another php page 
         $('#image-groups').on('click', '.get-data', function(){
             var id = $(this).data('row-id');
             var sendVars = 'id='+encodeURIComponent(id);
                $.ajax({
                    type: "POST",
                    url: "getimagedetails.php",
                    data: sendVars, 
                    success: function(rtnData) {
                       rtnData = $.parseJSON(rtnData)
                       $('#my-modal-title').html(rtnData.title);
                       $('#my-modal-image').attr('src', rtnData.url);
                       $('#my-modal-description').html(rtnData.description);
             
                        
                    }
                });
         });
         
         
     });
    </script>
</body>
</html>

Full code for: getimagedetails.php (the page we make the ajax call to)

  <?php
    // remove below for production
    ini_set('display_errors',1);
    ini_set('display_startup_errors',1);
    error_reporting(-1);
    // remove above for production
    
    // change these to your own database details
    $db = new PDO('mysql:host=sotestdbuser.db.10125908.hostedresource.com;dbname=sotestdbuser;charset=utf8', 'sotestdbuser', 'Sotestuser398!'); 
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); // later, change ERRMODE_WARNING to ERRMODE_EXCEPTION so users wont see any errors
    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    
    

    if(isset($_POST['id'])){
        
        $sql = 'SELECT url, title, description FROM imagebase WHERE id=?  LIMIT 1';  // "?"s here will get replaced with the array elements belowlinkslinks
        $stmt = $db->prepare($sql);
        $stmt->execute(array($_POST['id'])); // these array elements will replace the above "?"s in this same order
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
        // check for errors 
        if($stmt->errorCode() == 0) {
            // no errors
            $rowdata = 'test';
            foreach($rows as $row) {
                $rowdata = array('url' =>$row['url'], 'title' =>$row['title'], 'description' =>$row['description']);
            }
            echo json_encode($rowdata);
        } else {
            // had errors
            $errors = $stmt->errorInfo();
            echo $errors[2];
        }
    }
?>
Community
  • 1
  • 1
Wesley Smith
  • 19,401
  • 22
  • 85
  • 133
0

Try to make an ajax call onClick of the element

<?php
        $i = 0;
        while ($row = mysqli_fetch_assoc($data)) {
            print '<li>';
                print '<a class="pass_href btn btn-default" data-toggle="modal" data-href="test/path/to-the-image.jpg" data-target=".bs-example-modal-lg"><img src="'.$row["image"].'" /></a><br>';
                print '<a class="pass_href btn btn-default" data-toggle="modal" data-href="test/path/to-the-image-2.jpg" data-target=".bs-example-modal-lg"><h4>'.$row['name'].'</h4></a>';
            print '</li>';
        }
    ?>

Now the jQuery

$(function(){
    $('.pass_href').click(function(){
      var href = $(this).attr('data-href');
      $.post( "test.php", { href:href } );
    });
});
Azad Zain
  • 143
  • 11
  • Ah, so if I am reading this correctly, the jqeury portion identifies the href being clicked, then it assigns the href to a variable href.. and then it posts it to the page (in this case test.php), right? how would you explain this? what is the difference between the 2nd line and 3rd line of the jquery code? (is it that one identified the click and the other set the variable?) – user2883071 Apr 26 '15 at 19:19
  • Also, I am receiving the variable as such: `$name = $_GET['href'];` within php tags, but I am getting the message: `Undefined index:href`. I also tried it with `$_POST`, same error – user2883071 Apr 26 '15 at 19:33
  • Would still like this solution too – user2883071 Apr 26 '15 at 23:01
  • I did try it with `$_POST['href'];` and still the same result – user2883071 Apr 27 '15 at 21:38
0

For showing details information on the modal you need to post a form using ajax.Here i am giving you a solution.First add a data-id attribute in your both buttons and also call a function in onclick event.

print '<li>';
print '<a class="btn btn-default" data-id='.$row['id'].' onclick="show(this);" data-toggle="modal" data-target=".bs-example-modal-lg"><img src="'.$row["image"].'" /></a><br>';
print '<a class="btn btn-default" data-id='.$row['id'].' onclick="show(this);" data-toggle="modal" data-target=".bs-example-modal-lg"><h4>'.$row['name'].'</h4></a>';
print '</li>';

and then post a form using ajax on that function call.like-

<script>
function show(x){
    var id = $(x).data('id');
      $.ajax({
        type: "POST",
         url: "your/url",
         data: { id: id},
             success: function(data) {
                //parse your json data
                    var obj = $.parseJSON(data);
                    if (obj != null){
                      //append/show your data in your modal body
                    }
              }
          });                              
         } 
</script>

and in your php function receive your posted id and find details for that id from the database or anywhere. and then return your data as json type using php json_encode() function.

Khairul Islam
  • 1,207
  • 1
  • 9
  • 20
  • Thanks for the answer, So I have never used json, and I am not too sure how to `//append/show your data in your modal body` within jquery. Is there a simpler way of doing it? like in the other answer? Also, I am trying it out, but in this case, how do I get the value in php then? is it something like: `$name = $_GET['obj']; ?` Also, is it necessary that I return any data? can I not display it within php after querying the db? – user2883071 Apr 26 '15 at 21:01
  • yeah, something like that. this is a form submission nothing else. as like the normal way `$id = $_POST['id'];` you can receive the data. then return your data just using `json_encode('your data array or whatever you want to return')`. and then parse you returned data using`$.parseJSON(data)`. now showing them- for showing your data in the modal body you should keep the space/tag for your every data.like you want to show name in the modal then you can keep a div with a specific id and just change the html of that div like this- `$("#your-div-Id").html(obj["your data"]);` – Khairul Islam Apr 26 '15 at 21:15
  • I am getting an undefined index error when receiving the variable. I tried: `$id = $_POST['id'];` and `$id = $_GET['id'];` – user2883071 Apr 26 '15 at 21:38
  • can you please check with an alert that your `var id` has the value or not? just put an alert like `alert(id)` after `var id`. – Khairul Islam Apr 26 '15 at 21:43
  • Yes, it is returning a value, the first image returns 1, the second returns 2 – user2883071 Apr 26 '15 at 21:49
  • have you included jQuery library in that page? – Khairul Islam Apr 26 '15 at 21:50
  • I have included: https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js – user2883071 Apr 26 '15 at 21:51
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/76304/discussion-between-khairul-islam-and-user2883071). – Khairul Islam Apr 26 '15 at 21:54