A single script for N forms

3

I need to know what the correct way for when I submit a form a single script to resolve, the code below only works for your self to create a script for each form. How do I resolve this?

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><scripttype="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>
    
asked by anonymous 04.06.2014 / 02:42

3 answers

3

Use the pseudo-selector to select IDs starting with meuform ( ^= ) or even only $('form') .

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

The problem that remains to be solved is:
how to point to this within function success?

Here you have two options:

- do not use this plugin

Use jQuery .ajax() which basically has 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 this

If I remember correctly this plugin passes the form element as one of the parameters of the function. Make a log of the reserved word arguments to see all the parameters of the success function, I think 4th is 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 fourth parameter please send the link to the documentation for that .ajaxForm

    
04.06.2014 / 07:01
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 live: FIDDLE

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

Note:

Please note that this type of generic delivery 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) that you do a validation of 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 some 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 got there with invalid data it was because he intentionally joked JavaScript and is most likely attempting an invasion.     

04.06.2014 / 04:23
1

You can use $.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

    
04.06.2014 / 02:58