How to submit form without being redirected by the action attribute?

Asked

Viewed 3,250 times

1

The structure of the site is as follows:

index.html:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script>
       // verifica se a página foi carregada para evitar aplicar os códigos antes de ter algum elemento não carregado...
        $(document).ready(function(){
            $(".ajax").on("click", function(e){
                e.preventDefault(); //eliminamos o evento
                var path = $(this).attr('href'); //Pegamos o caminho
                $("#main").empty();
                $("#main").load(path); //Faz uma requisição http para o servidor. //carrega a página (o path) passada como parâmetro... 
            });
        });
</script>


<body>
    <nav>
            <ul>
                <li><a href="./contato.html" class="ajax" data-title="Meu site - Contato">Contato</a></li>
                <li><a href="./sobre.html" class="ajax" data-title="Meu site - Sobre">Sobre</a></li>
                <li><a href="./upload.php" class="ajax" data-title="Meu site - upload">upload</a></li>

            </ul>
    </nav>

   <article id='main'> <!-- #main será atualizado consoante a navegação que o utilizador fizer via Ajax... -->         

      <!-- Home.html -->  


   </article>

</body>

upload.php:

<?php

include 'functions.php';
include 'db_connect.php';

$requestMethod = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : null;
$submit = isset($_POST['submit']) ? $_POST['submit'] : null;

//Pregunta si está llegando una petición por POST, lo que significa que el usuario envió (submit) el formulario.
if ($requestMethod === 'POST' && $submit === 'Upload'){

    $file_audio = $_FILES["input_audio"]; 
    $file_cover = $_FILES["input_cover"]; 

    $errors_file_audio = valida_file_audio($file_audio); 

    $errors_file_cover = valida_file_cover($file_cover);

     if (empty($errors_file_audio) && empty($errors_file_cover)){

            $status  =  save_files($file_audio, $file_cover, $mysqli);

             if (is_array($status) && !empty($status)){

                foreach ($status as $item){
                    echo "<label> <p style='color:red;'>" . $item . "<br />" . "</p></label>";
                }
            }else{
                    //echo"<label> <p style='color:green;'> Upload realizado com sucesso!</p> </label>";
                 } 

    }

}

?>

<!-- Validar Campos com JavaScript e JQuery -->
<script src="jquery-1.6.2.js" type="text/javascript"></script>
<script src="jquery.validate.js" type="text/javascript"></script>
<script src="validar.js" type="text/javascript"></script>
<!--CSS para configurar as mensagens de erro (js e Jquery) -->

<style type="text/css">
/* Estilizar os alertas */
label.error{
padding-left: 5px;
color: red;
font-weight: bold;
}
</style>



<div class='upload'>


        <h1>Upload</h1>

            <?php
            $sucesso = isset($_GET['sucesso']) ? $_GET['sucesso'] : null;

            if ($sucesso == 'sdfgjhksladtfJH456') {

                echo"<label> <p style='color:green;'> Upload realizado com sucesso!</p> </label>";

            }

            ?>

            <form id="form_Upload" enctype="multipart/form-data" action="upload.php"  method="POST">

                        <label for="audio">MP3:</label><br />
                        <input type="file" name="audio" id="audio" size="45" />    

                        <?php

                            $errors_file_audio = isset($errors_file_audio) ?  $errors_file_audio : null;

                                if (is_array($errors_file_audio)){

                                    foreach ($errors_file_audio as $item){

                                         echo " <label> <p style='color:red;'>" . $item . "<br />" . "</p>  </label>";

                                    }
                                }

                        ?>

                        <br /><br />

                        <label for="cover">Cover:</label><br />
                        <input type="file" name="cover" id="cover" size="45" />

                        <?php

                             $errors_file_cover = isset($errors_file_cover) ?  $errors_file_cover : null;

                                if (is_array($errors_file_cover)){

                                    foreach ($errors_file_cover as $item){

                                         echo "<label> <p style='color:red;'>" . $item . "<br />" . "</p>  </label>";

                                    }
                                }              
                        ?>

                        <br /><br />
                        <input type="submit" name="submit" value="Upload" />

                     </form>

</div>   

That is, I have a main page (index.html) that "loads", via Ajax, for the tag <article></article> the selected page....

The idea is to submit the form, without being redirected by the action="upload.php" attribute of the tag <form></form>. That is, stay at index.html and keep upload.php inside the tag <article></article> even after uploading the files.

What is the ideal solution for this case?

  • Yes, how do I do that in practical terms?

  • At a glance at this article, he uses Formdata to submit the form with input file using ajax. http://portfolio.planetjon.ca/2014/01/26/submit-file-input-via-ajax-jquery-easy-way/

  • Wakim, I graduate your availability.

2 answers

1

Opa,

Dude, I think it’s enough to get preventDefault() in the form Ubmit, right? That inside a delegate because it will be loaded via ajax.

For example:

$('body').delegate("#frmAutenticar",'submit',function(e) {  
  e.preventDefault();
  // processa o formulario via ajax...          
});

In this case, the #frmAutenticar will be processed and the url will not change, the user remains on the same page. Dai just adapt to your form, the cat jump is in delegate since your form comes via ajax.

Refs:

  • Submit is recommended for form

  • I am using Submit after a delegate because the form is created via ajax after the click, according to the above example of the person who asked the question.

1

Giving a very simple example to the case, passing via POST

js

$('form[name="NOMEDOFORM"]').submit( function(){
    event.preventDefault();
    $.ajax({
        url      : 'page.php',
        type     : 'POST',
        data     : { campoA : $("#campoA").val() , campoB : $("#campoB").val() },
        success  : function( resultado ){
            // ação quando o resultado for satisfatório
        }
    });
});


page.html

$campoA = $_POST['campoA'];
$campoB = $_POST['campoB'];
  • so it won’t work because the form is created via AJAX, then Voce has to use delegate and then you attach the Submit to the element.

Browser other questions tagged

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