0

I have a contact form in Laravel that sends 2 emails - a confirm email to user and then to the sender.

I am not getting any error, and in my network tab it show POST status but no status code. The page just refreshes when I click on send. If someone can maybe just have a look and suggest something so I can just get an error to have something to work on.

Here is my HTML:

      <div id="contact">
        <form class="form-horizontal" id="contactForm" role="form">
              {{ csrf_field() }}

              @if(Auth::guest())

              <div class="form-group">
                <label for="exampleInputName2">Name</label>
                <input type="text" class="form-control" id="name" placeholder="Jane Doe" name="name">
              </div>
              <div class="form-group">
                <label for="exampleInputEmail2">Email</label>
                <input type="email" class="form-control" id="email" placeholder="jane.doe@example.com" name="email">
              </div>

              @else

              <div class="form-group">
                <label for="exampleInputName2">Name</label>
                <input type="text" class="form-control" id="name" value="{{ Auth::user()->getFullName() }}" name="name">
              </div>
              <div class="form-group">
                <label for="exampleInputEmail2">Email</label>
                <input type="email" class="form-control" id="email" value="{{ Auth::user()->email }}" name="email">
              </div>

              @endif

              <div class="form-group ">
                <label for="exampleInputText">Your Message</label>
               <textarea id="message" name="message" class="form-control" placeholder="Description"></textarea>
              </div>
              <button type="submit" class="btn btn-default" v-on:click="submitMessage">Send Message</button>
            </form>
      </div>

My Ajax call (using Vue.js):

    var contact = new Vue({
          el: '#contact',
          data: {

          },

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

              $.ajax({
                url: '/pages/contact/sendMessage',
                type: 'POST',
                data: $("#contactForm").serialize(),
                success: function(response){
                  toastr.success(response.response);
                },
                error: function(error){
                  toastr.success(error.error);
                }
              });
            }
          }
        });

My Route:

Route::post('/pages/contact/sendMessage', 'ContactController@sendMessage');

My Controller:

public function sendMessage(Request $request){
      $this->validate($request, [
        'name' => 'required',
        'email' => 'required',
        'message' => 'required'
      ]);

      $users = User::all();
      $emails = collect($users)->pluck('email')->all();

      if(Auth::user()){
        $user = Auth::user()->getFullName();
        $email = Auth::user()->email;
      }else{
        $user = $request->input('name');
        $email = $request->input('email');
      }

      $message = $request->input('message');

      Mail::to($emails)->send(new Contact($user, $email, $message));

      Mail::to($email)->send(new ContactConfirm($user, $email, $message));

      $response = [
        'response' => 'Email Successfully Sent',
        'error' => 'Something went wrong'
      ];

      return response()->json($response);

  }

My Mail:

    public $title;
    public $introLines;
    public $outroLines;
    public $actionText;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($user, $email, $message)
    {
      $this->title = 'Contact from' . ' ' . $user;
      $this->$introLines = ['The following user has issued a message'];
      $this->$outroLines = ['User: ' . $user, 'Email: ' . $email, 'Message: ' . $message];
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->view('emails.template');
    }

My .env:

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=email@gmail.com
MAIL_PASSWORD='app password'
MAIL_ENCRYPTION=tls

I also updated my config/mail.php to have the same info as above. I did stop and start my service several times after .env changes.

I Love Code
  • 420
  • 1
  • 5
  • 26
  • Is there some information in your log file located at `storage/logs` – milo526 Jan 23 '18 at 10:30
  • `[2018-01-23 10:47:35] local.ERROR: stream_socket_enable_crypto(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed {"userId":1,"email":"myemail@gmail.com","exception":"[object] (ErrorException(code: 0): stream_socket_enable_crypto(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed at C:\\xampp\\htdocs\\laravel\\vendor\\swiftmailer\\swiftmailer\\lib\\classes\\Swift\\Transport\\StreamBuffer.php:94)` – I Love Code Jan 23 '18 at 10:50
  • This is the Last item in log, but I did a test again now and did not get any new errors in log – I Love Code Jan 23 '18 at 10:50
  • https://stackoverflow.com/questions/44423096/localhost-and-stream-socket-enable-crypto-ssl-operation-failed-with-code-1 – milo526 Jan 23 '18 at 10:54

2 Answers2

0

This may not be the issue but you should make this change:

// you are wrapping a collection in collect() and chaining all() incorrectly
$users = User::all();
$emails = collect($users)->pluck('email')->all();

// instead simply do
$emails = User::all()->pluck('email');

This line though is sending an email to every single user in your database.

  Mail::to($emails)->send(new Contact($user, $email, $message))

Edit

According to that log error you should make this mail config change

'ssl' => [
   'allow_self_signed' => true,
   'verify_peer' => false,
   'verify_peer_name' => false,
],
0

I believe the problem is actually your "submit" button. A button with type=submit by default will submit to the forms "action=''" attribute of which you have none, and this will cause the form / page to refresh.

Change the button to

`<button type="button">` 

And then that will prevent the default action and your ajax call will then be triggered.

Alternatively I think you can also use

`<button @click.prevent="submitMessage">` 

Which will basically do the same thing.

If desired you could also put the .prevent directive on the form element itself.

<form v-on:submit.prevent></form>
skribe
  • 3,595
  • 4
  • 25
  • 36
  • Thank you so much - I needed this. My page kept redirecting when clicking on the button and I could not figure it out. Now I am at least getting an error 500 - better than what I had previously. Thanks! – I Love Code Jan 23 '18 at 11:37
  • Glad it helped. If my answer was good then please mark my answer as the "accepted answer" :) i.e. click the checkmark next to the answer – skribe Jan 23 '18 at 11:39