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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42001499/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:15:04  来源:igfitidea点击:

Laravel & Ajax - Insert data into table without refreshing

javascriptphpjqueryajaxlaravel

提问by harunB10

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:

首先,我不得不说我是使用 Ajax 的初学者......所以帮帮我吧。我想在不刷新页面的情况下将数据插入数据库。到目前为止,我有以下代码...在刀片中,我有一个带有 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() !!}

And in controller I have:

在控制器中我有:

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

I'm trying with ajax to insert into database:

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

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

Also in my web.phpI 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.

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

采纳答案by Rikard Olsson

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.

正如@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")
        }
    });
});

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.

您可以只替换为<input type="submit"><button>并且您可能不需要event.preventDefault()这会阻止表单发布。

EDIT

编辑

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

这是一个仅根据评论中的要求使用 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();
    });
})();

回答by Onix

Change your button type to type="button"and add onclick action onclick="yourfunction()". and just put ajax inside your funciton.

将您的按钮类型更改为type="button"并添加 onclick 操作 onclick="yourfunction()"。只需将 ajax 放入您的功能中。

回答by DekiChan

Replace input type with button and make onClick listener. Make sure you use this input id in onclick listener:

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

So:

所以:

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

I would also change the id to something clearer.

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

回答by sujivasagam

You are using button type "Submit" which usually submit the form. So make that as button and on click of that call the ajax function

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