Passing a value from bootstrap data-id to a php variable

梦想的初衷 提交于 2020-01-03 04:19:08

问题


I have a dropdown menu with several months values. This is an example of one of them.

<li data-toggle="modal" data-id="January" class="random " href="#AddMonth">January</li>

I would like to pass the "January" value to a php variable. Something like this

<div class="modal fade" id="AddMonth" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
    <h4 class="modal-title" id="myModalLabel">Update your information</h4>
  </div>
  <div class="modal-body">
      <?php
         // $month  = ? // month will contain the variable that was pass from data-id
         MethodSendMonthData($month);

       ?>
  </div>
</div>

I am not sure how could I achieve this?


回答1:


To elaborate on my comment previously.

You can use jQuery.ajax or even jQuery.post to achieve this.

For examples sake, your element has an id of mymonth

<li id="mymonth" data-toggle="modal" data-id="January" class="random " href="#AddMonth">January</li>

Now with jQuery you could get the trigger:

$(document).on('click', 'li#mymonth', function(){
    // get month
    var val = $(this).attr('data-id');

    $.post('myphpfile.php', {month: val}, function(data){
        console.log(data);
    });
});

As you can see, we grab the attribute data-id and store it in the val variable. Then post it off to the example php file : myphpfile.php

The myphpfile.php would have your php function as such (example of course):

<?php 

if(isset($_POST['month']) && !empty($_POST['month'])) {
    // do your sanatizing and such....
    // do your php stuff
    MethodSendMonthData($month);

   // you can echo back what you need to and use that in jquery as seen above
}

?>


来源:https://stackoverflow.com/questions/23050700/passing-a-value-from-bootstrap-data-id-to-a-php-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!