weixin_33712987 2016-11-05 14:56 采纳率: 0%
浏览 35

在laravel 5.3中使用Ajax

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)
  • 写回答

1条回答 默认 最新

  • weixin_33733810 2016-11-06 05:39
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题