0

I'm having some trouble getting the errors from a php script called with Ajax. I've got an ajax which is directing to a suppression script.
Here's my Js :

$('.js-delete-link').click(function (e) {
    e.preventDefault();
    let id = $(this).closest('tr').find('.id').text();
    if (confirm('Voulez-vous vraiment supprimer le message ?')) {
        let href = $(e.currentTarget).attr('href');
        $.ajax({
            url:href,
            type:'post',
            success:function(data){
                let msgJson = JSON.parse(data);                  
                bootstrapNotify(msgJson.msg,msgJson.type);
            },
        })
    }
});

and here's my php script where i'm actually deleting the items.

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

if (isset($_GET['id'])) {

    $id = FILTER_INPUT(INPUT_GET, 'id', FILTER_VALIDATE_INT);
    if ($id === false) {
        $arr = array("msg" => "Id incorrect ou non spécifié", "type" => 'danger');
    } else {
        if ($messageModelDb->delete($id)) {
            $arr = array("msg" => "Le ou les messages ont été supprimés", "type" => 'success');
        } else {
            $arr = array("msg" => "Le message n'existe pas !", "type" => 'danger');
        }
    }
}

echo json_encode($arr);

} else {
    $_SESSION['error'] = "Vous n'êtes pas autorisé.";
    redirect('liste-messages');
}

In my php i try to catch any error which could occur during the query and if it happens i pass a message according to the error.
However, no matter what i always get a success message even if the id does not exist.
Sorry if this may seem totally obvious but i'm new to all this and i'm kind of stuck here!
Thank you for your help !

2
  • server side redirect will not redirect the browser page while doing an ajax call Commented Oct 21, 2017 at 12:35
  • Thank you i did not realize that Commented Oct 21, 2017 at 12:44

2 Answers 2

1

if isset($_GET['id']) is false, nothing will happen because you should put the else statement like this:

<?php

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_GET['id'])) {

        $id = FILTER_INPUT(INPUT_GET, 'id', FILTER_VALIDATE_INT);
        if (!$id) {
            $arr = array("msg" => "Id incorrect ou non spécifié", "type" => 'danger');
        } else {
            if ($messageModelDb->delete($id)) {
                $arr = array("msg" => "Le ou les messages ont été supprimés", "type" => 'success');
            } else {
                $arr = array("msg" => "Le message n'existe pas !", "type" => 'danger');
            }
        }
    } else {
        $arr = array("msg" => "ID is not set", "type" => 'danger');
    }
} else {
    $arr = array("msg" => "Invalid request method", "type" => 'danger');
}

echo json_encode($arr);

Then in the Javascript file, you can add an error callback:

success: function(){  
    ... 
},
error: function(XMLHttpRequest, textStatus, errorThrown) { 
    alert("Status: " + textStatus + " - Error: " + errorThrown); 
} 
Sign up to request clarification or add additional context in comments.

4 Comments

Ok that did it but then i've got to handle the errors in the ajax callback right ? not in the php script ?
Ok thank you so much ! One more thing though, when i try and put a wrong id in my link i still get a answer as if the item existed and i don't really understand why ?
This is also true if the id is empty
I editted my anwser to complete the PHP code. I tested it and it works, Assuming there is nothing wrong with $messageModelDb->delete($id).
0

AFAIK, the FILTER_INPUT could return NULL too, so $id === false will be false in this case. Try to use if(!$id) instead, if you sure that your $id could not be 0

3 Comments

If $id = NULL, its still false: php.net/manual/en/types.comparisons.php. I think it's best to do if(!isset($id) && $id !== "") here
@jeroene wait... if(!$id) will be true in both cases, when $id is null and when $id is false, so we can use it so to test $id, no?
@AlexandrX Ah sorry, you're right.. Only note that if $id is 0 or "0", it will be false. Since I guess we can assume that $id will never be 0, !$id should be good.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.