1

Hi I'm using Laravel and jQuery Ajax to submit a contact form. This works perfectly and I can catch the success message easily as its a string. But my error message is being passed as an array, so I guess it works differently as the error messages aren't been output. But I can see in my console that it is been passed back as so:

errors: {name: ["The name field is required."], email: ["The email field is required."],…}
email: ["The email field is required."]
message: ["The message field is required."]
name: ["The name field is required."]
success: false

I'm trying to append these error messages as so into my html:

error: function (XMLHttpRequest, json, errors) {
                $( "#errors" ).append(json.message );

          }

and my controller passes this to the ajax as so:

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

However this is having no effect. Am I missing something? My code is below. Hope someone can help. Thanks in advance.

public function getContactUsForm()
        {

            if(Request::ajax()){

                    $data = Input::all();
                    $rules = array(
                                    'name' => 'required',
                                    'email' => 'required',
                                    'message' => 'required');
                        // catch validation and pass back json reponse if not filled in correctly.
                     $validator = Validator::make ($data, $rules);
                        if ($validator -> passes()){
                            //Send email using Laravel send function
                            Mail::send('emails.contactform', $data, function($message) use ($data)
                            {
                                $message->from(Config::get('mail.from')['address'], Config::get('mail.from')['name']);
                                   $message->to('[email protected]', 'Test')->subject(' Contact Form');

                            });  
                             return Response::json(array(
                                'success' => true,
                                'message' => 'Thank you, your message has been sent.'

                            )); 
                        } // end if start else
                            else
                            {
                                return Response::json(array(
                                    'success' => false,
                                    'errors' => $validator->getMessageBag()->toArray()

                                ));
                            }

                }
                else {
                    return 'NOT AN AJAX RESPONSE...';
                }

        }

and my ajax call is below:

$('#submit-contact').on('submit', function(e) {

  e.preventDefault(); 

  var name = $('#name').val();
  var message = $('#message').val();
  var email = $('#email').val();

  $.ajax({
         url: '/contact_request',
         headers: {
            'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
        },
        data: {name:name, message:message, email:email},
        type: 'POST',
        success: function (json) {
          // clear inputs
            $('#name,#message,#email').val('');
            // append success message
            $( "#success" ).append(json.message );

        },
        error: function (jqXHR, json) {
            $( "#errors" ).append(json.errors );

      }
    });

});

1 Answer 1

3

You can iterate over the json.errors object properties to output each error message value:

error: function (jqXHR, json) {
    for (var error in json.errors) {
        $('#errors').append(json.errors[error] + '<br>');
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

json.errors[error] is an array instead of a string?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.