如何使用Laravel中的Ajax调用将数据发布到数据库?

时间:2021-08-16 01:43:23

I have a subscribe box :

我有一个订阅框:

如何使用Laravel中的Ajax调用将数据发布到数据库?

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

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 Ajax call 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

<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');


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调用实现此目的?

2 个解决方案

#1


1  

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');

你可以在没有斜线的情况下做到这一点。路线::后( '订阅', '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.

如果有Ajax请求,请在检查中删除die。

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.

很确定表格很好。

#2


1  

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 really wants to do that, you can't stop them since they can (with a little work) spoof any request.

这种AJAX检测的唯一好处是防止用户直接从浏览器访问AJAX URL。而且,最终,如果有人真的想这样做,你就无法阻止他们,因为他们可以(通过一点点工作)欺骗任何请求。

#1


1  

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');

你可以在没有斜线的情况下做到这一点。路线::后( '订阅', '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.

如果有Ajax请求,请在检查中删除die。

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.

很确定表格很好。

#2


1  

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 really wants to do that, you can't stop them since they can (with a little work) spoof any request.

这种AJAX检测的唯一好处是防止用户直接从浏览器访问AJAX URL。而且,最终,如果有人真的想这样做,你就无法阻止他们,因为他们可以(通过一点点工作)欺骗任何请求。