A single script for N Formularios

Asked

Viewed 988 times

3

I need to know the correct way to when I submit a form a single script solve, the code below only works if I create a script for each form. How do I fix it?

Example: $("#meuform") ... $("#meuform2") ... $("#meuform3"), etc..

    <html>
    <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title> teste </title>
    <meta name="" content="" />
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
    <script type="text/javascript" src="jquery.form.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $(".resultado").hide();
            $("#meuform").ajaxForm({
                target: '.resultado',
                success: function(retorno){
                     $(".resultado").html(retorno);
                     $(".resultado").show();
                     $("#meuform").resetForm();
                }
            });
        });
    </script>
    <script type="text/javascript">
        $(document).ready(function() {
            $(".resultado").hide();
            $("#meuform2").ajaxForm({
                target: '.resultado',
                success: function(retorno){
                     $(".resultado").html(retorno);
                     $(".resultado").show();
                     $("#meuform2").resetForm();
                }
            });
        });
    </script>
    <script type="text/javascript">
        $(document).ready(function() {
            $(".resultado").hide();
            $("#meuform3").ajaxForm({
                target: '.resultado',
                success: function(retorno){
                     $(".resultado").html(retorno);
                     $(".resultado").show();
                     $("#meuform3").resetForm();
                }
            });
        });
    </script>
    </head>
    <body>
    <div class="resultado"> aqui é o reultado</div>
    <div class="formulario">
        <form method="POST" action="processafrm.php?var=10" id="meuform">
            nome:<br />
            <input type="text" name="nome" size="50" /><br />
            Email:<br />
            <input type="text" name="email" size="50" /><br />
            <input type="submit" name="enviar" value="Enivar dados" />
        </form>
    </div>
    <div class="formulario">
        <form method="POST" action="processafrm.php?var=10" id="meuform2">
            nome:<br />
            <input type="text" name="nome" size="50" /><br />
            Email:<br />
            <input type="text" name="email" size="50" /><br />
            <input type="submit" name="enviar" value="Enivar dados" />
        </form>
    </div>
    <div class="formulario">
        <form method="POST" action="processafrm.php?var=10" id="meuform3">
            nome:<br />
            <input type="text" name="nome" size="50" /><br />
            Email:<br />
            <input type="text" name="email" size="50" /><br />
            <input type="submit" name="enviar" value="Enivar dados" />
        </form>
    </div>
    </body>
    </html>

3 answers

3

An interesting solution is to create a "generic" function that works for any form with any fields.

Example:

function enviaForm(seletor) {
    var form = $(seletor),
        campos = new Object();

    form.on('submit', function (e) {
        //bloqueia o envio do form, para tratarmos dele aqui dentro
        e.preventDefault();

        //recolhe todos os inputs, desde que não sejam do tipo submit
        $(this).children('input:not([type="submit"])').each(function (i, el) {
            campos[el.name] = el.value;
        });

        //Com os dados todos computados, você faria o AJAX aqui
        $.post('minha-url-post',campos,function(resposta){
            //...
        });

        //limpa o objeto campos para rodar novamente caso necessário
        campos = new Object();
    });
}

Example of how to call the function:

enviaForm('.minhas-forms');

To see you live: FIDDLE

What this code does is basically generate a Object() with all the data of a given form whenever you give Submit on it. With this data already in the object you can do anything, in your case, send via AJAX.


Note:

It is worth remembering that this type of generic sending by itself (as well as any client-side code) does not provide real security against malicious people. It is highly recommended (not to say mandatory) to validate the fields on the server side.

A good implementation would be to perform a validation in Javascript with friendly messages for the common user, and on the server side perform the validation against any attack, treating this request differently (such as recording in a log the date and IP of who made the request, etc.), since if the user arrived there with invalid data it was because he circumvented Javascript intentionally and most likely is attempting an invasion.

3


Use the pseudo-selector to select ID’s started with meuform (^=) or even only $('form').

    $(document).ready(function() {
        $(".resultado").hide();
        $("form[id^=meuform]").ajaxForm({      // ou somente $('form').ajaxForm({
            target: '.resultado',

The remaining problem to solve is:
how to point to the this within the Success function?

Here are two options:

- do not use this plugin

Using the jQuery .ajax() which has basically the same functionality, and in this case would have a syntax:

$(document).ready(function (e) {
    $('form').submit(function (e) {
        var self = $(this);
        e.preventDefault();
        var form_data = self.serialize();
        var form_url = self.attr("action");
        var form_method = self.attr("method").toUpperCase();
        var self = this;
        $.ajax({
            url: form_url,
            type: form_method,
            data: form_data,
            success: function (retorno) {
                $(".resultado").html(retorno);
                $(".resultado").show();
                self.resetForm();      // aqui é onde resolve o problema
            }
        });
    });
});

- find the this

If I remember correctly this plugin passes the form element as one of the parameters of the function. Log the reserved word arguments to see all function parameters success, I believe the 4th is the form.

        success: function (retorno) {
            console.log(arguments);
        }

If you find it, you can use it like this:

        success: function (retorno, status, xhr, form) {
            $(".resultado").html(retorno);
            $(".resultado").show();
            form.resetForm();      // ou talvez $(form) no caso do elemento não vir encapsulado
        }

If I am wrong in this room send pf the link to the documentation of this . ajaxForm

  • 1

    Code worked perfectly and completely solved the question I just made a small change to reset the form where it was self.resetForm(); it was like $(self). resetForm();

1

You can use the $.each, referencing each form with this:

$(document).ready(function() {

    $('form').each(function(){ //para cada form, execute as ações abaixo

           $(this).closest(".resultado").hide(); 
     //como você deve ter vários .closest, selecionamos o mais próximo do form atual

           targetSel = '#'+$(this).attr('id')+' .resultado';
     //criando um novo seletor de alvo, pois o anterior selecionava todos os .resultado da página

           $(this).ajaxForm({
                target: targetSel,
                success: function(retorno){

                     $(this).closest(".resultado").html(retorno);
                     $(this).closest(".resultado").show();
                     $(this).resetForm();
                }
            });
       });

});

Jquery each
Jquery Closest

Browser other questions tagged

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