简体   繁体   中英

Laravel - How to return json error message on error?

I just added x-editable to my current Laravel project. It works perfectly well but I have a problem with returning the error message .

When the controller is able to save the request, I get a 'Success!' json message. That's fine. But when I have an error, I do not get the 'Error!' message. As you can see I fire up the error message when $article->save() was not successful.

What am I doing wrong?

Controller:

$article->$input['name'] = $input['value'];

if( $article->save() ){
    // this works
    return response()->json(array('status'=>'success', 'msg'=>'Success!.'), 200);
} 

else{
    // this does not work
    return response()->json(array('status'=>'error', 'msg'=>'Error!'), 500);
}

JavaScript in View:

$(".xeditable").editable({
    success: function(response) {
        console.log(response.msg);
    },
    error: function(response) {
        // console says, that response.msg is undefinded
        console.log(response.msg);
    }
});

Kind regards.

On error callback, the passed response parameter is jqXHR ( jQuery XMLHttpRequest ). In order to access the JSON response, you can access the responseJSON property like the code below.

$(".xeditable").editable({
  success: function(response) {
    console.log(response.msg);
    // Must return nothing.
  },
  error: function(response) {
    // The JSON object stored in responseJSON property.
    console.log(response.responseJSON.msg);

    // Must return a string, represent the error message.
    return response.responseJSON.msg;
  }
});

As pointed on the X-editable documentation, the error callback must return a string that represents the error message.

Hope this help!

I'm not familiar with x-editable but try to change the response code in case of error from 500 to 200 and then in your javascript

$(".xeditable").editable({
    success: function(response) {
        if (response.status == 'error') {
            console.log('error: ' + response.msg);
        }
        else {
            // do stuff for successful calls
            console.log('success: ' + response.msg);
        }
    },
    error: function(xhr, status, error) {
        console.log('server error: ' + status + ' ' + error);
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM