How to run PHP JAVASCRIPT code without an event

Asked

Viewed 26 times

2

Next, I’m trying to replace the alert for modal of that lib that uses jquery. In this case I am 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 run 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 I’m referring to is echo '<script> código </script>';. Thank you.

  • Why can’t you use a click event?

  • You want it to run, open the modal, dps from php execution?

  • Why it should be triggered according to a query result

1 answer

3


According to the documentation at this link, you can open the modal manually just by calling the method .modal() 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 selector '#ex1' refers to the id modal.

Example without use of 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>
<script src="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 the echo is executed, the jQuery lib and the elements must have already been loaded. In this case, to be safe, it would be interesting to execute the method after the DOM has been loaded:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.