0

I would like to use a return variable from my PHP file to display a custom message of possible errors in SweetAlert. It is possible?

enter image description here

File PHP:

if ($a > $b) {
    echo "true";
    $msg = "First personalised message";
    exit;
} elseif ($a == $b) {
    echo "true";
    $msg = "Second personalised message";
    exit;
} else {
    echo "false";
    exit;
}

JAVASCRIPT CODE:

$(document).ready(function ($) {
    $('#moving_send_toners').on('submit',function(e) {
        if ($("#moving_send_toners").valid()) {
            $.ajax({
                url:'action_send_toners.php',
                data:$(this).serialize(),
                type:'POST',
                success:function(data){
                    if (data == 'false') {
                        console.log(data);
                        swal('Sucesso!', 'Ação realizada.', 'success');
                        $('#moving_send_toners')[0].reset();
                    }
                    if (data == 'true') {
                        swal('Ops!', "Toner não pode ser enviado :(", "error");
                    }
                },
                error:function(data){
                    swal("ERRO!", data.msg, "error");
                }
            });
        }
        e.preventDefault();
    })
});
Don't Panic
  • 13,965
  • 5
  • 32
  • 51
  • Does this answer your question? [Returning JSON from PHP to JavaScript?](https://stackoverflow.com/questions/682260/returning-json-from-php-to-javascript) – Martin Zeitler Mar 09 '22 at 23:18

1 Answers1

0

From the image you included, it looks like you want to use the response from your PHP in the .error() callback, not the .success() callback (as is the usual way back-end responses are used).

The .error() callback is fired when the request fails. From the docs:

error.
A function to be called if the request fails. The function receives three arguments: ... Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error."

So you can see the type of error that this callback handles are things like 404 errors, 500 server errors, network timeouts, etc. For that kind of error, your PHP did not run. This handler only ever fires when your PHP did not run, so there is no way to pass a message to it from your PHP.

If you actually want to use the message in your success handler, here's how you would do that. First in your PHP:

if ($a > $b) {
    $response = [
        'status'    => true,
        'message'   => 'First personalised message'
    ];
    
} elseif ($a == $b) {
    $response = [
        'status'    => true,
        'message'   => 'Second personalised message'
    ];

} else {
    $response = [
        'status'    => false,
        'message'   => ':-('
    ];
}

header('Content-Type: application/json');
echo json_encode($response);
exit;

Then use that returned JSON in your Javascript:

success: function(response) {
    console.dir(response);
    
    if (response.status === false) {
        swal('Sucesso!', response.message, 'success');
        $('#moving_send_toners')[0].reset();
        
    } else {
        swal('Ops!', response.message, "error");
        
    }
},
Don't Panic
  • 13,965
  • 5
  • 32
  • 51