1

I am trying to submit a form using ajax so my page will not do a full page reload rather only the form should change to show any errors. I have tried many options from the web with no luck. This here is the best help I have seen, but it doesn't give the solution. Note I am using laravel version 5.3.10.

Here is my code:

Javascript:

<script type="text/javascript">

    $(document).ready(function () {

        $('#footer-form').click(function () {
            //event.preventDefault();
            $.ajax({
                type: 'POST',
                url: 'http://localhost/ensignhospital/mail',
                data: $('form#footer-form').serialize(),
                dataType: 'html'
            })

                    .done(function (data) {
                        console.log(data);
                    });

        });
    });

</script>

Laravel Route:

Route::group(['before' => 'guest'], function () {
    /*
     * CSRF Protection
     *
     * */
    Route::group(['before' => 'csrf'], function () {

        Route::post('/ensignhospital/mail', [
            'as' => 'mail',
            'uses' => 'HomeController@postSendMail'
        ]);
    });


});

Laravel controller:

 public function postSendMail(Request $request)
    {

        if($request->ajax()){

            $validator = Validator::make($request->all(), [

                'first_name' => 'required',
                'last_name' => 'required',
                'email' => 'required|email',
                'message' => 'required',
                'g-recaptcha-response' => 'required|captcha'
            ]);

            if($validator->fails()){
                return redirect()->back()
                    ->withErrors($validator)
                    ->withInput(Input::all());
            }else{
                return View('passed');

            }
        }else{
            return View('fail');
        }



    }

Form:

{!! Form::open(['route' => 'mail', 'method' => 'post', 'role' => 'form', 'id' => 'footer-form']) !!}
<div class="form-group has-feedback">
    {!! Form::label('first_name', null, ['class' => 'sr-only']) !!}
    {!! Form::text('first_name', null, ['class' => 'form-control', 'placeholder' => 'First Name']) !!}
    <i class="fa fa-user form-control-feedback"></i>
    @if($errors->has('first_name'))
        {{ $errors->first('first_name') }}
    @endif
</div>
<div class="form-group has-feedback">
    {!! Form::label('last_name', null, ['class' => 'sr-only']) !!}
    {!! Form::text('last_name', null, ['class' => 'form-control', 'placeholder' => 'Last Name']) !!}
    <i class="fa fa-user form-control-feedback"></i>
    @if($errors->has('last_name'))
        {{ $errors->first('last_name') }}
    @endif
</div>
<div class="form-group has-feedback">
    {!! Form::label('email', null, ['class' => 'sr-only']) !!}
    {!! Form::email('email', null, ['class' => 'form-control', 'placeholder' => 'Email address']) !!}
    <i class="fa fa-envelope form-control-feedback"></i>
    @if($errors->has('email'))
        {{ $errors->first('email') }}
    @endif
</div>
<div class="form-group has-feedback">
    {!! Form::label('message', null, ['class' => 'sr-only']) !!}
    {!! Form::textarea('message', null, ['class' => 'form-control', 'rows' => 8, 'placeholder' => 'Message']) !!}
    <i class="fa fa-pencil form-control-feedback"></i>
    @if($errors->has('message'))
        {{ $errors->first('message') }}
    @endif
</div>    

{!! Form::submit('Send', ['class' => 'btn btn-default', 'id' => 'mail_btn']) !!}

{!! Form::close() !!}
3
  • Use location.reload(); on success Commented Sep 27, 2016 at 10:45
  • What does .done(function (data) {console.log(data);}); show in the console ? I've noticed you are returning a view from your controller method, why don't you just return json data, which can be appended to the DOM via JS ? Commented Sep 27, 2016 at 10:49
  • @DavidDomain, I get an error from the if($request->ajax()){} block as I am directed to the error view View('fail'). Commented Sep 27, 2016 at 10:55

1 Answer 1

0

What you need to do is to render the view that you want to pass throught the ajax like this:

return view('passed')->render();

...

return view('fail')->render();

EDIT

You have to pass event as a clouser parameter and uncomment this: //event.preventDefault();:

$('#footer-form').click(function (event) {
        event.preventDefault();
        $.ajax({
            type: 'POST',
            url: 'http://localhost/ensignhospital/mail',
            data: $('form#footer-form').serialize(),
            dataType: 'html'
        })

                .done(function (data) {
                    console.log(data);
                });

    });

so that:

click(function () {

why it doesn't work. Should be:

click(function (event) {
Sign up to request clarification or add additional context in comments.

5 Comments

my ajax request isn't even passing through the if($request->ajax()){} block. I am trying to have that controller catch the form data using ajax, hence preventing a total page reload.
When I get rid of the if($request->ajax()){} block the code validates using laravel controller but the whole page reloads.
Why have you comment this: //event.preventDefault(); I will show you in edit
I noticed that the form did not post to the url so I removed it to make it do the default behaviour
I added the event variable but still won't pass into the if block

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.