Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a correct JSON response

I'm using Laravel 4 for a project I'm working on. It relies heavily on AJAX for a lot of its functionality.

In the jQuery I use to upload files (fileupload), I have the following success and fail function:

done: function (e, data) {
    // Show success message
},
fail: function (e, data) {
    // Show fail message
}

In my controller, I use the following to return success or fail:

// Success Response
return Response::json('success', 200)

// Fail Response
return Response::json('error', 400)

Everything works fine with the functionality, the success and fail messages show up, the file uploads, everything is perfect, except when the function fails and it returns the fail response, in the console I see:

400 (Bad Request)

The error message still shows and its all good, but I'm just wondering if I'm handling this correctly, I don't like red errors showing in my console for something that seems to be working correct.

Any advice would be greatly appreciated.

like image 812
BigJobbies Avatar asked Oct 20 '22 23:10

BigJobbies


1 Answers

That is exactly how it works. You are throwing a HTML Status Code for an error - which is a 'best practice' for an API.

The console is showing an error, because it sees a non-200 status code, and then alerts you.

like image 142
Laurence Avatar answered Oct 24 '22 12:10

Laurence