Passing Data via Modal Bootstrap and Getting PHP Variable

Passing data via Modal Bootstrap and getting php variable?

<button type='button' data-a="<?echo $fila['idPlaza'];?>" href='#editarUsuario' class='modalEditarUsuario btn btn-warning btn-xs' data-toggle='modal' data-backdrop='static' data-keyboard='false' title='Editar usuario'>
<img src='../images/edit.png' width='20px' height='20px'>
</button>

Put below code in footer before end of </body> tag.

<!-- MODAL EDITAR-->
<div id="editarUsuario" class="modal fade modal" role="dialog">
<div class="vertical-alignment-helper">
<div class="modal-dialog vertical-align-center">
<div class="modal-content">

</div>
</div>
</div>
</div>

Use Script like this.

<script>
$('.modalEditarUsuario').click(function(){
var ID=$(this).attr('data-a');
$.ajax({url:"NewPage.php?ID="+ID,cache:false,success:function(result){
$(".modal-content").html(result);
}});
});
</script>

Create NewPage.php, and paste the below code.
(Remember, this page name NewPage.php is used in script tag also. if you are planning to change the name of this page, change page name there in script tag too. Both are related.)

<?
$ID=$_GET['ID'];
?>
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h2 class="modal-title">Editar usuario</h2>
</div>
<form name="formularioModificaUsuario" method='post' action="usuarios.php">
<div class="modal-body">
<input type="text" class="form-control" name="idPlaza" id="a">
<?php
$valueA = $ID;
?>
</div>
<div class="modal-footer">
<button type="reset" id="cancelar" class="btn btn-danger" data-dismiss="modal" value="reset">
<img src='../images/cancel.png' width='20px' height='20px'> Cancelar</button>
<button type="submit" name="submitModifica" id="submit" class="btn btn-primary" value="submit">
<img src='../images/save_changes.png' width='20px' height='20px'> Guardar cambios</button>
</div>
</form>

Pass PHP variable to bootstrap modal

If, I got you correct.

The modal trigger button with $row['ID']

$order .= '<td><a href="#myModal" class="btn btn-default btn-small" id="custId" data-toggle="modal" data-id="'.$row['ID'].'">Edit</a></td>';

Bootstrap Modal event to fetch the $row['ID'] value with Ajax method

$(document).ready(function(){
$('#myModal').on('show.bs.modal', function (e) {
var rowid = $(e.relatedTarget).data('id');
$.ajax({
type : 'post',
url : 'fetch_record.php', //Here you will fetch records
data : 'rowid='+ rowid, //Pass $id
success : function(data){
$('.fetched-data').html(data);//Show fetched data from database
}
});
});
});

Modal HTML

<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Edit Data</h4>
</div>
<div class="modal-body">
<div class="fetched-data"></div> //Here Will show the Data
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>

Last Create fetch_record.php, retrieve the record and show in modal

<?php
//Include database connection
if($_POST['rowid']) {
$id = $_POST['rowid']; //escape string
// Run the Query
// Fetch Records
// Echo the data you want to show in modal
}
?>

How to send a PHP variable to a modal bootstrap and receive it as PHP variable?

You want to pass a user id to bootstrap modal.

So this occurs on client-side, when PHP has finished its execution long ago.

In your PHP loop, the trick will be to store the user id in a data attribute on the link which opens the modal.

Then an additional script will retreive that value to passe it to an hidden input of the modal.

See comments in code below for what was added.

USUARIOS.PHP:

<?php
if(isset($_POST['userID'])){
// if an id was posted, execute this script.

// You can save to database here.
// ...
}

?>

<!-- IMPORT THE MODAL FROM OTHER PAGE -->
<?php require_once('editar_usuario.php'); ?>

<!-- Here is the PHP variable that I need to send to the modal on the other page. -->
<?php $id_user = $carregaUsuarios["id"]; ?>

<table id="table_id2" class="table table-striped table-bordered table-hover" cellspacing="0" width="100%">
<thead>
<tr>
<th width="110px;"></th>
<th>ID</th>
<th>Nome</th>
<th>Login</th>
<th>Senha</th>
<th>Data</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<?php foreach ( $carregaUsuarios as $carregaUsuarios ) { ?>
<tr>
<td width="110px;" align="center">
<!-- BOTÃO EDITAR -->

<!-- data-id was added in the line below -->
<a class="btn btn-primary btn-sm" data-toggle="modal" data-target="#editarUsuario" data-id="<?php echo $id_user; ?>" title="Editar"><i class="fa fa-pencil text-white"></i></a>

<!-- BOTÃO VISUALIZAR -->
<a class="btn btn-success btn-sm" data-toggle="modal" data-target="#visualizarUsuario" title="Visualizar"><i class="fa fa-search text-white"></i></a>

<!-- BOTÃO EXCLUIR -->
<a class="btn btn-danger btn-sm" data-toggle="modal" data-target="#excluirUsuario" title="Alterar Status"><i class="fa fa-refresh text-white"></i></a>
</td>
<td><?php echo $carregaUsuarios["id"]; ?></td>
<td><?php echo $carregaUsuarios["nome"]; ?></td>
<td><?php echo $carregaUsuarios["login"]; ?></td>
<td><?php echo $carregaUsuarios["senha"]; ?></td>
<td>
<?php
$carregaUsuarios["data"] = date("d/m/Y H:i:s", strtotime($carregaUsuarios["data"]));
echo $carregaUsuarios["data"];
?>
</td>
<td>
<?php
if($carregaUsuarios["status"] == 0) {
echo "<span class='badge badge-danger'>INATIVO</span>";
}else{
echo "<span class='badge badge-success'>ATIVO</span>";
}
?>
</td>
</tr>
<?php } ?>
</tbody>
</table>

<!-- This whole script was added -->
<script>
$(document).ready(function(){
$("[data-target='#editarUsuario']").on("click", function(){
var userID = $(this).data("id");
$("#userID").val(userID);
});
});
</script>

EDITAR_USUARIOS.PHP:

<?php 
//I JUST NEED GET THE VARIABLE PHP $ID FROM PAST PAGE TO USE HERE AND MAKE SOME SELECTS IN DATA BASE
//$id = $carregaUsuarios["id"]; // No use for this here.
?>

<div class="modal fade" id="editarUsuario" tabindex="-1" role="dialog" aria-labelledby="editarUsuarioLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="editarUsuarioLabel">Editar Usuário</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form action="#" method="POST">
<input type="hidden" id="userID" name="userID"> <!-- This hidden input was added-->
<div class="form-group">
<label for="recipient-name" class="form-control-label">Nome:</label>
<input type="text" class="form-control something" name="nome" id="nome">
</div>

<div class="form-group">
<label for="recipient-name" class="form-control-label">Login:</label>
<input type="text" class="form-control" name="login" required>
</div>

<div class="form-group">
<label for="recipient-name" class="form-control-label">Senha:</label>
<input type="password" class="form-control" name="senha" required>
</div>

<div class="form-group">
<label for="recipient-name" class="form-control-label">Nível de Permissão:</label>
<select name="nivel_permissao" class="form-control" aria-describedby="nivel_permissao" required>
<option></option>
<option value="1">ADMINISTRADOR</option>
<option value="2">INTERMEDIÁRIO</option>
<option value="3">BÁSICO</option>
</select>
<small id="nivel_permissao" class="form-text text-muted">
Administrador - Cadastro, Edição, Exclusão, Visualização e Backup.
<br />
Intermediário - Cadastro, Edição, Visualização.
<br />
Básico - Visualização.
</small>
</div>

<div class="form-group">
<label for="recipient-name" class="form-control-label">Status:</label>
<select name="status" class="form-control" required>
<option value="1">ATIVO</option>
<option value="0">INATIVO</option>
</select>
</div>

<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>
<button type="submit" class="btn btn-primary">Confirmar</button>
</div>
</form>
</div>
</div>
</div>
</div>

So you will receive this id back on PHP side, on form submit via $_POST['userID']

I assumed you loaded the jQuery library...

pass php variables to bootstrap modal from button click no ajax

In your code, data you pass through data-vendor and data-id-product-name are not printed. If you see the source they will be empty.

Try printing the data you pass for these values from PHP.

See the modification I have done below

<button type="button" class="open-details-modal btn btn-primary" 
data-vendor="<?php echo $product['Vendor']; // <--- check this ?>"
data-id-product-name="<?php echo $product['ProductName']; // <--- check this ?>"
href="#detailsmodal" data-target="#detailsModal">Product Details</button>

pass php variable in modal bootstrap

In my project I'm using data- attributes.

Example. Look, how do I pass code to modal.

Link:

<a href="#modal-info" class="text-muted" data-toggle="modal" data-code="{{ code }}">

Modal:

<div class="modal fade" id="modal-info">
<dd name="code"></dd>
</div>

Event listener:

$('#modal-info').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget); // Button that triggered the modal
var code = button.data('code');
var modal = $(this);

modal.find('[name="code"]').text(code);
}

How to pass a GET variable in Bootstrap Modal?

Bootstrap modal href is not calling your page when you click. Your page is already loaded when you include userDetails.php. So you can define the get before the include or pass the user id through GET variable.

So:

<div class="modal fade" tabindex="-1" role="dialog" aria-labelledby="modal-user" aria-hidden="true" id="modal-user">
<div class="modal-dialog modal-lg">

<?php
$_GET['id_user'] = $rel['id_user'];
include('userDetails.php');
?>

</div>
</div>

In a LOOP

If you have a loop and want to do it dynamically through the jQuery you can do the following:

Remove the bootstrap calls from your link, and add a trigger class modal-btn and make it like:

<a 
class="btn btn-primary modal-btn btn-xs"
href="userDetails.php?id_user=<?= $rel['id_user'] ;?>"><?= $rel['id_user'] ;?>
</a>

Update your modal structure and remove the include():

<div class="modal fade" tabindex="-1" role="dialog" aria-labelledby="modal-user" aria-hidden="true" id="modal-user"> 
<div class="modal-dialog modal-lg">
<div class="modal-content"></div>
</div>
</div>

The jQuery should get the href property of the link and call the bootstrap modal function load and also force the modal to show

$(".modal-btn").on('click',function(e){ //trigger when link clicked
e.preventDefault();
$('#modal-user').modal('show'); //force modal to show
$('.modal-content').load( $(this).attr('href')); //load content from link's href
});

So your page userDetails.php will be loaded inside the modal, and you will need to remove the <div class="modal-content">...</div> from it to avoid duplication...



Related Topics



Leave a reply



Submit