Search code examples
phpsqlajaxmysqlisweetalert2

How to use AJAX in Sweet Alert


I want the user to confirm if he wants to update his image. I know that I can't use sql with php inside javascript and I have tried on so many ways, but I couldn't make it work, no errors were shown, nothing happened. This code updates the image without even pressing the button. I don't have knowledge on AJAX, so it would be great an example of my code and what it means.

    <script>
function rmv_foto() {
event.preventDefault();
  swal({
    title: 'Remover foto de perfil?',
    text: "Essa ação não poderá ser desfeita.",
    type: 'warning',
    showCancelButton: true,
    confirmButtonColor: '#3085d6',
    cancelButtonColor: '#F54400',
    confirmButtonText: 'Sim, pode remover!'
    }).then((result) => {
      if (result.value) {
        var rmv_foto="<?php
        $delete = "UPDATE esc_usuarios_fotos SET img_local = 'images/user.png' WHERE img_usu_codigo = '" . $_SESSION['codigo'] . "'"; 
        mysqli_query($conexao, $delete) 
        ?>";
        swal(
          'Foto Removida!',
          'Sua foto de perfil foi removida com sucesso.',
          'success'
        ).then(function() {
          location.href = 'perfil.php';
      });
      }
    })
}
</script>

How can I properly use ajax to do the update just when user confirms?


Solution

  • With some good research, working like a charm!

        function rmv_foto(){
    swal({
         title: 'Remover foto de perfil?',
          showCancelButton: true,
          confirmButtonText: 'Sim, pode remover!',
          cancelButtonText: 'Cancelar',
          text: 'Essa ação não poderá ser desfeita.',
          type: 'warning',
          confirmButtonColor: '#F54400',
          showLoaderOnConfirm: true,
          preConfirm: ()=>{
                $.ajax({
                    url: 'rmv.php',
                    method: 'POST',
                    data:{},
                    success: function(resp)
                          {
                            if(resp) return "ok",
                              swal(
                                'Foto Removida!',
                                'Sua foto de perfil foi removida com sucesso.',
                                'success'
                              ).then(function() {
                                location.href = 'perfil.php';
                              });
                          }
                })
              }
        })
    };