Laravel& Ajax - 将数据插入表中而不刷新

时间:2017-02-02 11:50:08

标签: javascript php jquery ajax laravel

首先,我不得不说我是初学者使用Ajax ......所以请帮助我们。 我想在不刷新页面的情况下将数据插入到数据库中。到目前为止,我有以下代码...... 在刀片中我有一个带有id的表单:

In [80]: p = np.arange(3) # for creating the indices of combinations using np.tile and np.repeat

In [81]: a = a[np.repeat(p, 3)] # creates the first column of combination array

In [82]: b = b[np.tile(p, 3)] # creates the second column of combination array

In [83]: abs(a[:, :2] - b[:, :2]).sum(1) < a[:, 2] + b[:, 2]
Out[83]: array([ True, False,  True,  True, False,  True,  True, False,  True], dtype=bool)

在控制器中我有:

 this.canvas.addEventListener('click', this.canvasClick.bind(this), false);

我正在尝试使用ajax插入数据库:

{!! Form::open(['url' => 'addFavorites', 'id' => 'ajax']) !!}

  <a href="#" id="favorite" class="bookmark"><img align="right" src="{{ asset('/img/icon_add_fav.png')}}"></a>
  <input type="hidden" name = "idUser" id="idUser" value="{{Auth::user()->id}}">
  <input type="hidden" name = "idArticle" id="idArticle" value="{{$docinfo['attrs']['sid']}}">
  <input type="submit" id="test" value="Ok">

{!! Form::close() !!}

同样在我的public function addFavorites() { $idUser = Input::get('idUser'); $idArticle = Input::get('idArticle'); $favorite = new Favorite; $favorite->idUser = $idUser; $favorite->idArticle = $idArticle; $favorite->save(); if ($favorite) { return response()->json([ 'status' => 'success', 'idUser' => $idUser, 'idArticle' => $idArticle]); } else { return response()->json([ 'status' => 'error']); } } 我有一条添加收藏夹的路线。但是当我提交表单时,它会返回我这样的JSON响应: $('#ajax').submit(function(event){ event.preventDefault(); $.ajax({ type:"post", url:"{{ url('addFavorites') }}", dataType="json", data:$('#ajax').serialize(), success: function(data){ alert("Data Save: " + data); } error: function(data){ alert("Error") } }); }); ...它实际上插入到数据库中,但我希望页面不要重新加载。只是为了显示警告框。

4 个答案:

答案 0 :(得分:1)

正如@sujivasagam所说,它正在进行常规的后期行动。尝试用这个替换你的javascript。我也认识到了一些语法错误,但在此处进行了更正。

$("#ajax").click(function(event) {
    event.preventDefault();

    $.ajax({
        type: "post",
        url: "{{ url('addFavorites') }}",
        dataType: "json",
        data: $('#ajax').serialize(),
        success: function(data){
              alert("Data Save: " + data);
        },
        error: function(data){
             alert("Error")
        }
    });
});

您只需将<input type="submit">替换为<button>,而您可能不会需要event.preventDefault()来阻止该表单发布。

修改

以下是使用javascript获取和发布评论的示例。

(function() {

    // Loads items into html
    var pushItemsToList = function(items) {
        var items = [];

        $.each(items.data, function(i, item) {
            items.push('<li>'+item.title+'</li>');
        });

        $('#the-ul-id').append(items.join(''));
    }

    // Fetching items
    var fetchItems = function() {
        $.ajax({
            type: "GET",
            url: "/items",
            success: function(items) {
                pushItemsToList(items);
            },
            error: function(error) {
                alert("Error fetching items: " + error);
            }
        });
    }

    // Click event, adding item to favorites
    $("#ajax").click(function(event) {
        event.preventDefault();

        $.ajax({
            type: "post",
            url: "{{ url('addFavorites') }}",
            dataType: "json",
            data: $('#ajax').serialize(),
            success: function(data){
                  alert("Data Save: " + data);
            },
            error: function(data){
                 alert("Error")
            }
        });
    });

    // Load items (or whatever) when DOM's loaded
    $(document).ready(function() {
        fetchItems();
    });
})();

答案 1 :(得分:0)

您正在使用通常提交表单的按钮类型“提交”。因此,将其作为按钮,然后单击该调用ajax函数

答案 2 :(得分:0)

将您的按钮类型更改为type="button"并添加onclick动作onclick =“yourfunction()”。并把ajax放在你的功能中。

答案 3 :(得分:0)

用按钮替换输入类型并生成onClick侦听器。确保在onclick监听器中使用此输入ID:

所以:

$('#test').on('click', function(event){
  event.preventDefault()
  ... further code

我还会将内容更改为更清晰的内容。

相关问题