Laravel& Ajax - 将数据插入表中而不刷新 [英] Laravel & Ajax - Insert data into table without refreshing

查看:86
本文介绍了Laravel& Ajax - 将数据插入表中而不刷新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

First of all, I have to say that I'm beginner with using Ajax... So help me guys. I want to insert the data into db without refreshing the page. So far, I have following code... In blade I have a form with an id:

{!! 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']);
    }
}

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

I'm trying with ajax to insert into database:

   $('#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")
      }
   });
   });

同样在我的 web.php 我有添加收藏夹的路线。但是当我提交表单时,它会返回JSON响应,如下所示: {status:success,idUser:15,idArticle:343970} ...它实际上插入到数据库中,但我希望页面不重新加载。只是为了显示警告框。

Also in my web.php I have a route for adding favorites. But when I submit the form, it returns me JSON response like this: {"status":"success","idUser":"15","idArticle":"343970"}... It actually inserts into the db, but I want the page not to reload. Just to display alert box.

推荐答案

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

As @sujivasagam says it's performing a regular post action. Try to replace your javascript with this. I also recognized some syntax error but it is corrected here.

$("#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()阻止表单发布。

You could just replace <input type="submit"> with <button>instead and you'll probably won't be needing event.preventDefault() which prevents the form from posting.

编辑

这是一个获取和发布的示例在评论中要求的javascript。

Here's an example of getting and posting just with javascript as asked for in comments.

(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();
    });
})();

这篇关于Laravel&amp; Ajax - 将数据插入表中而不刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆