Success message when registering in BD

Asked

Viewed 148 times

0

The script below worked with the older version of js and Bootstrap, but after I started using the latest it stopped... I use it to return the form message! If anyone can help me, I understand little of json and js...

// Quando carregado a página
$(function ($) {

// Quando enviado o formulário
$('#NovaEntrada').on('submit', function () {

    // Armazenando objetos em variáveis para utilizá-los posteriormente
    var formulario = $(this);
    var botao = $('#salvar');
    var mensagem = $('#mensagem');

    // Exibindo indicador de carregamento (Bootstrap)
    // Docs: http://getbootstrap.com/javascript/#buttons
    botao.button('loading');

    // Enviando formulário
    $(this).ajaxSubmit({

        // Definindo tipo de retorno do servidor
        dataType: 'json',

        // Se a requisição foi um sucesso
        success: function (retorno) {

            // Se cadastrado com sucesso
            if (retorno.sucesso) {
                // Definindo estilo da mensagem (sucesso)
                mensagem.attr('class', 'alert alert-success');

                // Limpando formulário
                formulario.resetForm();


            //recarrega a pagina
            setTimeout(function() {
                window.location.reload(1);
            }, 1000);
            }
            else {
                // Definindo estilo da mensagem (erro)
                mensagem.attr('class', 'alert alert-danger');
            }

            // Exibindo mensagem
            mensagem.html(retorno.mensagem);

            // Escondendo indicador de carregamento
            botao.button('reset');

        },

        // Se houver algum erro na requisição
        error: function () {

            // Definindo estilo da mensagem (erro)
            mensagem.attr('class', 'alert alert-danger');

            // Exibindo mensagem
            mensagem.html('Ops, algum erro foi encontrado!!!');

            // Escondendo indicador de carregamento
            botao.button('reset');
        }

    });

    // Retorna FALSE para que o formulário não seja enviado de forma convencional
    return false;

 });

 });

form

<form id="NovaEntrada" enctype="multipart/form-data" method="post" action="ajax/Cadastrar.php"> 
Obs.:Não adicionei os inputs para não ficar longo o codigo 
<input type="submit" id="salvar" class="btn btn-primary" value="Salvar" data-loading-text="Salvando..."/>
 <!---- exibe a mensagem do script -----> 
 <div id="mensagem"></div>
</form>

php return.

// Função que retorno um JSON com a propriedade sucesso e mensagem
function retorno($mensagem, $sucesso = false) 
{
// Criando vetor com a propriedades
$retorno = array();
$retorno['sucesso'] = $sucesso;
$retorno['mensagem'] = $mensagem;

// Convertendo para JSON e retornando
return json_encode($retorno);
}

ajax/Register.php

// Executando e exibindo resultado
echo ($stmt->execute()) ? retorno('Cadastrado com sucesso', true) :  retorno($stmt->errorInfo());
  • of the one echo() in the json_encode() and forehead to see

  • 1

    It returns the message right, the problem seems that the script does not receive the msg

  • 1

    echo result: {"success":true,"message":"Successfully registered"}

  • must be problem with equal nomenclature, vc has two mensagem in the code Jquery, tries to change one of them to see

1 answer

1

changed the variable name mensagem, which refers to the tag that will receive the message to campo_mensagem:

// Quando carregado a página
$(function ($) {

// Quando enviado o formulário
$('#NovaEntrada').on('submit', function () {

    // Armazenando objetos em variáveis para utilizá-los posteriormente
    var formulario = $(this);
    var botao = $('#salvar');
    var campo_mensagem = $('#mensagem');

    // Exibindo indicador de carregamento (Bootstrap)
    // Docs: http://getbootstrap.com/javascript/#buttons
    botao.button('loading');

    // Enviando formulário
    $.ajax({

        url:'destino.php',//url do arquivo que vai receber os dados
        // Definindo tipo de retorno do servidor
        dataType: 'json',

        // Se a requisição foi um sucesso
        success: function (retorno) {

            // Se cadastrado com sucesso
            if (retorno.sucesso) {
                // Definindo estilo da mensagem (sucesso)
                campo_mensagem.attr('class', 'alert alert-success');

                // Limpando formulário
                formulario.resetForm();


            //recarrega a pagina
            setTimeout(function() {
                window.location.reload(1);
            }, 1000);
            }
            else {
                // Definindo estilo da mensagem (erro)
                campo_mensagem.attr('class', 'alert alert-danger');
            }

            // Exibindo mensagem
            campo_mensagem.html(retorno.mensagem);

            // Escondendo indicador de carregamento
            botao.button('reset');

        },

        // Se houver algum erro na requisição
        error: function () {

            // Definindo estilo da mensagem (erro)
            campo_mensagem.attr('class', 'alert alert-danger');

            // Exibindo mensagem
            campo_mensagem.html('Ops, algum erro foi encontrado!!!');

            // Escondendo indicador de carregamento
            botao.button('reset');
        }

    });

    // Retorna FALSE para que o formulário não seja enviado de forma convencional
    return false;

 });

 });
  • 1

    Not yet a friend, in the browser console gave this error: Typeerror: $(...). ajaxSubmit is not a Function... I think it should be the function that is generating incompatibility, because with js version 2.3 works

  • yes, use $.ajax() only

  • edited answer

  • 1

    Already started working well brother, returned to msg Ops, some error was found, however error and in function... php code returns success

  • error function puts a parameter error:function(e){ and of the one console.log(e) to see what went wrong

Browser other questions tagged

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