Problem with validation of various forms with ajax and php

Asked

Viewed 252 times

1

On my website I have several forms: Real Estate Filter Form, Contact Form, Contact Form and Contact Form.

Is there any way to recover all forms except the property filter form and send to different urls in ajax?

In the code below I am working only with a form.

$(document).ready(function(){
        //Forms
        var formMsg     = $('.load');
        var button      = $('#btnEnvia'); 
        var forms       = $('form');
        var has_error   = 0 ;
        var nome        = $("#nome").val();
        var msg         = $("#msg").val();
        var email       = $("#email").val();
        var telefone    = $("#telefone").val();
        var atpos       = email.indexOf("@");
        var dotpos      = email.lastIndexOf(".");

        var urlpost = 'tpl/form-contato.php';
        var urlpost2 = 'tpl/form-presidente.php';
        var urlpost3 = 'tpl/form-contato.php';

        formMsg.hide();
        button.attr("type", "submit");
        forms.submit(function(){
            formMsg.fadeOut("fast");
            return false;
        });

        function carregando(){
            formMsg.empty().html('<p><img src="img/load.gif" width="22">  Agurade enviando...</p>').fadeIn("fast");
        }

        function errosend(){
            formMsg.empty().html('<p class="danger">Erro inesperado, contate o administrador.</p>').fadeIn("fast");
        }

        //Genericas
        function errdados( mensagem ){
            formMsg.empty().html('<p class="bg-danger">'+mensagem+'</p>').fadeIn("fast");
        }
        function sucesso( mensagem ){
            formMsg.empty().html('<p class="success">'+mensagem+'</p>').fadeIn("fast");
        }

        $.ajaxSetup({
            url:        urlpost,
            type:       'POST',
            beforeSend: carregando,
            error:      errosend
        });


        var formContato = $('form[name="contato"]');

        formContato.submit(function(){
            var dados = $(this).serialize();
            var acao = "&acao=enviar"
            if ($("#nome").val().length == 0) {
                has_error = 1 ;
                $('#nome').css({
                    "background-color": "rgba(248, 116, 116, 0.52)"
            });
            }
            if($("#email").val().length == 0) {
                has_error = 1 ;
                $('#email').css({
                    "background-color": "rgba(248, 116, 116, 0.52)"
                });
            }
            if(atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= email.length) {
                has_error = 1 ;
                $('#email').css({
                    "background-color": "rgba(248, 116, 116, 0.52)"
                });
            }
            if($("#msg").val().length == 0) {
                has_error = 1 ;
                $('#msg').css({
                    "background-color": "rgba(248, 116, 116, 0.52)"
                });
            }
            if(has_error == 0 ) {
                $.ajax({
                    data: dados+acao,
                    success: function(resposta){
                        sucesso("Enviado com sucesso!");
                        $('#btnEnvia').val('ENVIADO!');
                         $('#btnEnvia').css({
                            "background-color": "#00E681"
                        });
                    }
                });
            }
        });
  • Do you want to do a function that is reused for all forms? Is that it? Or you want to send all forms when the user presses "send"?

  • You can pass on a input hidden by name forms[] informing in which form the submission will be executed and capturing the URL as a value: var urlpost = $('#form_execute').val(). And do a for in the element to run each url independently.

  • @Filipemoraes, would be more or less like this, retrieve only some forms treat the data in a generic way like Success, error and complete and if the fields are empty or not and send the action to different url.

1 answer

1

To Jquery 1.5+, you can ultilizar the object:

$.when($.ajax(), [...]).then(function(resultado){},[...]);

Example:

<input type="button" id="button" value="enviar" />

$('#button').click(function() {
    $.when(
        $.ajax({
            url: 'tpl/form-contato.php',
            success: function(data) {
                alert('Deu certo!')
            }
        }),
        $.ajax({
            url: 'tpl/form-presidente.php',
            success: function(data) {
                alert('Deu certo!')
            }
        }),
        $.ajax({
            url: 'tpl/form-contato.php',
            success: function(data) {
                alert('Deu certo!')
            }
        })
    ).then( function(){
        alert('Deu TUDO certo!');
    });
});

Thus, a single Deferred is passed to jQuery.when();

Source

  • Very cool this feature, but it sends the actions to all the urls at the same time, or it scrolls through the forms, identifies the form and sends it to the url I assign to it?

  • Exactly what you said last. See the documentation at "SOURCE".

Browser other questions tagged

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