Passing jQuery variable to php in modal

I print photos and names (in grid). The user will be able to click on the image or name and this will open a modal with the image / name name (which will be the same) that 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 was clicked, how do I store the path to the image or the name that was clicked on the variable and send it to php so that I can trigger a request and get more information (based on the click) to populate the modal?

I was reading this post: How to pass jQuery variables to PHP variable? But that's just for one case, how would I pass variables that are printed using a while loop?

Was the data-id

modals tag helpful here?

+3


source to share


3 answers


Basically, you need to do the following:

  • Load images into page using code php

  • At the same time, download the buttons / links that select each image
  • For each button add an attribute data

    and store the database row id for each image record in this data attribute (these buttons are also configured to open the same modal code)
  • When the user clicks the button, get the saved row id of the clicked button
  • Make ajax call to another php page passing in id line
  • In another php page use id to find the record and return all fields
  • On the first page when the ajax call returns, use the returned data to populate the modal content

Here is a working example

Also note , depending on the additional information you get from the database, you can simply store all the information in the button data attributes on the first page load and avoid calling ajax all together. Of course, if you are getting a lot of data, like files pdf

or whatever, this might not be practical.



Full code for: imagesfromdb.php (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 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>

      

Complete code for: getimagedetails.php (the page we are making 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];
        }
    }
?>

      

+1


source


Try making 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 jQuery

$(function(){
    $('.pass_href').click(function(){
      var href = $(this).attr('data-href');
      $.post( "test.php", { href:href } );
    });
});

      

0


source


For displaying the modality details you need to submit the form using ajax. Here I give you the solution. First, add your two key attribute data-id

and call the event function

in onclick

.

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 submit the form with ajax for this call.like function -

<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 get your submitted id and find data for that id from database or wherever. and then return your data as a form json

using php function json_encode()

.

0


source







All Articles