Quick question. How do I call a Bootstrap Modal from PHP? I have a form and when some error happen I want to show an alert modal to the user. I've tried many solutions from other topics but neither has worked.
Here's what I've tried last:
echo '<script type="text/javascript">';
echo '$(\'#alertDuplicate\').modal(\'show\')';
echo '</script>';
and here's the modal:
<!-- Modal Alert Duplicate -->
<div class="modal fade" id="alertDuplicate">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Erro</h4>
</div>
<div class="modal-body">
<p>Essa função já existe!</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
Try putting that into a document ready function like this:
echo '<script type="text/javascript">';
echo '$(document).ready(function() {';
echo '$("#alertDuplicate").modal("show");';
echo '});';
echo '</script>';
You can use the example below or you can use ajax to call and return the response from your php script.
echo <<<EOT
<script type="text/javascript">
$(document).ready(function() {
$('#alertDuplicate').modal('show');
});
</script>
EOT;
AJAX EXAMPLE
With ajax you can use something like this:
<script type="text/javascript">
$(document).ready(function () {
$("input#submit").click(function(){
$.ajax({
type: "POST",
url: "YOUR_PHP_FILE.php",
data: $('form.FORM_NAME').serialize(),
success: function(msg){
$("#alertDuplicate").modal('hide');
},
error: function(){
$("#alertDuplicate").modal('show');
}
});
});
});
</script>
(You have to change the words "FORM_NAME" and "YOUR_PHP_FILE" with your needs)