How to execute a JAVASCRIPT code by PHP without event

2

Next, I'm trying to replace alert with modal that of jquery that uses jquery. In case I'm using the first example:

<div id="ex1" class="modal">
  <p>Usuário ou senha incorretos.</p>
  <a href="#" rel="modal:close">Fechar</a>
</div>

<p><a href="#ex1" rel="modal:open">Open Modal</a></p>

However, in my case, this href should be executed in the php controller. That's where my problem comes in. How could I trigger this modal without an event (click type, for example)? In the case what I am referring to is echo '<script> código </script>'; . Thank you.

    
asked by anonymous 23.07.2018 / 06:49

1 answer

3

According to the documentation documentation, you can open the modal manually by just calling the method .modal() of the plugin on the element. Therefore, it is not necessary to trigger an event for this. The echo would be:

<?php
echo "<script> $('#ex1').modal(); </script>";
?>

The '#ex1' selector refers to id of the modal.

Example without using PHP, just to illustrate how it works:

$('#ex1').modal();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery-modal/0.9.1/jquery.modal.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-modal/0.9.1/jquery.modal.min.css" />
<div id="ex1" class="modal">
  <p>Usuário ou senha incorretos.</p>
  <a href="#" rel="modal:close">Fechar</a>
</div>

<p><a href="#ex1" rel="modal:open">Open Modal</a></p>

Remembering that, depending on where echo is run, the jQuery lib and elements must already have been loaded. In this case, to prevent it, it would be interesting to execute the method after the DOM has been loaded:

<?php
echo "<script>
document.addEventListener('DOMContentLoaded', function(){ $('#ex1').modal(); });
</script>";
?>
    
23.07.2018 / 07:14