Reputation: 251
How to access properties that have been returned from response()->json() method from laravel
My Controller :
$validator = Validator::make($request->all(), [
'file' => 'required|mimes:xlsx|max:10000'
]);
if ($validator->fails()) {
return response()->json([
'message' => 'Please only upload valid Excel (.xlsx) file.'
], 422);
}
Ajax call :
$.ajax({
url : "{{ route('budgets.import') }}",
method:'post',
async: false,
data :new FormData(this),
contentType: false,
cache: false,
processData:false,
dataType: 'json',
success:function(response) {
console.log(response);
},
error: function(response) {
console.log(response);
Swal.fire(
'Failed!',
response.message,
'error'
);
},
});
result i've got when i console.log(response.response.data.message):
Uncaught TypeError: response.response is undefined
How can i access the "message" property ?
UPDATE 1
result i've got when i console.log(response):
Update 2
I tried to check the Network tab then found that the status is 500, although i passed in the controller 422,
But when i click the response the content was :
Illuminate\Http\JsonResponse {#1387
#data: "{"message":"Please only upload valid Excel (.xlsx) file."}"
#callback: null
#encodingOptions: 0
+headers: Symfony\Component\HttpFoundation\ResponseHeaderBag {#1386
#computedCacheControl: array:2 [
"no-cache" => true
"private" => true
]
#cookies: []
#headerNames: array:3 [
"cache-control" => "Cache-Control"
"date" => "Date"
"content-type" => "Content-Type"
]
#headers: array:3 [
"cache-control" => array:1 [
0 => "no-cache, private"
]
"date" => array:1 [
0 => "Wed, 19 Jan 2022 12:20:50 GMT"
]
"content-type" => array:1 [
0 => "application/json"
]
]
#cacheControl: []
}
#content: "{"message":"Please only upload valid Excel (.xlsx) file."}"
#version: "1.0"
#statusCode: 422
#statusText: "Unprocessable Content"
#charset: null
+original: array:1 [
"message" => "Please only upload valid Excel (.xlsx) file."
]
+exception: null
}
The "message" property was there, just couldn't access it in ajax call. And the most frustrating one is statusCode is true 422 , but in network tab it says 500
Upvotes: 0
Views: 552
Reputation: 311
Try this:
var obj = JSON.parse(response);
Then you can get your message:
$message = obj.message;
Upvotes: 0