Send email from contact form in Laravel 5 using jQuery AJAX

橙三吉。 提交于 2021-01-27 22:50:24

问题


I have contact form in Laravel blade:

<div id="contactform">
    <meta name="_token" content="{{ csrf_token() }}" /> 
    <ul>
    @foreach($errors->all() as $error)
        <li>{{ $error }}</li>
    @endforeach
    </ul>
    {{ Form::open(array('route' => 'contact_store', 'id' => 'contact', 'name' => 'contact')) }}
        <input type="text" id="firstName" name="firstName" placeholder="{{ trans('index.first_name') }}" class="required" />
        <input type="text" id="lastName" name="lastName" placeholder="{{ trans('index.last_name') }}" class="required" />
        <input type="text" id="email" name="email" placeholder="{{ trans('index.email') }}" class="required email" />
        <textarea id="message" name="message" cols="40" rows="5" placeholder="{{ trans('index.message') }}" class="required"></textarea>
        <input id="submit" class="send_it" name="submit" type="submit" value="{{ trans('index.submit_button') }}" />
    {{Form::close()}}
    <div id="response"></div>
    <div id="loading"><img src="images/loader.gif" alt="loader"></div>
</div>

I have my routes set in routes.php:

Route::get('/', 'HomeController@index');
Route::post('/', 
['as' => 'contact_store', 'uses' => 'HomeController@store']);

I have jQuery validator validation set and it works correctly. When validation is passed I'm calling ajax to send data.

 $('#submit').click( function(e) {
     $.ajaxSetup({
         header:$('meta[name="_token"]').attr('content')
      })
      e.preventDefault;
      if( $('#contact').valid() ) {
         ajaxSubmit();
       }
       else {
           $('label.error').hide().fadeIn('slow');
       }
       });
   });

function ajaxSubmit() {
$('#loading').show();
$('#submit').attr('disabled', 'disabled');
var firstName = $('#firstName').val();
var lastName = $('#lastName').val();
var email = $('#email').val();
var message = $('#message').val();

var data = 'firstName=' +firstName+ '&lastName=' +lastName+ '&email=' +email+ '&message=' +message;

$.ajax({
    url: '/',
    type: 'get',
    dataType: 'json',
    data: data,
    cache: false,
    success: function(response) {
            $('#loading, #contact, .message').fadeOut('slow');
            $('#response').html('<h3>'+Lang.get('index.email_sent')+'</h3>').fadeIn('slow');
    },
    error: function(jqXHR, textStatus, errorThrown) {
            $('#loading').fadeOut('slow');
            $('#submit').removeAttr('disabled');
            $('#response').text('Error Thrown: ' +errorThrown+ '<br>jqXHR: ' +jqXHR+ '<br>textStatus: ' +textStatus ).show();
    }
});
return false;
}

And in my controller I have:

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App;
use App\Http\Requests;
use App\Http\Requests\ContactFormRequest;
use Mail;

class HomeController extends Controller
{
public function index()
{
    return view('index');
} 
public function store(ContactFormRequest $request)
{
    Mail::send('email.mail',
    [
        'name' => $request->get('firstName'),
        'email' => $request->get('email'),
        'message' => $request->get('message')
    ], function($message)
    {
        $message->from($request->get('email'));
        $message->to('mymail@gmail.com')->subject('Contact form');
    });
    $response = [
        'status' => 'success',
        'msg' => 'Mail sent successfully',
    ];
    return response()->json([$response], 200);
}
}

And in my ContactFormRequest.php I have:

public function authorize()
{
    return true;
}
public function rules()
{
    return [
        'firstName' => 'required',
        'lastName' => 'required',
        'email' => 'required|email',
        'message' => 'required|min:10'
    ];
}
}

And I configured config/mail.php:

'driver' => env('MAIL_DRIVER', 'smtp'),
'host' => env('MAIL_HOST', 'smtp.gmail.com'),
'port' => env('MAIL_PORT', 465),
'from' => ['address' => null, 'name' => null],
'encryption' => env('MAIL_ENCRYPTION', 'ssl'),
'username' => env('mymail@gmail.com'),
'password' => env('mypass'),
'sendmail' => '/usr/sbin/sendmail -bs',

I added blade file called mail.blade.php in resources/views/email. Validation that I set in js with jquery validator works good, but when validation is ok and it comes to part when ajax needs to be send I got error: Error Thrown: SyntaxError: Unexpected token < in JSON at position 0
jqXHR: [object Object]
textStatus: parsererror

I think json from controller is not passed well but I can't figure out how to fix it.


回答1:


Problem was in csrf token that wasn't sending with form. So I added

var _token = $('[name="_token"]').val(),

and send it with other form data and everything is ok.



来源:https://stackoverflow.com/questions/40507295/send-email-from-contact-form-in-laravel-5-using-jquery-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!