gpt4 book ai didi

php - 如何使用 laravel 通过 jquery ajax 将表单值插入数据库?

转载 作者:行者123 更新时间:2023-11-29 07:21:38 25 4
gpt4 key购买 nike

Controller :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>

网络.php

<?php
Route::get('contact-us', function () {
return view('contact-us');
});
Route::post('enq','UserController@enq');

我是 laravel 的新手 我在做什么 我将向数据库中插入一个简单的表单值。现在,当我点击提交按钮时会发生什么,它什么也没显示。我对此一无所知。那么,我该怎么做呢?请帮助我。

谢谢

最佳答案

改变你的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 token

添加 <meta name="_token" content="{!! csrf_token() !!}"/>在你的头部

然后

 $.ajaxSetup({
headers:
{'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')}
});

在您的 ajax 调用之前添加此代码

关于php - 如何使用 laravel 通过 jquery ajax 将表单值插入数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56020720/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com