控制器:UserController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class UserController extends Controller {
public function insertform() {
return view('contact-us');
}
public function enq()
{
$name = $this->input->post('name');
$phone = $this->input->post('phone');
$email = $this->input->post('email');
$msg = $this->input->post('msg');
$data=array('name'=>$name,"phone"=>$phone,"email"=>$email,"msg"=>$msg);
DB::table('enquiry')->insert($data);
echo "Record inserted successfully";
}
}
查看:Contact-us.blade.php
<script>
$(document).ready(function(){
$("#submit").click(function(e){
e.preventDefault();
name = $("#name").val();
phone = $("#phone").val();
email = $("#email").val();
msg = $("#msg").val();
$.ajax({
type:"POST",
data:{"name":name,"phone":phone,"email":email,"msg":msg},
url:"/enq",
success:function(data){
$("#success").html(data);
}
});
});
});
</script>
<div id="success"></div>
<form method="post">
<input type="text" placeholder="Your Name" name="name" id="name">
<input type="text" placeholder="Phone Number" name="phone" id="phone">
<input type="text" placeholder="Email Adress" name="email" id="email">
<textarea placeholder="Massege" name="msg" id="msg"></textarea>
<input type="submit" name="submit" id="submit" value="submit now" class="btn-blue">
</form>
web.php
<?php
Route::get('contact-us', function () {
return view('contact-us');
});
Route::post('enq','UserController@enq');
我是laravel的新手,在这里,我要在数据库中插入一个简单的表单值。现在,当我单击“提交”按钮时,什么都没有显示。我对此一无所知。那么,我该怎么做?请帮助我。
谢谢
答案 0 :(得分:1)
更改您的enq函数
public function enq(Request $request)
{
$name = $request->name;
$phone = $request->phone;
$email = $request->email;
$msg = $request->msg;
$data=array('name'=>$name,"phone"=>$phone,"email"=>$email,"msg"=>$msg);
DB::table('enquiry')->insert($data);
echo "Record inserted successfully";
}
并配置CSRF令牌
添加
<meta name="_token" content="{!! csrf_token() !!}"/>
在您的头部
然后
$.ajaxSetup({
headers:
{'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')}
});
在您的ajax调用之前添加此代码
答案 1 :(得分:0)
在ajax请求中添加其他数据,令牌。
$.ajax({
type:"POST",
data:{"name":name,"phone":phone,"email":email,"msg":msg,"_token":"{{csrf_token()}}"},
url:"{{URL::to('enq')}}",
success:function(data){
$("#success").html(data);
}
});