javascript - Laravel & Ajax - Insert data into table without refreshing - Stack Overflow

First of all, I have to say that I'm beginner with using Ajax... So help me guys.I want to insert

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

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

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

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

Share Improve this question edited Feb 2, 2017 at 12:22 harunB10 asked Feb 2, 2017 at 11:50 harunB10harunB10 5,22716 gold badges75 silver badges115 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 1

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

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.

EDIT

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

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

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

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

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

So:

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

I would also change the id to something clearer.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744737078a4590814.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信