如何在 Laravel 中使用 Ajax 调用将数据发布到数据库?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30106698/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to post data to database using Ajax call in Laravel?
提问by cyber8200
I have a subscribe box :
我有一个订阅框:
My goal is when the user enter the email, I want to save it to my database.
我的目标是当用户输入电子邮件时,我想将其保存到我的数据库中。
I already know how to achieve this using form post via Laravel.
我已经知道如何通过 Laravel 使用表单发布来实现这一点。
Form POST via Laravel
通过 Laravel 表单 POST
public function postSubscribe() {
// Validation
$validator = Validator::make( Input::only('subscribe_email'),
array(
'subscribe_email' => 'email|unique:subscribes,email',
)
);
if ($validator->fails()) {
return Redirect::to('/#footer')
->with('subscribe_error','This email is already subscribed to us.')
->withErrors($validator)->withInput();
}else{
$subscribe = new Subscribe;
$subscribe->email = Input::get('subscribe_email');
$subscribe->save();
return Redirect::to('/thank-you');
}
}
Now, I want to achieve this using Ajaxcall to avoid the page load and also to learn more about Ajax. Here are what I've tried :
现在,我想使用Ajax调用来避免页面加载并了解有关 Ajax 的更多信息。这是我尝试过的:
Form
形式
{!! Form::open(array('url' => '/subscribe', 'class' => 'subscribe-form', 'role' =>'form')) !!}
<div class="form-group col-lg-7 col-md-8 col-sm-8 col-lg-offset-1">
<label class="sr-only" for="mce-EMAIL">Email address</label>
<input type="email" name="subscribe_email" class="form-control" id="mce-EMAIL" placeholder="Enter email" required>
<!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
<div style="position: absolute; left: -5000px;"><input type="text" name="b_168a366a98d3248fbc35c0b67_73d49e0d23" value=""></div>
</div>
<div class="form-group col-lg-3 col-md-4 col-sm-4"><input type="submit" value="Subscribe" name="subscribe" id="subscribe" class="btn btn-primary btn-block"></div>
{!! Form::close() !!}
Ajax Call
Ajax 调用
<script type="text/javascript">
$(document).ready(function(){
$('#subscribe').click(function(){
$.ajax({
url: '/subscribe',
type: "post",
data: {'subscribe_email':$('input[name=subscribe_email]').val(), '_token': $('input[name=_token]').val()},
dataType: 'JSON',
success: function (data) {
console.log(data);
});
});
});
</script>
Controller
控制器
public function postSubscribeAjax() {
// Getting all post data
if(Request::ajax()) {
$data = Input::all();
die;
}
dd($data);
}
Route
路线
Route::post('/subscribe','SubscribeController@postSubscribeAjax');
Route::post('/subscribe','SubscribeController@postSubscribeAjax');
Result
结果
I keep getting:
我不断得到:
Undefined variable: data
未定义变量:数据
Which mean my Request::ajax()
is not containing anything? Why is that?
这意味着我Request::ajax()
的不包含任何东西?这是为什么?
How can I achieve this using an Ajax call?
如何使用 Ajax 调用实现此目的?
采纳答案by Cayce K
This was resolved in Chat
这已在聊天中解决
We had to fix a couple syntax errors and change the input button to a html button so that it would prevent the form from submitting. There are other ways we could have done this, but this worked.
我们不得不修复一些语法错误并将输入按钮更改为 html 按钮,以防止表单提交。我们还有其他方法可以做到这一点,但这是有效的。
So I'm going to address a few things here. Starting from bottom moving on up!!
所以我将在这里解决一些问题。从下往上走!!
Route
路线
You can do this without the slash.
Route::post('subscribe','SubscribeController@postSubscribeAjax');
您可以不使用斜线执行此操作。
Route::post('subscribe','SubscribeController@postSubscribeAjax');
Controller
控制器
Your Controller is good enough, but you need to actually display the result from the ajax. We will handle that.
您的控制器已经足够好了,但是您需要实际显示 ajax 的结果。我们会处理的。
Remove the die
in your check if there is an Ajax request.
die
如果有 Ajax 请求,请删除检查中的 。
Ajax
阿贾克斯
<script type="text/javascript">
$(document).ready(function(){
$('#subscribe').click(function(e){
e.preventDefault(); // this prevents the form from submitting
$.ajax({
url: '/subscribe',
type: "post",
data: {'subscribe_email':$('input[name=subscribe_email]').val(), '_token': $('input[name=_token]').val()},
dataType: 'JSON',
success: function (data) {
console.log(data); // this is good
}
});
});
});
</script>
Form
形式
Pretty sure the form is good.
很确定形式是好的。
回答by Kryten
Assuming the "Undefined variable" error is happening in your postSubscribeAjax
method, it looks like you have a problem with scope. Specifically, when the PHP interpreter gets to the line dd($data)
, the variable $data
has not been defined yet.
假设您的postSubscribeAjax
方法中发生了“未定义的变量”错误,看起来您的范围有问题。具体来说,当 PHP 解释器到达该行时dd($data)
,变量$data
尚未定义。
This is not surprising, since $data
is assigned inside the block of code following an if
statement - it is not available outside that block.
这并不奇怪,因为它是$data
在if
语句之后的代码块内分配的- 它在该块之外不可用。
You can solve this problem by adding $data = null;
before the if
statement, BUT... this is only going to show you that you have a different problem. Here's why:
您可以通过$data = null;
在if
语句前添加来解决此问题,但是...这只会向您表明您遇到了不同的问题。原因如下:
You're getting an "undefined variable" error. The means that your code is skipping the if
block (how do I know this? because if it didn't skip it, it would execute the die
statement and you'd never see the error). This means that your code is not correctly identifying the request as an AJAX request.
您收到“未定义变量”错误。这意味着您的代码正在跳过该if
块(我怎么知道这一点?因为如果它没有跳过它,它将执行该die
语句并且您永远不会看到错误)。这意味着您的代码没有正确地将请求识别为 AJAX 请求。
What I would do is this: skip the if
block entirely. Simply get your data and process it.
我会做的是:if
完全跳过该块。只需获取您的数据并对其进行处理即可。
It's been a while since I looked at this stuff, but IIRC, there is no reliable way to detect AJAX requests. To the server, an AJAX request is just like any other request. Some Javascript libraries (jQuery included, if I'm not mistaken) set a header on the request to identify it as AJAX, but it is neither universally required nor universally detected.
自从我看这些东西已经有一段时间了,但是 IIRC,没有可靠的方法来检测 AJAX 请求。对于服务器来说,AJAX 请求就像任何其他请求一样。一些 Javascript 库(包括 jQuery,如果我没记错的话)在请求上设置了一个标头以将其标识为 AJAX,但它既不是普遍需要的,也不是普遍检测到的。
The only benefit to this AJAX detection is to prevent your users from accessing the AJAX URL directly from a browser. And, ultimately, if someone reallywants to do that, you can't stop them since they can (with a little work) spoof any request.
这种 AJAX 检测的唯一好处是防止您的用户直接从浏览器访问 AJAX URL。并且,最终,如果有人真的想这样做,您无法阻止他们,因为他们可以(通过一点工作)欺骗任何请求。
回答by Vikas Katariya
Please pass csrf token
请传递 csrf 令牌
<script type="text/javascript">
$(document).ready(function(){
$('#subscribe').click(function(e){
e.preventDefault(); // this prevents the form from submitting
$.ajax({
url: '/subscribe',
type: "post",
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
},
data: {'subscribe_email':$('input[name=subscribe_email]').val(), '_token': $('input[name=_token]').val()},
dataType: 'JSON',
success: function (data) {
console.log(data); // this is good
}
});
});
});
</script>