EvaldasL
EvaldasL

Reputation: 105

jQuery PHP POST error handling

I'm sending POST request via jQuery:

if ( isset( $_POST['newOwner'], $_POST['uID'] ) ) :
    $function->updateTransport( $_POST['newOwner'], $_POST['uID'] );
endif;

$.post("", {
    newOwner: $("#newOwner").val(),
    uID: uid
})

How can I log in jQuery when, for example, MySQL can't update? I've tried .fail but jQuery always show success post request.

public function updateTransport( $newOwner, $uID )
{
    try
    {
        $stmt = $this->db->prepare( "UPDATE cars SET owner= ? WHERE id = ?" );
        $stmt->execute( array( $newOwner, $uID ) );
    }
    catch(PDOException $e)
    {
        echo $e->getMessage();
    }
}

Upvotes: 0

Views: 63

Answers (1)

pOoOf
pOoOf

Reputation: 119

You need to send specific data about success and failure of query executed. Try this code.

    public function updateTransport( $newOwner, $uID ){
        try
        {
            $stmt = $this->db->prepare( "UPDATE cars SET owner= ? WHERE id = ?" );
            $status = $stmt->execute( array( $newOwner, $uID ) );
            if($status){
                $ret = array(
                    'status' => 'success',
                    'message' => 'Success'
                    );
                echo json_encode($ret);
            }else{
                $ret = array(
                    'status' => 'failed',
                    'message' => 'Failed'
                    );
                echo json_encode($ret);
            }
        }
        catch(PDOException $e)
        {
            $ret = array(
                'status' => 'failed',
                'message' => $e->getMessage()
                );
            echo json_encode($ret);
        }
   }
    $.ajax({
        'url' : 'yourURL',
        data : { 'key' : value },
        success : function(data, textStatus, jqXHR){
            var dat = JSON.parse(data);
            if(dat.status == 'success'){

            }else{

            }
        },
        error : function(jqXHR, textStatus, errorThrown){
            var dat = JSON.parse(data);
            if(dat.status == 'success'){

            }else{

            }
        }
    });

Upvotes: 1

Related Questions