Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a PHP function on a Bootstrap Modal using AJAX

I have a list of users echoed on my page using a PHP loop. When I click each user's name, a Bootsrap Modal pops up and display further details of the user. The links look like this.

<a href="#user"  data-toggle="modal"  data-id="{$user['id']}">UserName</a>

As you can see, I'm passing user's ID to the Bootstrap modal so that I can use it to retrieve other information of the user by calling get_user_by_id() in the Bootstrap Modal.

Modal Looks like this

<div class="modal fade" id="user">
    <div class="modal-header">
        <button class="close" data-dismiss="modal">×</button>
        <h3>Modal header</h3>
    </div>
    <div class="modal-body">
        <?php
          $user = get_user_by_id($id);
         ?>
        <input type="text" name="bookId" id="bookId" value=""/>
    </div>
</div>

JS code is like this

$('#user').on('show.bs.modal', function (event) {
   var button = $(event.relatedTarget)
   var id = button.data('id')
})

According to the above JS code, I have my user's ID in var id variable. But, ther's no way I can imagine how to use that value for the above PHP function as the argument.

Is there any possible way for that?

I have edited the question to be more unique about AJAX methods which most answers were based on AJAX

PS: I'm very new to PHP and Bootstrap.

like image 319
Tharindu Thisarasinghe Avatar asked Apr 23 '15 18:04

Tharindu Thisarasinghe


1 Answers

You will want to use ajax to run the PHP. As @Tom states javascript cannot access PHP after the loading in the DOM. PHP is a server side language and can only be accessed as such.

Once you connect to the PHP through ajax you can then load the div with the content from the return. Only AFTER the content is loaded should you open the modal otherwise you will have a jumpy look of the box showing up and then content just appearing.

Basic example

$(".btn").click(function(){
    // AJAX code here.
    $.ajax(
    ....
    success: function($data){
      $('.target').html(data)
      $("#myModal").modal('show');
    }
    );
});
like image 52
Cayce K Avatar answered Sep 19 '22 15:09

Cayce K