0

I had a code, where an if condition failed. In that case, I wanted the error: part of the Ajax to get triggered. But everytime, the success: of Ajax was called. Here is a code which can help you understand what I want to ask.

Ajax request call

success: function (response){
//some code 
},

error: function (response){
//some code
},

In my backend code

if(condition ){
//some code
return response()->json([
   'success'=>true,
   'message'=>"Success: handler in Ajax should be triggered"

]);
}else{
//some code
return response()->json([
   'success'=>false,
// OR 'error'=>true,
   'message'=>"Error: handler in Ajax should be triggered"

]);
}

But, even if the condition got false, the success: in Ajax was still triggered. It didn't go to the error: part. I didn't understand. Can someone explain what was happening?

Skumar
  • 480
  • 6
  • 24
  • Ajax doesn't know anything about your `success` *property* - that's not a standard HTTP response code. In order to get to `error:` you need to fail in your back end and return a non-200 HTTP response code, eg a 500 error code. Otherwise, in your `success:` callback, check for `response.success` – freedomn-m Oct 13 '20 at 10:04

1 Answers1

1

Your success callback is beeing called, because the response was successfull since it returned the HTTP status code of 200.

Your error callback is only called, when your controller action returns an status code of >= 400 .

If you modify your controller action to:

return response()->json(
  [
    'success'=>false,
    'message'=>"Error: handler in Ajax should be triggered"
  ], 
  400
);

Then your error callback will be called.

miron
  • 1,361
  • 1
  • 11
  • 24
  • Can you tell me when can HTTP Status code return >=400? I am new to coding. – Skumar Oct 13 '20 at 10:11
  • I attached a list with the description of every status code. But in simple words you could say that all status code begining with a 4xx are client errors and 5xx server errors. – miron Oct 13 '20 at 10:46