0

This issue works fine when calling ajax from PHP, but I can't seem to get it working with Laravel 5.2. All I'm trying to do is send an email using AJAX when submitting a form.

This is my routes.php entry for sending the email:

Route::post('/send', 'CommsController@send');

And this is my layout.blade.php file:

<head>
    <meta name="csrf-token" content="{{ csrf_token() }}" />
</head>

$( document ).ready(function() {
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    ...

    $( "#send" ).button().click(function(event) {
        var form       = $( "#contact-form" ),
            postAction = form.attr('action'),
            isValid    = form.valid(),
            valSum     = $(".validation-summary");

        if ( isValid ) {
            var postData = {
                message_type: "contact"
                ,first_name: first_name.val()
                ,last_name: last_name.val()
                ,email: email.val()
                ,message: message.val()
            };

            // process the form
            $.ajax({
                type: "POST",
                // our data object
                url: postAction,        // the url where we want to POST
                data: postData
            })
            // using the done promise callback
            .done(function(data) {
                // log data to the console so we can see
                console.log(data); 
                // here we will handle errors and validation messages
                if ( ! data.success ) {
                    valSum.removeClass( "success" );
                    valSum.addClass( "validation-summary error" );
                    valSum.html( data );
                } else {
                    // $( ".validation-summary" ).html( "Message sent." );
                    valSum.html( data.message );
                }
            })
            // using the fail promise callback
            .fail(function(data) {
                // show any errors
                // best to remove for production
                console.log(data);

                valSum.removeClass( "success" );
                valSum.addClass( "validation-summary error" );
                valSum.html( "Server Error: " + data.statusText + " processing your request, please contact Dorothea or report a bug." );
            });
            // stop the form from submitting the normal way and refreshing the page
            event.preventDefault();
        } else {
            return false;
        }
    });

And finally here is my CommsController send() function:

public function send(Request $request) {
    //check if its our form
    if ( Session::token() !== Request::get( 'csrf-token' ) ) {
        return Response::json( array(
            'message' => 'Unauthorized attempt to create setting'
        ));
    }

    $message_type = strval(Request::input('message_type'));
    $first_name = strval(Request::input('first_name'));
    $last_name = strval(Request::input('last_name'));
    $email = strval(Request::input('email'));
    $message = strval(Request::input('message'));

    $to  = "robinson.jeanine6@gmail.com";

    // subject
    $subject = "Dorothea - Contact Us";

    Mail::send('email.contact', ['request' => Request::all()], function ($message) use ($request) {
        $message->from($this->email, $this->email);
        $message->to($user->email, $user->email)->subject($subject);
    });

    $response = array(
        'status' => 'success',
        'message' => 'Message sent.',
    );

    return Response::json( $response );
}

This question is related to the one I posted here, but instead of getting a MethodNotAllowedHttpException, all that been returned now from the AJAX call is the CSRF-token value.

Community
  • 1
  • 1
Tim Kruger
  • 863
  • 2
  • 10
  • 26

2 Answers2

0

Replace .done callback with .success to get the return data.

.success(function(data) {
    if (data.status != 'success' ) {
        valSum.removeClass( "success" );
        valSum.addClass( "validation-summary error" );
    }

    // eventually, print out the return message
    valSum.html(data.message);
})
ln9187
  • 730
  • 1
  • 7
  • 23
  • @In9187 please refer [here](http://stackoverflow.com/questions/10931836/should-i-use-done-and-fail-for-new-jquery-ajax-code-instead-of-success-and) for why I'm using `.done` instead of `.success`. – Tim Kruger Jan 19 '16 at 14:49
0

Just wanted to let everyone that tried to help me out know that sending of emails works fine in Laravel if I change the post request to a get request.

Not too sure why this is, so if anyone can shed some light as to why this would be the case that would be great.

Tim Kruger
  • 863
  • 2
  • 10
  • 26