user10989117
user10989117

Reputation:

Ajax alway in success when it should be error

I do an Ajax for delete on a file, but when I do so my script always goes in success when it shoudl enter error ... I don't understand what happens, with onlt php/html is echo me a warning but with ajax t tell me success :(

If it can be usefull information : I use MVC architecture, my database connexion is PDO and in a class manager, my request are also in a manager, everything is working if I use php, it goes wrong with Ajax.

Here my jQuery attempt 1st way :

 $('.ButtonDelete').on('click', function() {
        let id= $(this).val();
        let code=$('#code'+id).val();
        let confimation = confirm("Are you sure you want to delete " + code + "?");
        if (confimation==true){
            req = $.ajax({
                url: "menu.php?Option=deleteIgr",
                type : 'POST',
                data : { code : code },
                error(xhr,status,error) {
                    console.error("An error occurred: " + status, error);
                },
                success(result,status,xhr) {
                    var error = (typeof(result.error) !='undefined' && result.error!=null) ? result.error : null;
                    if(error){
                    alert("this element cannot be delete" + error);
                    }
                    else {
                    console.log("Deleted with success");
                    $('#row'+id).remove();
                    }
                }
            });

here my jQuery attempt 2nd way :

 $('.ButtonDelete').on('click', function() {
        let id= $(this).val();
        let code=$('#code'+id).val();
        let confimation = confirm("Are you sure you want to delete " + code + "?");
        if (confimation==true){
            req = $.ajax({
                url: "menu.php?Option=deleteIgr",
                type : 'POST',
                data : { code : code }
            });
            req.done(function (response, status, jqXHR){
                var error = (typeof(response.error) !='undefined' && response.error!=null) ? response.error : null;
                if(error){
                alert("this element cannot be delete" + error);
                }
                else {
                console.log("Deleted with success");
                $('#row'+id).remove();
                }

            });
            req.fail(function (jqXHR, status, err){
                console.error("An error occurred: " + status, err);
            });
        }
    });

here my php that ajax execute:

try {
//my code before
    case "deleteIgr":
        require("Class/Ingredient.php");
        require("Class/IngredientsManager.php");
        $data = array ('code'=> $_POST['code'],'name'=>$_POST['name']);
        $deleterIngredient = new IngredientsManager;
        $deletedIngredient=$deleterIngredient->deleted(new Ingredient($data));
        break;
//my code after
}
catch(Exception $e) { 
    $result['error'] = $e->getMessage();
    echo  $result['error'];
}

for more precision : here the PHP where my jquery take data :

<?php foreach($ingredients as $object)
            { ?>
                <form method="post" >
                    <div id=<?='row'.$object->code()?> class="grid">
                        <span><input type="text" id=<?='code'.$object->code()?> class="cellCode" name="code" value=<?=$object->code()?> readonly></span>
                        <span><input type="text" id=<?='name'.$object->code()?> class="cellName" name="name" value=<?=$object->name()?>></span>
                        <span><button id=<?=$object->code()?> class="ButtonEdit" type="button" ></button></span>
                        <span><button class="ButtonDelete" type="button" value=<?=$object->code()?>></button></span>
                    </div>
                </form>

<?php } ?>

and also my connecition in PDO is made for show error in warning :

$db = new PDO('sqlsrv:Server=####;Database=####', $this->_user, $this->_password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));

When it's success for real there is no problem but it also return success when t doesn't delete the thing when I expect that it log me the warning that return php (my php is I think working because if I try with from post echo it send me a warning when it doesn't delete data.

Upvotes: 1

Views: 119

Answers (1)

Siddhartha esunuri
Siddhartha esunuri

Reputation: 1144

In your DB response set this parameter

if(mysql_query($query)){
    $response_array['status'] = 'success';  
}else {
    $response_array['status'] = 'error';  
}

And in your PHP call set proper headers

<?php    
    header('Content-type: application/json');
    echo json_encode($response_array);
?>

Finally in your ajax

success: function(data) {
    if(data.status == 'success'){
        alert("Deleted with success");
    }else if(data.status == 'error'){
        alert("Error on query!");
    }
},

Upvotes: 1

Related Questions