I'm using jQuery $.ajax
to send ajax requests to my Laravel 5.1 API.
I'm trying to simply output the error response from the server, but am unable to JSON.parse
the response due to a rogue '
at the beginning of the responseText
property value.
Why is that there?
Frontend:
API.Auth.register(params).done(function (result) {
// Do stuff
}).error(function (xhr, status, error) {
console.log('Registration error: ', xhr);
var parsed_response = JSON.parse(xhr.responseText);
console.log('parsed_response', parsed_response);
alertify.error('There was a problem with your registration.');
});
register : function (params)
{
return $.ajax({
url: globals.env.api_host + globals.env.api_ver + '/register',
type: 'POST',
data: params,
dataType: 'json',
cache: true
})
},
Laravel 5.1: I've tried wrapping the properties in " "
, with the same error result:
public function register(Request $request)
{
try {
$new_user = $this->create($request->all());
} catch (QueryException $e) {
// error code 23000 is unique SQL unique constraint error - TODO: abstract this checking
if ($e->getCode() === '23000') {
return response()->json(['status' => 500, 'message' => 'This e-mail already exists. Try a new e-mail or logging in.']);
} else {
return response()->json(['status' => 500, 'message' => 'There was an error processing registration.']);
}
}
EDIT: I tested if the '
persists if I just return a string:
//Original Route:
//$router->post('/register', 'Auth\AuthController@register');
$router->post('/register', function () {
return 'hello world';
});
Response: 'hello world
That single quote at the beginning persists.
Side note: I can't find anything on capturing a custom Exception message in jQuery ajax. My preferred way to return errors is custom exceptions:
throw new BadRequestHttpException('There was an error processing registration.');
but $.ajax
offers no way to capture the exception message, so I've resorted to returning response()->json...
from Laravel.
Any thoughts on this?
EDIT: Found it. Someone made an accidental change to the config/app.php
file and added a '
. Odd how Laravel treats this though by still serving the response, but prepends the '
.