phpjqueryajaxlaravel

Send data to controller via Ajax


I am new to Ajax and I am using Laravel, now I want to have a delete button that will send the id of the item that I want to delete to controller. Here is my code:

Views

      <div class="row">
        @foreach($photos as $photo)
     <div class="col-xs-3 col-md-1">
    <button onclick="removeItem({{$photo->id}}); return false;">Delete</button>   
          </div> 
          @endforeach

        </div>

Here is my script for now, I don't have an idea on this:

     <script type="text/javascript">
    function removeItem($myvar) {
        alert($myvar);
    }
    </script>

I want to send this to this route:

       Route::post('deletephoto','GamefarmsController@deletephoto');

Solution

  • You need to perform an XMLHTTPRequest to the server via AJAX. Since you are using a jQuery as javascript library, such request is easy using functions like post or ajax.

    your HTML/template:

    <button class="my_button" id="{{$photo->id}}" data-url="{{path('deletephoto')}}">Delete</button>
    

    So, inside your javascript function, use something like:

    function removeItem() {
    
         $('button.my_button').click(function(e){
                e.preventDefault();     
                var url = $(this).attr('data-url');
            var id = $(this).attr('id');
            $.ajax({
                                type: "POST",
                                url: url,
                                data: {id:id},
                                cache: false,
                                success: function(data){
    
                                }
                                });
    
            return false;
           });
    
        }
    

    In details: We add a data attribute to your HTML button that would contain your path, If you are using Twig as templating engine, you can write something like:

    data-url={{path('path_delete')}}
    

    But it depends on your template engine and laravel way of routing.

    Then using the attr() jQuery function onclick on your button:

    var url = $(this).attr('data-url');
    

    You can apply the same rule to get your id.

    Finally, you should write a controller that will get the POST request with the id parameter and perform deletion. You can get your id from the request object inside controller, something like:

    if($request->isXmlHttpRequest())
          {
    $id = (int)$request->request->get('id');
    
    }