gpt4 book ai didi

javascript - Laravel 5.5 中使用 AJAX 提交表单

转载 作者:行者123 更新时间:2023-12-03 00:37:53 26 4
gpt4 key购买 nike

我正在尝试在 Laravel 5.5 中使用 ajax 提交表单问题是页面正在刷新并且没有向数据库提交数据。我需要将数据存储在数据库中而不刷新页面。
这是我的代码:

Controller

public function new_timing_table(Request $request)
{
if (Request::ajax()) {
$timing_tables = new Timing_Table;
$timing_tables->timing_tables_name = $request->timing_tables_name;
$timing_tables->save();
$msg = "yes";
} else {
$msg = "yes";
}
return ['msg'=> $msg];
}

查看

<form id="timeForm" class="form-horizontal form-material" >                                                                      
<div class="form-group">
{{ csrf_field() }}
<div class="col-md-12 m-b-20">
<label> Table Name</label>
<input type="text" id="timing_tables_name" class="form-control"
name="timing_tables_name" />
</div>
<div class="modal-footer">
<input type="button" value="Replace Message" id='btnSelector'>
</div>
</div>
</form>

Ajax 脚本

const xCsrfToken = "{{ csrf_token() }}";
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': xCsrfToken
}
});


jQuery(document).ready(function() {
jQuery('#btnSelector').click(function(e) {
event.preventDefault();
getMessage();
});
});
var getMessage = function() {
var timing_tables_name = $("input[name=timing_tables_name]").val();
$.ajax({
type: 'post',
url: '/new_timing_table',
dataType: 'json', //Make sure your returning data type dffine as json
data: timing_tables_name,
//data:'_token = <php echo csrf_token() ?>',
success: function(data) {
console.log(data); //Please share cosnole data
if (data.msg) //Check the data.msg isset?
{
$("#msg").html(data.msg);
}
}
});
}

路由器

 Route::post('/new_timing_table','Timing_TableControoler@new_timing_table');

最佳答案

您的脚本中有拼写错误或错误。

jQuery('#btnSelector').click(function(e){
// An error here - it should be e.preventDefault();
event.preventDefault();
getMessage();
});

关于javascript - Laravel 5.5 中使用 AJAX 提交表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53583908/

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