2

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.

KondukterCRO
  • 543
  • 2
  • 16
  • 31
  • What about `return response()->json($response, 200);` ? Could you `console.log()` each of `jqXHR`, `textStatus`, `errorThrown` and tell us the result? – Wistar Nov 09 '16 at 16:05
  • jqXHR -> Object {readyState: 4, responseText: " ↵↵ Official Split A… }↵ ↵↵↵↵ – KondukterCRO Nov 09 '16 at 20:01
  • 1
    You are receiving HTML from the server but you told ajax that the datatype was json. What is exactly the responseText you are getting? That might give you some indication of what's being returned – Wistar Nov 10 '16 at 12:59
  • Yes, you were right. Now my success function is shown but mail is not sending. – KondukterCRO Nov 10 '16 at 20:30
  • I am not familiar with Mail and it's hard to tell from your code. Anything in the log? – Wistar Nov 10 '16 at 21:10
  • Nothing in the log. No errors, nothing. I just put mail send function from documentation in controller. But nothing happens. Response from json is ok but it seems just like mail is not executing. – KondukterCRO Nov 11 '16 at 11:43
  • go to the app/config/mail.php and change the driver to “mail”. Also put the host as blank. – Wistar Nov 11 '16 at 13:58
  • Same thing again. Success function is run but mail is not sent. – KondukterCRO Nov 11 '16 at 15:00
  • Try removing the encryption `'encryption' => ''` – Wistar Nov 11 '16 at 15:19
  • No, nothing changed with removal of encryption. This is localhost so I think settings are ok. What I think that is wrong is function in controller. Yes, it's made by laravel documentation but I think it can't get fields that are collected by jquery ($('#firstName').val() etc. – KondukterCRO Nov 11 '16 at 16:32
  • What does your logs says when you `Log::info($request->all())`? – Wistar Nov 11 '16 at 17:14

1 Answers1

0

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.

KondukterCRO
  • 543
  • 2
  • 16
  • 31