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

2019-05-29 05:52发布

问题:

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
}

?>