Working on a Laravel application which has form inputs field whereby am validating on the backend. Am pushing data to the backend via AJAX code which works fine. I have implemented a logic whereby errors from the backend are shown on the frontend via AJAX error object.
Inside the PHP function am also hitting an API to fetch some data. At times the API is not available,, am trying to handle the errors (when the API is not available) and display to the user via AJAX in the form of an alert box (using sweet alert js) but it aint throwing the error when API is not available.
Controller function
public function validatePlans (Request $request){
$validation = $this->validate($request, [
'FirstName' => 'required|string|max:13|regex:/^[a-zA-Z ` ]+$/',
'MiddleName' => 'required|string|max:13|regex:/^[a-zA-Z ` ]+$/',
'LastName' => 'required|string|max:13|regex:/^[a-zA-Z ` ]+$/'
],
[
'FirstName.regex' => 'Please insert a valid First Name',
'MiddleName.regex' => 'Please insert a valid Middle Name',
'LastName.regex' => 'Please insert a valid Sur Name'
]
);
/*Hits the API to get some data*/
$trv= GeneralHelper::global_Curl_Meta($data, 'api/v1/travel/get-plans?=');
//If API not available or status is failure
$travelplan_data = ($trv == null || $trv->status == "failure") ? [] : $trv->data;
//dd($travelplan_data);
if(!empty($travelplan_data)){
$plans = $travelplan_data;
//dd($plans);
return 'true';
}
}
else{
return 'fail';
}
}
AJAX code receiving the response from the API
$.ajax({
type: "POST",
url: "getplans",
data:JSON.stringify(type),
contentType: 'application/json',
dataType: "json",
success: function(response){
//API not reachable
if(response =='fail'){
//Display error using sweet alert js library
swal({
title: "Ooops!",
text: "We are undergoing a bit of scheduled maintenance. Sorry for the inconvenience. We'll be back soon.",
icon: "warning",
button: "Back",
});
//Unblock the spinner
$.unblockUI();
}
//On success
else{
//Unblock the spinner
$.unblockUI();
//Redirect
window.location.href="getp" ;
}
},
//Alert errors from backend
error: function(data) {
//Unblock the spinner
$.unblockUI();
var errors = '';
for(datos in data.responseJSON){
errors += data.responseJSON[datos] + '
';
}
//Display errors using sweet alert js library
swal({
title: "Ooops!",
text: errors,
icon: "warning",
button: "Rectify",
});
}
});