Sending ajax with notification

Asked

Viewed 386 times

0

Good morning guys, I’m having a problem in a test, when registering I return a notification, only that the notification gives only one message, I mean, message of success, I can’t get by an error message, like an if Else, and I want to know if it’s not a gambiarra what I did, I don’t know much about ajax and jquery, but ta working kkk, I wanted to know if it was the best option! because I will follow with this code for Insert, update and delete!

    <form id="cadastrarUsuario" action="" method="POST" class="form-group">
                Nome: <br>
                <input required type="text" name ="nome_usuario"><br>
                Sobrenome: <br>
                <input required type="text" name ="sobrenome_usuario"><br>
                <hr>
                <button type="submit">Enviar</button>
            </form>

    <script src="js/classie.js"></script>
    <script src="js/notificationFx.js"></script>
    <script type="text/javascript">

$(function(){

    $('#cadastrarUsuario').submit(function(event){
        event.preventDefault();
        var formDados = new FormData($(this)[0]);

        $.ajax({
            url:'addUsuario.php',
            type:'POST',
            data:formDados,
            cache:false,
            contentType:false,
            processData:false,
            success:function(data){
  if(data == "salvo"){
    $('#cadastrarUsuario').trigger("reset");
                            var notification = new NotificationFx({
                            wrapper : document.body,
                            message : '<p>Deu Certo</p>',
                            layout : 'growl',
                            effect : 'scale',
                            type : 'notice', // notice, warning, error or success
                            ttl : 6000,
                            onClose : function() { return false; },
                            onOpen : function() { return false; }
                            });
                            notification.show();
  }
  else{
    $('#cadastrarUsuario').trigger("reset");
                            var notification = new NotificationFx({
                            wrapper : document.body,
                            message : '<p>Deu Erro</p>',
                            layout : 'growl',
                            effect : 'scale',
                            type : 'notice', // notice, warning, error or success
                            ttl : 6000,
                            onClose : function() { return false; },
                            onOpen : function() { return false; }
                            });
                            notification.show();
  }
},
            dataType:'html'
        });
        return false;
    });
});

</script>

Php

 <?php 
$nome = $_POST['nome_usuario'];
$sobrenome = $_POST['sobrenome_usuario'];
 try{
    $mysqli = new mysqli('localhost','root','@0202','ajax');
    $sql = "INSERT INTO `usuario` (`idusuario`,`nomeusuario`,`sobreusuario`) VALUES (NULL,'{$nome}','{$sobrenome}')";

    $mysqli->query($sql);
    echo "salvo";
  }
  catch(Exception $e){
    $retorno = "Erro ao salvar. ".$e->getMessage();
    echo $retorno;
  }
?>

1 answer

2


PHP has no Return, that’s the problem. In ajax, in line:

success:function(data){

"data" will be what you have returned from PHP. For example, let’s say you want to know if the query was successfully entered. You can put the code inside a Try/catch block. It could be like this:

PHP:

<?php 
  $nome = $_POST['nome_usuario'];
  $sobrenome = $_POST['sobrenome_usuario'];

    $mysqli = new mysqli('localhost','root','@0202','ajax');
    $sql = "INSERT INTO `usuario` (`idusuario`,`nomeusuario`,`sobreusuario`) VALUES (NULL,'{$nome}','{$sobrenome}')";

    if($mysqli->query($sql) === false){
      echo mysqli_connect_error();
    }
    else{
    echo "salvo";
    }
?>

Details about mysqli_connect_error() here.

And in ajax, within the Success function, you do something like:

success:function(data){
  if(data == "salvo"){
    //código em caso de sucesso
  }
  else{
    alert(data);
    //ou talvez
    alert("erro ao salvar");
  }
}
  • Not working with the notification!

  • Give details about the error.

  • I updated my question, I did as you showed, when click save it returns me (It worked) in the notification, now when I error the query purposely returns me (It worked) only it does not register in the bank obviously but it was for it returns me in the notification (Gave Error).

  • I edited my answer. It was my mistake: mysqli->query does not throw in Exception.

  • was great, worked perfectly, but stopped working when I put php Mailer, to send an email before the query, I don’t know if it’s taking too long to send the email or something I just know about the error!

  • I’m glad it worked. About Mailer, I think it’s better to ask another question, because it would already be another theme. I suggest you research first before you ask, maybe there’s a solution out there.

Show 1 more comment

Browser other questions tagged

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