mistery_girl mistery_girl - 5 months ago 19
Ajax Question

How to select elements that are in ajax response after validation

I'm using ajax to send data from my form. I'm using Laravel, in controller I'm using Validator and I return json when there are validation errors like that:

$messages = $this->getValidation('individual', $input, 0);

$validator = Validator::make($input, $rules, $messages);

if ($validator->fails()) {
return Response::json(array(
'success' => false,
'errors' => $validator->getMessageBag()->toArray()


In my view I show only part of code that is needed:

url: form.action,
type: form.method,
data: $(form).serialize(),
success: function(response) {

$.each(response.errors, function (key, value) {

$('input[name=key]').addClass('error'); //I can't get input with the same name as the key



I want if there is error property in json, to select input, select or textarea which name is the same as the key in $.each function and add them error class.

Returned data is in this format:

{"success":false,"errors":{"title":["The title field is required."],"first_name":["The first name field
is required."],"last_name":["The last name field is required."],"front_passport":["The front passport
field is required."]}}


You are selecting elements with name 'key'; replace your selector with: