I have the following ajax code in my frontend.
var formData = $('#application-information-step-one').serialize();
var actionUrl = $('#application-information-step-one').attr('action');
$.ajax({
url: actionUrl,
type: 'POST',
data: formData,
success: function(data) {
var resp = JSON.stringify(data);
console.log(resp);
},
error: function(data) {
}
And following code to return json response from my controller if the request is ajax
:
if ($request->ajax()) {
return response()->json([
'message' => 'Information saved sucessfully !'
],200)->headers('Content-Type', 'application/json');
}
But with the above code setup. Laravel returns HTML code of same page from where the request was made.
HTML page is rendered in preview section of network tab .
Can anyone suggest what am I missing here ?
2
Answers
Return JSON response from controller
In AJAX success function code:
and add to AJAX request object next parameters too
Check for Ajax request is incorrect, otherwise the controller wouldn’t have outputted HTML.
You can try several things:
use IlluminateSupportFacadesRequest;
at the top of the filerequest->ajax()
withRequest::wantsJson()
request()->ajax()
Any of the above subject to your Laravel version.
More details here