Fabian
Fabian

Reputation: 561

Handling AJAX return values in SweetAlert2

I use a SweetAlert2 Popup with an AJAX request. Once the user clicks on submit I execute the request. In the PHP file I then make some validation on the submitted data and depending on the result I want to give a feedback in SweetAlert2 for the user as information.

Here is my SweetAlert2 Code:

$('#sweet-ajax').click(function () {
    swal({
        title: "Sure?", 
        text: "Clicking on validated sends the data to our tool.", 
        type: "warning",
        showCancelButton: true,
        closeOnConfirm: false,
        confirmButtonText: "Yes, submit!",
        cancelButtonText: "Cancel",
        showLoaderOnConfirm: true,
        confirmButtonClass: 'btn btn-success',
        cancelButtonClass: 'btn btn-danger m-l-10',
        preConfirm: function(givenData){
            return new Promise(function(resolve, reject) {
                setTimeout(function(){
                    //if statment only for test purposes filled with 2==1 
                    if(2 == 1){
                        swal("Oops", "Sorry something strange happend!", "error")
                    }else{
                        resolve()
                    }
                }, 2000)
            })
        },
        allowOutsideClick: false
    }).then(function(givenData){
        $.ajax({
                    type: "post",
                    url: "/assets/php/checkTool.php",
                    data: {registration: "success", amount: ammountInput, email: "[email protected]"},
                })
        swal({
                //only if the response from the AJAX is correct - but how?
                type: 'success',
                title: 'Correct!',
                html: 'All safe! Here is the answer from the tool: ' //need to get the return value of the AJAX request and append it here
            })
    }, function(dismiss) {

          if (dismiss === 'cancel') {
            swal(
              'Cancelled',
              'The action have been cancelled by the user :-)',
              'error'
            )
          }
      })

});

And the checkTool.php file:

<?php 
     $registration = $_POST['registration'];
     $ammountInput= $_POST['ammount'];
     $email= $_POST['email'];

     //only some demo things here. Implement it after the SweetAlert2 stuff works properly
     if ($registration == "success"){
         return response(json_encode(array("abc"=>'Success')));

     }else{
         return response(json_encode(array("abc"=>'Error')));

     }
?>

How can I now determinate what is the response from the AJAX request in the Javascript Code of SweetAlert2?

Is it possible to handle the AJAX response in SweetAlert2?

Upvotes: 1

Views: 10331

Answers (2)

Laszlo Sarvold
Laszlo Sarvold

Reputation: 963

In my experience what made it work, keeping in mind the use of showLoaderOnConfirm: true is doing the ajax call inside the preconfirm, and getting from the json response the elements I need as follows:

swal({
  title: "Sure?", 
  text: "Clicking on validated sends the data to our tool.", 
  type: "warning"
  showLoaderOnConfirm: true,
  preConfirm: function () {
    return new Promise(function (resolve) {
      $.ajax({
        type: "POST",
        contentType: "application/json; charset=UTF-8",
        data: JSON.stringify(objectToPost),
        url: "/assets/php/checkTool.php",
        dataType: 'json', // in ,my case the absence of this was the cause of failure
      })
      // in case of successfully understood ajax response
        .done(function (myAjaxJsonResponse) {
          console.log(myAjaxJsonResponse);
          swal(
            "My title!",
            "My response element is: " + myAjaxJsonResponse.selectedElement,
            "success"
          );
        })
        .fail(function (erordata) {
          console.log(erordata);
          swal('cancelled!', 'The action have been cancelled by the user :-)', 'error');
        })

    })
  },
})
  .catch(swal.noop)

The swal being invoked when clicking a button, on my scenario.I hope this helps someone, as it took me quite some time to make it work.

Upvotes: 2

taekwondoalex
taekwondoalex

Reputation: 386

Wrap your sweet alert inside the ajax .done(function(response){}) function

}).then(function(givenData){
        $.ajax({
                type: "post",
                url: "/assets/php/checkTool.php",
                data: {registration: "success", amount: ammountInput, email: "[email protected]"},
            }).done(function(response) {
                if(response['abc'] === 'Success') {
                    swal({
                        type: 'success',
                        title: 'Correct!',
                        html: 'All safe! Here is the answer from the tool: ' + response['answer'] 
                    })
                }
            });
        })
}, function(dismiss) {

Upvotes: 2

Related Questions