如何使用AJAX和php Laravel发送联系表单而不刷新页面

时间:2018-02-19 15:17:14

标签: php jquery ajax laravel laravel-5

我使用Laravel 5.5和Mailtrap.io创建了一个联系表单。但是,我试图让联系表单发送而不重新加载页面来执行此操作我正在使用AJAX。但是,我不知道如何将AJAX与Laravel和Mailtrap.io连接。

这是我创建的表格。

@if(Session::has('success'))
<p class="alert {{ Session::get('alert-class', 'success') }}">{{ Session::get('success') }}</p>
@endif
<form action="{{ url('contact') }}" method="POST" class="wpcf7-form" novalidate="novalidate">
    {{ csrf_field() }}
    <div class="primary-form">
        <div class="col-xs-6">
            <span class="wpcf7-form-control-wrap text-768"><input type="text" name="first-name" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-validates-as-required" placeholder="First Name" /></span>
        </div>
        <div class="col-xs-6">
            <span class="wpcf7-form-control-wrap text-768"><input type="text" name="last-name" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-validates-as-required" aria-required="true" aria-invalid="false" placeholder="Last Name" /></span>
        </div>
        <div class="col-xs-6">
            <span class="wpcf7-form-control-wrap email-766"><input type="email" name="email" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-email wpcf7-validates-as-required wpcf7-validates-as-email" aria-required="true" aria-invalid="false" placeholder="E-mail Address" /></span>
        </div>
        <div class="col-xs-6">
            <span class="wpcf7-form-control-wrap phone"><input type="text" name="phone" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-validates-as-required" aria-required="true" aria-invalid="false" placeholder="Phone Number" /></span>
        </div>
        <div class="col-xs-12">
            <span class="wpcf7-form-control-wrap textarea-6"><textarea name="message" cols="40" rows="10" class="wpcf7-form-control wpcf7-textarea" aria-invalid="false" placeholder="Your Message"></textarea></span>
        </div>

        <div class="pull-right" style="margin-right:10px;">
            <p class="clearfix">
                <button type="submit" class="button button-simple btn-submit mt-30">SEND</button>
            </p>
        </div>
    </div>
</form>

我用来发送页面而不重新加载页面的AJAX方法。

$(".btn-submit").click(function(e){
    e.preventDefault();
    var first_name = $("input[name=first-name]").val();
    var last_name = $("input[name=last-name]").val();
    var email = $("input[name=email]").val();
    var phone = $("input[name=phone]").val();
    var bodyMessage = $("textarea[name=message]").val();

    $.ajax({
       type:'POST',
       url:'/contact',
       data:{first_name:first_name, last_name:last_name, email:email, phone:phone, bodyMessage:bodyMessage},
       success:function(data){
          alert(data.success);
       }
    });
});

这是我的ContactController。

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Post;
use Mail;
use Session;

class ContactController extends Controller
{
    public function postContact(Request $request){
        $this->validate($request, ['email' => 'required|email'] );

        $data = array(
            'first_name' => $request->first_name,
            'last_name' => $request->last_name,
            'email' => $request->email,
            'phone' => $request->phone,
            'bodyMessage' => $request->message
        );

        Mail::send('emails.contact', $data, function($message) use ($data){
            $message->from($data['email']);
            $message->to('jafar@calmcollective.co.uk');
            $message->subject('Contact Details');
        });

        Session::flash('success', 'Your E-mail was sent! Allegedly.');
        Session::flash('alert-class', 'alert-success');

        return redirect('contact');

    }
}

我花了好几个小时。任何帮助将不胜感激。

4 个答案:

答案 0 :(得分:2)

首先,表单正在重新加载,因为您在提交按钮上使用单击处理程序希望防止默认,您拥有的内容:$(".btn-submit").click(function(e),更改单击以提交:$("#form-id").submit(function(e)

其次,为什么不发送FormData对象而不是所有这些:

e.preventDefault();
    var first_name = $("input[name=first-name]").val();
    var last_name = $("input[name=last-name]").val();
    var email = $("input[name=email]").val();
    var phone = $("input[name=phone]").val();
    var bodyMessage = $("textarea[name=message]").val();

    $.ajax({
       type:'POST',
       url:'/contact',
       data:{first_name:first_name, last_name:last_name, email:email, phone:phone, bodyMessage:bodyMessage},
       success:function(data){
          alert(data.success);
       }
    });

试试这个:

e.preventDefault();
    var form = document.querySelector('#form-id');
    var data = new FormData(form);

    $.ajax({
       type:'POST',
       url:'/contact',
       data:data,
       success:function(data){
          alert(data.success);
       }
    });

在你的php中,你必须通过表单字段的名称访问变量 的修改
要清楚使用请求对象访问php脚本中的变量,请执行以下操作:$request->input('nameOfInputfield'),以数组的形式访问所有值$request->all()

答案 1 :(得分:1)

根据原始问题的回答,我发现ContactController方法的拼写错误:

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

应该是

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

然后在你的javascript中,你应该监听表单提交事件,而不仅仅是提交按钮点击事件,并将csrf_token添加到数据中:

$("form.wpcf7-form").submit(function(e){
    e.preventDefault();
    var token = $("input[name=_token]").val(); // The CSRF token
    var first_name = $("input[name=first-name]").val();
    var last_name = $("input[name=last-name]").val();
    var email = $("input[name=email]").val();
    var phone = $("input[name=phone]").val();
    var bodyMessage = $("textarea[name=message]").val();

    $.ajax({
       type:'POST',
       url:'/contact',
       dataType: 'json',
       data:{_token: token, first_name:first_name, last_name:last_name, email:email, phone:phone, bodyMessage:bodyMessage},
       success:function(data){
          alert(data.success);
       }
    });
});

最后,您应该在ContactController中返回一个success参数:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Post;
use Mail;
use Session;

class ContactController extends Controller
{
    public function postContact(Request $request){
        $this->validate($request, ['email' => 'required|email'] );

        $data = array(
            'first_name' => $request->first_name,
            'last_name' => $request->last_name,
            'email' => $request->email,
            'phone' => $request->phone,
            'bodyMessage' => $request->message
        );

        Mail::send('emails.contact', $data, function($message) use ($data){
            $message->from($data['email']);
            $message->to('jafar@calmcollective.co.uk');
            $message->subject('Contact Details');
        });

        return response()->json(['success' => 'Your E-mail was sent! Allegedly.'], 200);

    }
}

答案 2 :(得分:0)

我用jquery和jquery表单插件来做:

http://malsup.com/jquery/form/ jquery form plugin

答案 3 :(得分:0)

您可以尝试为Ajax提供属性 <!DOCTYPE html> <meta charset="utf-8"> <head> <title>Pie</title> <link href="https://fonts.googleapis.com/css?family=Lato:300" rel="stylesheet" type="text/css"> </head> <style> .container1 { width: 355px; position: absolute; flex-direction: column; font-size: 10px; } .container2 { width: 355px; position: absolute; flex-direction: column; transform: translate(400px, 0px); } .container3 { width: 355px; position: absolute; flex-direction: column; transform: translate(800px, 0px); } </style> <body> <script src="https://d3js.org/d3.v4.min.js"></script> <div class="container1" id="svg1"></div> <div class="container2" id="svg2"></div> <div class="container3" id="svg3"></div> <script> var employed1 = [{ City: 'Bradford City', Percentage: 54.63 }, { City: 'Leeds', Percentage:62.19 }, { City: 'Liverpool', Percentage: 55.62 }, { City: 'Manchester', Percentage: 60.50 }, { City: 'Sheffield', Percentage: 59.03 }]; var employed2 = [{ City: 'Brighton', Percentage: 65.29 }, { City: 'Bristol', Percentage: 66.72 }, { City: 'Luton', Percentage: 62.87 }, { City: 'Milton Keynes', Percentage: 67.80 }, { City: 'Southampton', Percentage: 67.36, }]; var unemployed1 = [{ City: 'Bradford City', Percentage: 15.52 }, { City: 'Leeds', Percentage: 6.96 }, { City: 'Liverpool', Percentage: 9.76 }, { City: 'Manchester', Percentage: 10.71 }, { City: 'Sheffield', Percentage: 5.33 }]; var unemployed2 = [{ City: 'Brighton', Percentage: 5.33 }, { City: 'Bristol', Percentage: 5.51 }, { City: 'Luton', Percentage: 8.50 }, { City: 'Milton Keynes', Percentage: 5.17 }, { City: 'Southampton', Percentage: 5.44 }]; var other3 = [{ City: 'Bradford City', Percentage: 29.85 }, { City: 'Leeds', Percentage: 30.85 }, { City: 'Liverpool', Percentage: 34.62 }, { City: 'Manchester', Percentage: 28.79 }, { City: 'Sheffield', Percentage: 33.76 }]; var other4 = [{ City: 'Bradford City', Percentage: 29.38 }, { City: 'Leeds', Percentage: 27.77 }, { City: 'Liverpool', Percentage: 28.63 }, { City: 'Manchester', Percentage: 27.03 }, { City: 'Sheffield', Percentage: 27.30 }]; const NE = ["Bradford City", "Leeds", "Liverpool", "Manchester", "Sheffield"]; var colorNE = d3.scaleOrdinal() .domain(NE) .range(["#A8A7A7", "#2F9599", "#E8175D", "#474747", "#CC527A"]); const SE = ["Brighton", "Bristol", "Luton", "Milton Keynes", "Southampton"]; var colorSE = d3.scaleOrdinal() .domain(SE) .range(["#F8B195", "#F67280", "#C06C84", "#6C5B7B", "#355C7D"]); var mentalHealthAndAlcoholPie = d3.pie() .value(function(d) { return d.Percentage }) .sort(function(a, b) { return a.City.localeCompare(b.City); }); var arcGenerator = d3.arc() .innerRadius(100) .outerRadius(135) .padAngle(.02) .padRadius(50); draw("svg1", employed1); draw("svg1", employed2); draw("svg2", unemployed1); draw("svg2", unemployed2); draw("svg3", other3); draw("svg3", other4); function draw(selector, data) { var arcData = mentalHealthAndAlcoholPie(data); var svg = d3.select("#" + selector) .append("svg") .attr("width", 1000) .attr("height", 450) .append("g") .attr("transform", "translate(200, 250)"); svg.selectAll(null) .data(arcData) .enter() .append('path') .attr("fill", function(d) { var result = null; if (NE.indexOf(d.data.name) >= 0) { result = colorNE(d.data.name); } if else (SE.indexOf(d.data.name) >= 0) { result = colorSE(d.data.name); } else { result = "white"; } return result; }) .style("stroke", "white") .attr('d', arcGenerator); svg.append("text") .selectAll('text') .data(arcData) .enter() .append('text') .each(function(d) { var centroid = arcGenerator.centroid(d); d3.select(this) .attr('x', centroid[0]) .attr('y', centroid[1]) .attr('dy', '0.30em') .text(d.label) }); } </script> </body> </html> 吗? 你应该能够获得参数。

如果你这样做了,你还需要根据ajax文档将json返回给ajax请求,就像这样:

dataType: "json"