Reputation: 504
When I submit an Ajax request and I know that the data should fail, I am receiving the error response within the success
event instead of the fail
event.
I need the response from Laravel to be sent to the Ajax fail event, as I will be building custom functionality for when the request fails to process.
I've tried all sorts to try and get it to work, but I'm at a complete loss as to why it's returning into the Success event. I must be being daft or something!
My Function within the Controller:
public function add_company(Request $request)
{
/**
* Validate the Add Company request
*/
$validator = \Validator::make($request->all(), [
'name' => 'required',
'sector' => 'required',
'number' => 'required',
'email' => 'required',
]);
if ($validator->fails()) {
return response()->json(['error' => 'Something went wrong']);
}
DB::table('companies')->insert([
'user_id' => Auth::id(),
'company_number' => $request->company_number,
'name' => $request->name,
'sector' => $request->sector,
'number' => $request->number,
'email' => $request->email,
'address_1' => $request->address_line_1,
'address_2' => $request->address_line_2,
'city' => $request->city,
'postcode' => $request->postcode,
]);
return response()->json(['success' => 'Company created successfully.']);
}
My Ajax function:
$('[data-add-company]').on('submit', function(e) {
e.preventDefault();
let $this = $(this);
let action = $this.attr('action');
let method = $this.attr('method');
var formData = $this.serialize();
$.ajax({
type: method,
url: action,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
'Access-Control-Allow-Origin': '*',
},
data: formData,
success: function(data){
console.log('success');
console.log(data); // Fail messages appear here for some reason.
},
error: function(data) {
console.log('error');
console.log(data);
},
});
});
I've tried using data.success
and data.error
to get the correct message but they just come up as undefined when I key into them.
What should happen
fail
event should initiate when the validation fails and show the correct fail message from the controller.success
event should only contain the success message from the controller, once the request has been successfully validated.Thanks in advance!
Upvotes: 1
Views: 1291
Reputation: 1159
What seems to be happening is even though your request failed its validation in the controller its still returns a valid response which JQuery sees as a success
, allowing it into the success
callback on the frontend.
Try
if ($validator->fails()) {
return response()->json(["error" => "something went wrong"], 422);
}
This should trigger the error callback.
You can also pass the errors back like this:
return response()->json($validator->errors(), 422);
To get all the error messages on the frontend.
For further reading check out this jQuery error handling article .
Upvotes: 1