1

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.

4 Answers 4

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 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();
    });
})();
Sign up to request clarification or add additional context in comments.

6 Comments

It's working, but only for the first item (article). On my page I have several articles shown (using Laravel blade's foreach) and each of them have button for adding to favorites. Like I've said, it works only for the first item (inserts into db and render alert box) in articles list.
First of all, it's not good practice to try and combine (as I now see that you do) Blade and Javascript by dynamically changing the FE. I would try to fetch your items through Ajax as well. If you still want to use like you're doing, then try to find some code to insert a new row in the list with javascript
How do you mean to fetch items through Ajax?
You do a get request and adding the result to your list dynamically. I could give you an example in my answer, I just have to update it
Please... Because I'm struggling with this for a couple of hours... :)
|
0

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

2 Comments

I've tried now to add onClick to button, but nothing new happens... Same issue.
Use <button onClick="fnFunction()"> <script> function fnFunction(arg) { $.ajax({ type: "POST", url: {{url}}, dataType: "json", success: function(response){ } }); } </script>
0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.