Delete data without refreshing the page

2

I am no longer using extra pages to use functions within the PHP page. I use PDO with a php for the functions and use everything in the page without loading anything external.

My question is how to use ajax in this case. Home I want to send a button of a form, but the function is inside the page.
I quit the code.

Here's an example to delete data:

Form submitted to this section

if (isset($_POST['deletepost'])){

   if(empty($errors) === true){
      $postiddel = $postid;

      $users->deletepost($postiddel);
      header('Location: home');
      exit();
   }
}

HTML

<form method="post" name="deleteform" action="">

    <input type="text" name="postid" hidden value="<?php echo $postid; ?>">
    <li><button type="submit" name="deletepost" class="dropdownbutton">Eliminar publicação</button></li>

</form>

What I need to do is run the php that is inside the same page without refreshing the page .... I do not know if this is possible, but I hope it is, because I'm tired of using external pages.

    
asked by anonymous 22.12.2014 / 19:50

1 answer

5

Using the submit button using HTML will always call whatever is in the action and reload the page. An alternative method is to loop in javascript from all input fields (inputs, selects, etc) through some selector, for example a jquery selector like $ (': input) and pass the data through ajax. Jquery example:

function enviarDados() {
    $.ajax({
        type: POST, url: 'http://localhost/aplicacao',
        data: $(':input')
    }).done( function( res ) {
        alert('dados enviados');
    })
} 

You can put the call to this function on the submit button without it sending the page like this:

<input type='submit' value='Enviar' onclick='enviarDados(); return false;'>

'return false' in onclick prevents the button from making the actual submit of the form. So you can call an ajax function that sends the data without the form being sent.

    
22.12.2014 / 21:01