Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

Fagner Campos

Função não sendo executada dentro de submitHandler (jQuery Validate)

Recommended Posts

Boa tarde galera, tudo bem?

 

Tenho um formulario sendo validado com jQuery Validate.

 

Estou tendo problemas quando o script entra dentro do submitHandler, pois quero que seja executado uma função dentro dele, mas isso não está acontecendo.

 

Vejam o trecho em questão:

submitHandler: function(form) {
                var dados = $(form).serialize();
                $.ajax({
                    type: "POST",
                    url: "inc/processa.php",
                    data: dados,
                    success: function(data)
                    {
                        $("#name").val("");
                        $("#email").val("");
                        $("#comment").val("");
                        $("#security_question").val("");
                        $("#guestbook-notification").html('<p class="successmsg">Recado gravado com sucesso! Obrigado!</p>');
                        $("#recados").html(data);
                        setFormAutoValue('.validacao');
                    }
                });
                
                return false;
            }

A função setFormAutoValue(); não está sendo executada. Ela é responsável por gerar uma nova "questão de segurança", um "captcha"...

 

Existe alguma forma em especial que precisa ser feito para chamar ela?

 

Compartilhar este post


Link para o post
Compartilhar em outros sites

Não, não existe nenhuma forma especial.

 

Pq vc acha que ela não está sendo executada ?

Compartilhar este post


Link para o post
Compartilhar em outros sites

Não, não existe nenhuma forma especial.

 

Pq você acha que ela não está sendo executada ?

 

Sinceramente não sei. Ela não é executada nem a pau.

 

Ela está funcionando normalmente, pois ela é executada uma vez assim que a página é carregada e toda a vez que é necessário "atualizar somente o captcha". Mas quando é chamada dentro do submitHandler simplesmente não funciona.

Se eu colocar a chamada da função pra ser executada primeiro, o resto não funciona. Não dá pra entender porque, pois está sendo chamada como nos outros lugares.

 

Alguma idéia?

 

Veja a sintaxe da função

function setFormAutoValue(formulario) {

            var $form2 = $(formulario);
            

            $.ajax({
                'url': 'action.php',
                'data': {
                    get_auto_value: $form2.attr("id")
                },
                'type': "POST",
                'dataType': 'json',
            }).done(function(response) {

                if (typeof response.data != 'undefined') {
                    $form2.find('.auto-safe span').text(unescape(response.data));
                }

            });

        }

Compartilhar este post


Link para o post
Compartilhar em outros sites

-> O formulário possui a classe .validacao ?

-> O que aparece no console de erros ? Ctrl + Shift + J ?

-> Pq vc tem que chamar ela depois que o form é enviado ?

Compartilhar este post


Link para o post
Compartilhar em outros sites

-> O formulário possui a classe .validacao ?

-> O que aparece no console de erros ? Ctrl + Shift + J ?

-> Pq você tem que chamar ela depois que o form é enviado ?

 

1. Sim, possui a classe.

 

2. aparece isso:

GET 
https://mts0.googleapis.com/vt [HTTP/1.1 200 OK 2609ms]
GET 
https://mts0.googleapis.com/vt [HTTP/1.1 200 OK 2593ms]
ReferenceError: gBrowser is not defined about:blank:313:6
This site makes use of a SHA-1 Certificate; it's recommended you use certificates with signature algorithms that use hash functions stronger than SHA-1.[Learn More] js
NS_ERROR_FAILURE: Component returned failure code: 0x80004005 (NS_ERROR_FAILURE) [nsITaskbarTabPreview.invalidate] WindowsPreviewPerTab.jsm:406:0
This site makes use of a SHA-1 Certificate; it's recommended you use certificates with signature algorithms that use hash functions stronger than SHA-1.[Learn More] main.js
This site makes use of a SHA-1 Certificate; it's recommended you use certificates with signature algorithms that use hash functions stronger than SHA-1.[Learn More] 71737050
This site makes use of a SHA-1 Certificate; it's recommended you use certificates with signature algorithms that use hash functions stronger than SHA-1.[Learn More] recent
This site makes use of a SHA-1 Certificate; it's recommended you use certificates with signature algorithms that use hash functions stronger than SHA-1.[Learn More] __utm.gif
This site makes use of a SHA-1 Certificate; it's recommended you use certificates with signature algorithms that use hash functions stronger than SHA-1.[Learn More] 924653_915286181861936_1262355291_n.jpg
Use of getPreventDefault() is deprecated.  Use defaultPrevented instead. jquery.min.js:3:0
Error: Exposing privileged or cross-origin callable is prohibited <unknown>
This site makes use of a SHA-1 Certificate; it's recommended you use certificates with signature algorithms that use hash functions stronger than SHA-1.[Learn More] openhand_8_8.cur
This site makes use of a SHA-1 Certificate; it's recommended you use certificates with signature algorithms that use hash functions stronger than SHA-1.[Learn More] ViewportInfoService.GetViewportInfo
This site makes use of a SHA-1 Certificate; it's recommended you use certificates with signature algorithms that use hash functions stronger than SHA-1.[Learn More] transparent.png
This site makes use of a SHA-1 Certificate; it's recommended you use certificates with signature algorithms that use hash functions stronger than SHA-1.[Learn More] gen_204
This site makes use of a SHA-1 Certificate; it's recommended you use certificates with signature algorithms that use hash functions stronger than SHA-1.[Learn More] google_white2.png
This site makes use of a SHA-1 Certificate; it's recommended you use certificates with signature algorithms that use hash functions stronger than SHA-1.[Learn More] mapcnt6.png
ReferenceError: gBrowser is not defined about:blank:313:6
This site makes use of a SHA-1 Certificate; it's recommended you use certificates with signature algorithms that use hash functions stronger than SHA-1.[Learn More] AuthenticationService.Authenticate
GET 
https://mts0.googleapis.com/vt [HTTP/1.1 200 OK 2562ms]
GET 
https://mts1.googleapis.com/vt [HTTP/1.1 200 OK 1094ms]
GET 
https://mts1.googleapis.com/vt [HTTP/1.1 200 OK 1643ms]
GET 
https://mts1.googleapis.com/vt [HTTP/1.1 200 OK 2405ms]
GET 
https://mts1.googleapis.com/vt [HTTP/1.1 200 OK 1658ms]
GET 
https://mts1.googleapis.com/vt [HTTP/1.1 200 OK 2003ms]
GET 
https://mts1.googleapis.com/vt [HTTP/1.1 200 OK 2265ms]
GET 
https://mts0.googleapis.com/vt [HTTP/1.1 200 OK 2312ms]
GET 
https://mts0.googleapis.com/vt [HTTP/1.1 200 OK 2578ms]
GET 
https://mts0.googleapis.com/vt [HTTP/1.1 200 OK 2578ms]
This site makes use of a SHA-1 Certificate; it's recommended you use certificates with signature algorithms that use hash functions stronger than SHA-1.[Learn More] cb_scout2.png
GET 
https://mts0.googleapis.com/vt [HTTP/1.1 200 OK 2515ms]
GET 
https://mts0.googleapis.com/vt [HTTP/1.1 200 OK 2328ms]
GET 
https://mts0.googleapis.com/vt [HTTP/1.1 200 OK 2516ms]
This site makes use of a SHA-1 Certificate; it's recommended you use certificates with signature algorithms that use hash functions stronger than SHA-1.[Learn More] imgs8.png
This site makes use of a SHA-1 Certificate; it's recommended you use certificates with signature algorithms that use hash functions stronger than SHA-1.[Learn More] vt
This site makes use of a SHA-1 Certificate; it's recommended you use certificates with signature algorithms that use hash functions stronger than SHA-1.[Learn More] vt
This site makes use of a SHA-1 Certificate; it's recommended you use certificates with signature algorithms that use hash functions stronger than SHA-1.[Learn More] vt
This site makes use of a SHA-1 Certificate; it's recommended you use certificates with signature algorithms that use hash functions stronger than SHA-1.[Learn More] vt
This site makes use of a SHA-1 Certificate; it's recommended you use certificates with signature algorithms that use hash functions stronger than SHA-1.[Learn More] vt
This site makes use of a SHA-1 Certificate; it's recommended you use certificates with signature algorithms that use hash functions stronger than SHA-1.[Learn More] vt
This site makes use of a SHA-1 Certificate; it's recommended you use certificates with signature algorithms that use hash functions stronger than SHA-1.[Learn More] vt
This site makes use of a SHA-1 Certificate; it's recommended you use certificates with signature algorithms that use hash functions stronger than SHA-1.[Learn More] vt
This site makes use of a SHA-1 Certificate; it's recommended you use certificates with signature algorithms that use hash functions stronger than SHA-1.[Learn More] csi
This site makes use of a SHA-1 Certificate; it's recommended you use certificates with signature algorithms that use hash functions stronger than SHA-1.[Learn More] vt
This site makes use of a SHA-1 Certificate; it's recommended you use certificates with signature algorithms that use hash functions stronger than SHA-1.[Learn More] vt
This site makes use of a SHA-1 Certificate; it's recommended you use certificates with signature algorithms that use hash functions stronger than SHA-1.[Learn More] vt
This site makes use of a SHA-1 Certificate; it's recommended you use certificates with signature algorithms that use hash functions stronger than SHA-1.[Learn More] vt
This site makes use of a SHA-1 Certificate; it's recommended you use certificates with signature algorithms that use hash functions stronger than SHA-1.[Learn More] vt
This site makes use of a SHA-1 Certificate; it's recommended you use certificates with signature algorithms that use hash functions stronger than SHA-1.[Learn More] vt
This site makes use of a SHA-1 Certificate; it's recommended you use certificates with signature algorithms that use hash functions stronger than SHA-1.[Learn More] vt
This site makes use of a SHA-1 Certificate; it's recommended you use certificates with signature algorithms that use hash functions stronger than SHA-1.[Learn More] vt
This site makes use of a SHA-1 Certificate; it's recommended you use certificates with signature algorithms that use hash functions stronger than SHA-1.[Learn More] vt
This site makes use of a SHA-1 Certificate; it's recommended you use certificates with signature algorithms that use hash functions stronger than SHA-1.[Learn More] vt
This site makes use of a SHA-1 Certificate; it's recommended you use certificates with signature algorithms that use hash functions stronger than SHA-1.[Learn More] vt
This site makes use of a SHA-1 Certificate; it's recommended you use certificates with signature algorithms that use hash functions stronger than SHA-1.[Learn More] vt
This site makes use of a SHA-1 Certificate; it's recommended you use certificates with signature algorithms that use hash functions stronger than SHA-1.[Learn More] vt
GET 
https://csi.gstatic.com/csi [HTTP/1.1 204 No Content 500ms]
This site makes use of a SHA-1 Certificate; it's recommended you use certificates with signature algorithms that use hash functions stronger than SHA-1.[Learn More] csi
GET 
https://maps.googleapis.com/maps/api/js/QuotaService.RecordEvent [HTTP/1.1 200 OK 297ms]
This site makes use of a SHA-1 Certificate; it's recommended you use certificates with signature algorithms that use hash functions stronger than SHA-1.[Learn More] QuotaService.RecordEvent
POST 
https://safebrowsing.google.com/safebrowsing/downloads [HTTP/1.1 200 OK 1127ms]
This site makes use of a SHA-1 Certificate; it's recommended you use certificates with signature algorithms that use hash functions stronger than SHA-1.[Learn More] downloads
GET 
https://safebrowsing-cache.google.com/safebrowsing/rd/ChVnb29nLWJhZGJpbnVybC1zaGF2YXI4AEACSgwIARCQrwMYka8DIAFKDAgAEIehBBiJoQQgAQ [HTTP/1.1 200 OK 828ms]
This site makes use of a SHA-1 Certificate; it's recommended you use certificates with signature algorithms that use hash functions stronger than SHA-1.[Learn More] ChVnb29nLWJhZGJpbnVybC1zaGF2YXI4AEACSgwIARCQrwMYka8DIAFKDAgAEIehBBiJoQQgAQ
GET 
https://safebrowsing-cache.google.com/safebrowsing/rd/ChNnb29nLW1hbHdhcmUtc2hhdmFyOABAAkoMCAEQyc0LGM7NCyABSgwIABDBjgwYxo4MIAE [HTTP/1.1 200 OK 156ms]
This site makes use of a SHA-1 Certificate; it's recommended you use certificates with signature algorithms that use hash functions stronger than SHA-1.[Learn More] ChNnb29nLW1hbHdhcmUtc2hhdmFyOABAAkoMCAEQyc0LGM7NCyABSgwIABDBjgwYxo4MIAE
GET 
https://safebrowsing-cache.google.com/safebrowsing/rd/ChFnb29nLXBoaXNoLXNoYXZhcjgAQAJKDAgBEOTZDRjn2Q0gAUoMCAAQ8MkYGPTJGCAB [HTTP/1.1 200 OK 188ms]
This site makes use of a SHA-1 Certificate; it's recommended you use certificates with signature algorithms that use hash functions stronger than SHA-1.[Learn More] ChFnb29nLXBoaXNoLXNoYXZhcjgAQAJKDAgBEOTZDRjn2Q0gAUoMCAAQ8MkYGPTJGCAB
GET 
XHR 
http://localhost:801/jeff_sol/inc/checkQuestion.php [HTTP/1.1 200 OK 16ms]
POST 
XHR 
http://localhost:801/jeff_sol/inc/processa.php

3. É chamado para gerar uma nova "questão de segurança" para gravar um novo recado.

Compartilhar este post


Link para o post
Compartilhar em outros sites

  • Conteúdo Similar

    • Por luiz monteiro
      Olá. Tenho 3 formulários em uma mesma pagina, onde cada um tem 1 input type text.
      O que preciso é recuperar o nome desses inputs e o valor correspondente ao formulário submetido.
      =============
      form name="formulario1" id="formulario1"
      input type="text" name="nome1" value="valor1" /form
      form name="formulario2" id="formulario2"
      input type="text" name="nome2" value="valor2" /form
      form name="formulario3" id="formulario3"
      input type="text" name="nome3" value="valor3" /form
      =============
      ..........
      var formulario_submetido = document.getElementById("formulario1"); formulario_submetido.addEventListener('submit', function(e) { e.preventDefault(); //tentei console.log(document.querySelectorAll('#'+this.id + ' input').name); //tentei var formula = new FormData(formulario_submetido); console.log(formula.input['type=text'].name); //tentei console.log(formula.get(input['type=text']).name); ..........
        no console.log(e), ele está nessa hierarquia   form -> srcElement -> input -> attributes -> name 
      Como recupero o valor do name dele e o valor do value?
       
      Agradeço desde já.
    • Por juniormatrix
      Olá
       
      Achei esse script aqui no fórum mesmo:
       
      $.validator.addMethod( "customEmail", function (value, element) { return this.optional(element) || /^[\w-\.]+@fulano\.com\.br$/i.test(value); }, "Por favor, insira um e-mail válido com o domínio @fulano.com.br" ); $("#formulario").validate({ ignore: ".ignore", rules: { empresa: { required: true }, nome: { required: true }, contato: { required: true }, celular: { required: true }, email: { required: true, email: true, customEmail: true }, }, }); Testei e funcionou perfeitamente, mas gostaria que liberasse mais e-mails válidos, ao invés de apenas um.

      Tem como fazer? 
       
      Se alguém puder ajudar, fico muito grato.
    • Por ment0r
      Boa noite pessoal, tudo bem?
       
      Estou desenvolvendo um sistema simples com exibição de formulário via modal. Uma vez cadastrado o serviço (tabela possui apenas dois campos, id e nome), eles são exibidos numa tabela com um ícone que permite a alteração do nome.

       
      Eu clico no ícone e é chamado um modal que é gerado via ajax (pois são vários registros).
       

       
      Nesse modal é mostrado o serviço e uma vez alterado, o botão Salvar chama uma função que atualiza a tabela servico, concluindo a tarefa. Fiz o mesmo processo pra cadastrar o serviço, com a diferença de que o modal está presente na mesma página, ou seja, não é chamado via ajax.
       
      Eis os códigos:
      <a href="#" onclick="modalUpdate(<?= trim($array['id']) ?>)"> <i class='bx bx-edit'></i> </a> // Trecho onde eu chamo a função modalUpdate. Função btAltServico click:
      $('#btAltServico').click(function() { var inpnome = $('#nome'); var inpid = $('#id'); if (inpnome.val() == '') { swal("Atenção", "Por favor, preencha os campos obrigatórios", "warning"); if (inpnome.val() == '') { inpnome.css("border","2px solid #f94545"); } else { inpnome.css("border",""); } alert(inpnome); alert(inpid); } else { $.ajax({ url: '../inc/ajax/altServico.php', type: 'post', dataType: 'json', // pode ser html data: { nome : inpnome.val(), id : inpid.val() }, success: function(resposta){ if (resposta == 1) { inpnome.val(""); inpnome.css("border",""); swal("Sucesso", "Serviço alterado", "success"); } else { if (resposta == 0) { swal("Erro", "Serviço não alterado. Log de erro gerado.", "error"); } else { swal("Atenção", "Serviço já cadastrado", "warning"); } } } }) } });  
      E modalUpdate.php :
       
      <?php /* * altServico.php * * Script responsável pelo update de serviços na tabela servico * * Função chamada pelo arquivo ajax.js */ //if ($_POST) { require'../conn.php'; require'../../class/class.geral.php'; $geral = new Geral(); $nome = $_POST['nome']; $id = $_POST['nome']; $ativo = 1; // Verifica se o servico já foi cadastrado $sqlVer = "select nome from algo68_db_cliente.servico where nome = '".$nome."' and id <> ".$id.""; $queryVer = mysqli_query($conn, $sqlVer); $resultVer = mysqli_num_rows($queryVer); if ($resultVer > 0) { echo json_encode(2); // servico já cadastrado } else { // Update do servico $sql = "update algo68_db_cliente.servico set nome = '".$nome."', ativo = ".$ativo." where id = ".$id; $query = mysqli_query($conn, $sql); $result = mysqli_affected_rows($conn); if ($result > 0) { echo json_encode(1); // alterou o servico } else { $geral->logErro(date('d/m/Y|H:i:s'), @$_SERVER[REQUEST_URI], 'AlterarServico', mysqli_error($conn)); echo json_encode(0); // não alterou o servico } } //} ?> O problema é que quando clico no botão Salvar, não acontece nada - se eu colocar um alert qualquer na função click, só pra saber se está chegando, também não da nada. E está da mesma forma que o cadastro de serviço, que funciona perfeitamente.

      Bom, é isso pessoal, tentei ser o mais breve e especifico possível. Qualquer ajuda é bem vinda, obrigado a todos, desde já.
    • Por Danilo - Jesus voltará!
      Olá pessoal, tenho uma div a qual através de um select categorias eu trago dados de empresas do banco, aí preciso clicar nas listagens das empresas e pegar o ID quando clica no checkbox e gravar pelo ajax novamente na session feita no arquivo php tipo um carrinho de compras, que essa parte já tenho... só não to conseguindo pegar os ids gerados dinamicamente no retorno feito do ajax, eles aparecem com F12 ao inspecionar, mas não aceita eu clicar para pegar o ID, acho que é algo de DOM, mas não to sabendo fazer... alguém aí saberia me ajudar como pegar esses ids ao clicar, já que eles vem dinamicamente?
       
      obrigado
    • Por Alessandro Bodão
      Salve galerinha, passando pra mostrar pra vocês o novo projeto de marca que a Jatobá Estúdio desenvolveu, espero que gostem.   https://www.behance.net/gallery/166555627/Fernanda-Pinheiro-Nutricionista-Esportiva
×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.