简体   繁体   中英

Ajax use in laravel 5.3

I am in a bit of I a fix. I am trying to submit a form using Ajax. Now when I do this without creating the laravel default auth scaffold it works fine, but if add the auth scaffold it fails. I have tried all I can but can't seem to get it to submit.

Here is my code: controller to send mail --

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;

use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;

class MailController extends Controller
{
    //
    public function index(Request $request)
      {


          if ($request->ajax()) {
              $validator = Validator::make($request->all(), [
                          'first_name' => 'required',
                          'last_name' => 'required',
                          'email' => 'required|email',
                          'mymessage' => 'required',
                          'g-recaptcha-response' => 'required|captcha',
              ]);

              if ($validator->fails()) {
                  return redirect()->back()
                                  ->withErrors($validator)
                                  ->withInput();
              } else {

                  // get input fields values
                  $data = [
                      'firstName' => $request->input('first_name'),
                      'lastName' => $request->input('last_name'),
                      'email' => $request->input('email'),
                      'mymessage' => $request->input('mymessage'),
                  ];

                  Mail::send('emails.email', $data, function ($message) {
                     official email
                      $message->to('xxxxxxxxx@gmail.com', 'My Name')->subject('Information');
                  });

                  return response()->json([
                              'responseText' => 'Mail was sent!'], 200);
              }
          } else {
              return View('fail')->render();
          }
      }
}

The Route files:

Route::get('/', function () {
    return view('welcome');
});

Route::post('/mail', [
    'as' => 'mail',
    'uses' => 'MailController@index'
]);

Auth::routes();

Route::get('/home', 'HomeController@index');

Ajax code:

$(document).ready(function() {

    var options = {
        beforeSubmit: validate,
        url: '/mail',
        data: $(this).serialize(),
        type: 'POST',
        dataType: 'json',
        clearForm: true,
        success: great,
        error: lost
    };

    $('#footer-form').ajaxForm(options);
});

function validate(formData, jgForm, options) {
    for (var i = 0; i < formData.length; i++) {
        if (!formData[i].value) {
            alert('Please enter a value for all fields');
            return false;
        }
    }
}

function great(responseText, statusText, formData) {
    // prevent multiple form submission
    $('#mail_btn').prop('disabled', true);
    // show alert on success
    $(".alert-success").prop("hidden", false);
    // remove mail error information if displayed
    $(".alert-info").prop("hidden", true);
    // reset google recaptcha
    grecaptcha.reset();

}

function lost(formData) {
    // prevent multiple form submission
    $('#mail_btn').prop('disabled', false);
    $(".alert-info").prop("hidden", false);
}

My form code:

<div class="col-sm-6">
 <div class="footer-content" id="myfooter">
    {!! Form::open(['action' => 'MailController@index', '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('mymessage', null, ['class' => 'sr-only']) !!}
                            {!! Form::textarea('mymessage', null, ['class' => 'form-control', 'rows' => 8, 'cols' => 3, 'placeholder' => 'Message']) !!}
                            <i class="fa fa-pencil form-control-feedback"></i>
                            @if($errors->has('mymessage'))
                                {{ $errors->first('mymessage') }}
                            @endif
                        </div>
                        <div class="form-group has-feedback">
                            {!! app('captcha')->display() !!}
                        </div>

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

                        {!! Form::close() !!}
                        <div class="alert alert-success" id="mail_alert" role="alert" hidden>
                            Mail Sent!
                        </div>
                         <div class="alert alert-info" id="mail_info" role="alert" hidden>
                            Mail Sending Error!
                        </div>
                    </div>
                </div>

Error message:

Failed to load resource: the server responded with a status of 401 (Unauthorized)

The problem was that I was using mailgun sandbox account hence I was only able to send mail when I use the laravel app with the auth scaffold include with the auth scaffold the app would allow as mailgun sandbox account don't send any reponse.

Solution was to use regular gmail send it and it responded as expected and the mail went through.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM