在模式中将Jquery变量传递给php

时间:2021-04-19 10:02:50

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?

单击图像/名称时,如何存储图像路径或单击到变量的名称并将其发送到php,以便我可以运行查询并获取更多信息(基于单击)来填充模式?

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?

我正在阅读另一篇文章:如何将jQuery变量传递给PHP变量?但是只针对单个案例,我如何传递使用while循环打印出来的变量?

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

WOuld模态的data-id标签在这里有用吗?

3 个解决方案

#1


1  

Basically, what you need to do is this:

基本上,你需要做的是:

  1. Load your images onto the page with your php code
  2. 使用php代码将图像加载到页面上

  3. At the same time, load the buttons/links that select each picture
  4. 同时,加载选择每张图片的按钮/链接

  5. 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)
  6. 对于每个按钮,添加一个数据属性并存储该数据属性中每个图像记录的数据库行ID(这些按钮也都设置为打开相同的模态)

  7. When the user clicks the button, get the stored row id from the clicked button
  8. 当用户单击该按钮时,从单击的按钮获取存储的行ID

  9. Make an ajax call to another php page passing in the row id
  10. 对另一个传递行id的php页面进行ajax调用

  11. On the other php page, use the id to look up the record and return all of the fields
  12. 在另一个php页面上,使用id查找记录并返回所有字段

  13. Back on the first page, when the ajax call returns, use the returned data to fill in the modal's content
  14. 回到第一页,当ajax调用返回时,使用返回的数据填充模态的内容

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.

另请注意:根据您从数据库获取的其他信息,您可能只在第一页加载时将所有信息存储在按钮的数据属性中,并避免一起调用ajax。当然,如果您获得了大量数据,如pdf文件或其他东西,那可能不太实际。

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

完整代码:imagesfromdb.php(主页):

<?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)

完整代码:getimagedetails.php(我们调用ajax的页面)

  <?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];
        }
    }
?>

#2


0  

Try to make an ajax call onClick of the element

尝试在点击元素上进行ajax调用

<?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

现在是jQuery

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

#3


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.

为了显示有关模态的详细信息,您需要使用ajax发布表单。这里我给你一个解决方案。首先在两个按钮中添加一个data-id属性,并在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 post a form using ajax on that function call.like-

然后在该函数调用上使用ajax发布一个表单。

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

并在您的PHP函数中接收您发布的id并从数据库或任何地方查找该ID的详细信息。然后使用php json_encode()函数以json类型返回数据。

#1


1  

Basically, what you need to do is this:

基本上,你需要做的是:

  1. Load your images onto the page with your php code
  2. 使用php代码将图像加载到页面上

  3. At the same time, load the buttons/links that select each picture
  4. 同时,加载选择每张图片的按钮/链接

  5. 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)
  6. 对于每个按钮,添加一个数据属性并存储该数据属性中每个图像记录的数据库行ID(这些按钮也都设置为打开相同的模态)

  7. When the user clicks the button, get the stored row id from the clicked button
  8. 当用户单击该按钮时,从单击的按钮获取存储的行ID

  9. Make an ajax call to another php page passing in the row id
  10. 对另一个传递行id的php页面进行ajax调用

  11. On the other php page, use the id to look up the record and return all of the fields
  12. 在另一个php页面上,使用id查找记录并返回所有字段

  13. Back on the first page, when the ajax call returns, use the returned data to fill in the modal's content
  14. 回到第一页,当ajax调用返回时,使用返回的数据填充模态的内容

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.

另请注意:根据您从数据库获取的其他信息,您可能只在第一页加载时将所有信息存储在按钮的数据属性中,并避免一起调用ajax。当然,如果您获得了大量数据,如pdf文件或其他东西,那可能不太实际。

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

完整代码:imagesfromdb.php(主页):

<?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)

完整代码:getimagedetails.php(我们调用ajax的页面)

  <?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];
        }
    }
?>

#2


0  

Try to make an ajax call onClick of the element

尝试在点击元素上进行ajax调用

<?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

现在是jQuery

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

#3


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.

为了显示有关模态的详细信息,您需要使用ajax发布表单。这里我给你一个解决方案。首先在两个按钮中添加一个data-id属性,并在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 post a form using ajax on that function call.like-

然后在该函数调用上使用ajax发布一个表单。

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

并在您的PHP函数中接收您发布的id并从数据库或任何地方查找该ID的详细信息。然后使用php json_encode()函数以json类型返回数据。