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

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>//verificaseapáginafoicarregadaparaevitaraplicaroscódigosantesdeteralgumelementonãocarregado...$(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, into the <article></article> tag the selected page ....

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

What is the ideal solution for this case?

    
asked by anonymous 20.07.2014 / 22:00

2 answers

1

Opa,

Dude, I think you just need to preventDefault () on form submit, right? This inside a delegate as it will be loaded via ajax.

As for example:

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

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

Refs:

15.08.2014 / 05:30
0

Given a very simple example for 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'];
    
15.08.2014 / 06:18