Laravel Ajax将数据发布到数据库中

时间:2015-09-27 18:11:33

标签: jquery ajax laravel-5

This is my index.php

    <div class="container">
    <h1>Drink A Coffee today</h1> <hr>
       <h2>Coffee Orders</h2>
    <ul id="orders">
    <p><li class="highlight"></li></p>
    <p><li class="highlight"></li></p>
    </ul>

    <h4>Add a Coffee Order</h4>

    {!! Form::open(['url' => 'index', 'method' => 'POST']) !!}
     <div class="form-group" role="form">
    <p>
        <label for="name">Name:</label>
        <input id="name" type="text" name="name" class="form-control">
    </p>

    <p>
        <label for="drink">Drink:</label>
        <input id="drink" type="text" name="drink" class="form-control">
    </p>
    <p>
        <button id="add-order" class="btn btn-default" type="submit">Add!</button>
    </p>
</div>
{!! Form::close() !!}
</div>

以下是我的控制器

public function makeOrder() {
      $post = Request::all();

      if (Request::ajax()) {
        $order = new Order;

        $order->name = $post['name'];
        $order->drink = $post['drink'];

        $order->save();
        $response = array(
        'status' => 'success',
        'msg' => 'Option created successfully',
        );

        return Response::json( $response );
      }
    }

//Below is my Route

Route::post('index', 'MakeOrderController@makeOrder');

然后是我的Ajax脚本

$(document).ready(function() {

    $('#add-order').click(function(e) {
        e. preventDefault();
        //setting variables based on the input fields
        var inputName = $('input[name="name"]').val();
        var inputDrink = $('input[name="drink"]').val();
        var token = $('input[name="_token"]').val();
        var data = {name:inputName, drink:inputDrink, token:token};

        var request = $.ajax({

            url: "index",
            type: "POST",
            data: data,
            dataType:"html"
            });

            request.done(function( msg ) {
                var response = JSON.parse(msg);
                console.log(response.msg);
            });

            request.fail(function( jqXHR, textStatus ) {
                console.log( "Request failed: " + textStatus );
            });
        });



});

但是当我尝试提交时,没有任何事情发生,当我检查元素时,我收到此错误&#34;无法加载资源:服务器响应状态为500(内部服务器错误) 请求失败:错误&#34;

1 个答案:

答案 0 :(得分:0)

啊,我想我现在看到了。在你的AJAX数据中,你发送'令牌',但是Laravel期望这个参数被命名为'_token'。

您可以通过在表单上使用jQuery的serialize()函数来简化自己,而不是将每个字段检索为变量。例如:

var data = $(this).closest('form').serialize();

而不是var inputName,var inputDrink等