Calling PHP function via a button in a modal

Asked

Viewed 197 times

0

I’m displaying the amount of files in a directory, within a modal, I want to call a function in PHP when the user clicks the button "Erase", tried to use onclick , but it didn’t work.

My code:

 <!-- Meu modal -->
  <div class="modal" id="c_up_pa">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-body">
          <h3>Arquivos sobrando...</h3>
          <hr>
          <p>
            <?php 
            foreach($files as $file){
            if(!in_array($file, $images)){

            echo "Cerca de <b>" .count($file). "</b> arquivo(s) que não estão no banco de dados <p>"; // Número total

            echo "Nomes dos arquivos: <b>" . $file . "</b><br>"; // Exibe os arquivos

           }}?>
        </p>
        </div>

        <div class="modal-footer">
          <button type="submit" onclick="apagar_files()" class="btn btn-danger">Apagar</button>
          <button type="button" class="btn btn-primary" data-dismiss="modal">Fechar</button>
        </div>

         <?php
           function apagar_files(){
           if (file_exists($file))
           unlink($file); }          
         ?>

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

What I’m not getting is call the function via a button correctly.

How can I be doing?

1 answer

0


Come on. PHP is a side serve language, meaning it runs on the server

HTML, CSS and JAVASCRIPT are processed in the client side, i.e., runs in the user’s browser.

With this in mind, your code will not work as you are trying to run a Server Side process on the Client Side.

What I suggest to you is to perform an AJAX request in a.php file and in that file you run the function code.

Example:

$(document).ready(function(){ $('.btnDeletar').on('click', function(){ $.ajax({ method: "POST", url: "deletar.php", success: function(data){ alert('Arquivos Deletados'); } }); }); });

  • 1

    Thank you for the answer, I am new to programming! I will take the test.

  • Hello, the button doesn’t do anything apparently, it’s like this: <button type="submit" onclick="btnDeletar()">Apagar</button> , I put the script below already, and created a page called "delete.php" and put the action, however, was not...

  • first add the "bntDeletar" class to your delete button, change its type to button and try again, in case it still doesn’t work see that error in the console.

  • It appears that "btnDeletar" is not set

  • I forgot to mention, remove onclick="btnDeletar()"

  • And put what into button to reference the script?

  • the btnDeletar class

Show 2 more comments

Browser other questions tagged

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