Every time I do an ajax request the Laravel always return the JSON response with so many whitespaces in front of the response text so the response always executed in error, not in the success section of ajax request, and I can’t show my error message too because it starts with white space so I can’t take the object notation, is there anything I can do to get rid of it?
Screenshot of response text :
My ajax request code :
$('.ajax-form').submit(function (e) {
e.preventDefault();
var form = $(this);
$.ajax({
dataType: "json",
url: form.attr('action'),
method: form.attr('method'),
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function(result){
console.log('success');
alert(result.data.message);
if (result.data.location) window.location.hash = result.data.location;
location.reload(true);
},
error: function(err){
console.log(err);
if (err.status == 422) {
let el = form.find('.error-block');
el.find('.alert-danger').remove();
console.log(err);
$.each(err.responseJSON.errors, function (i, error) {
let errorBlock = "<div class='alert alert-danger alert-dismissible'> "
+ "<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button>"
+ "<p><i class='icon fa fa-close'></i> " + error[0]+ "</p></div>";
el.append(errorBlock);
$('.modal').animate({ scrollTop: 0 }, 'fast');
});
}
}
});
});
My code in laravel :
public function insert(Request $request)
{
$request->validate(['image' => 'required|image']);
return response()->json(['data' => ['message' => 'Data is successfully updated!']]);
}
Actually this code work before I got this whitespace thing, I think this is the server-side who have the problem, but I didn’t change anything except I’ve do composer update
before.
3
Answers
For now, I find my solution is to add
ob_clean();
in Controller__construct
method so I don't have to add it in every controller and request, but I hope there's a better solution than this.You can try set headers with “Accept” parameter to json into your ajax.
Since I can’t add a comment yet, I will post a question here. can you please show us the dump the data in your controller before returning it to script?