Return php error using sweet alert

Hi i need to return a error using sweet alert, this is what I’ve done so far

Javascript code

      $('#emptytrash').click(function() {


      swal({
        title: "Sicuro di voler eliminare tutti i messaggi?",
        text: "I messaggi verranno eliminati in modo permanente e non potranno più essere recuperati!",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "Si, elimina tutti",
        cancelButtonClass: "btn btn-danger",
        cancelButtonText: "No, non procedere!",
        closeOnConfirm: false
    },
    function(){
        $.ajax({
          url: "delete_all.php",
          method: "POST",
          dataType: 'json'

          success: function(response) {

            swal('Deleted!', response.message, response.status);

        }

    });
    });

  });

this is my delete_all.php

if ($_SERVER["REQUEST_METHOD"] == "POST") {

	// Prelevo l'id dell'amministratore e lo passo ad una variabile
	$userid = $_SESSION['user_id'];

	$delete_inbox = mysqli_prepare($conn, "DELETE FROM user_inbox where user_inbox_user=? AND user_inbox_status = 'trash'"); 
	       mysqli_stmt_bind_param($delete_inbox, 'i', $userid);
	       mysqli_stmt_execute($delete_inbox);
	       mysqli_stmt_close($delete_inbox);

	 if ($delete_inbox) {

        $response['status']  = 'success';
 		$response['message'] = 'Product Deleted Successfully ...';

    } else {

        $response['status']  = 'error';
 		$response['message'] = 'Unable to delete product ...';
    }

    echo json_encode($response);

}

How can I report json messages for success or errors using sweet alert? Many thanks for your help

HI,

For me it’s easy to do like this in returning response.

In your server side.

if($delete_inbox)
 $msg = "success"
else
  $msg = "error";


return json_encode(['msg'=>$msg]);

Now in in your client side

 success: function(response) {
         if(response.msg === 'success'){
          //alert success
       }else{
          //alert error
      }
    }

Hi @jemz many thanks for your help. Can i also ask another question? Do i need to sanitize json output for security reasons?

You might actually just set an appropriate response code:

if ($_SERVER["REQUEST_METHOD"] === "DELETE") {
  if (!isset($_SESSION['user_id']) {
    // Not authorized
    http_response_code(403);
    die(); // ... or better return if inside a function
  }

  // etc...

  if (!$delete_inbox) {
    // Internal server error
    http_response_code(500);
  }
}

And if that code is an error code (4xx or 5xx), the error() callback will be called:

$.ajax({
  url: 'delete_all.php',
  method: 'DELETE',
  success (response) {
    // ...
  },
  error (response) {
    // ...
  }
})

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.