2

I have some problems while coding in Laravel, in particular with passing data to a modal (bootstrap framework) and passing data to an Ajax post request. I have an array of items with an 'id', a 'name' and a 'content', that are retrieved from database and passed to the view. Below are the controller code and the view:
Controller:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;


class SiteController extends Controller
{    
    public function index(){
    
    $items = App\Items::all();

    return view('home', compact('items'));
    }
}


View (index.blade.php)

@foreach ($items as $item)
<div class="panel panel-default">
  <div class="panel-heading">
    <h3 class="panel-title">{{ $item->name }}</h3>
  </div>
  <div class="panel-body">
    {{ $item->content }}
    <a href="#" role="button" class="delete_btn" data-item_id="{{ $item->id }}" data-item_name="{{ $item->name }}" class="btn btn-default">Delete</a>
  </div>
</div>
@endforeach

When I click on the 'button' Delete, it will shows a modal. Below the code:

<div id="modal" class="modal fade" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title">Delete item</h4>
      </div>
      <div class="modal-body">
        <p>Are you sure to delete item <strong id="item_name"></strong>?</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button id="delete_btn_modal" type="button" class="btn btn-danger" data-item_id="is passed by js">Delete</button>
      </div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

To pass data (item id and item name) to the modal I use the following javascript code, which is in another file included in the layout. In the code I update the modal data finding the id of field that has to be updated (in this case 'item_name' and 'delete_btn_modal'). Here I have the first problem: the modal will show always the name of the first item.
Javascript code (functions.js):

$('.delete_btn').on('click', function (event) {
  var a = $('delete_btn')
  var item_name = a.data('item_name')
  var item_id = a.data('item_id')
  
  var modal = $('#modal')
  modal.find('#item_name').text(item_name)
  modal.find('#delete_btn_modal').attr('data-item_id',item_id)
  modal.modal('show');
});

So I try to simulate the click on 'Delete'. I need to send an ajax post request to the controller, which will delete the item from database. Below is my ajax code:

$.ajaxSetup({
    headers: {
    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
    });
    
        $('.delete_btn_modal').click(function(e) {
            e.preventDefault();
            var btn = $('.delete_btn_modal');
            var item_id = btn.data('item_id');
      
            var url = "/item";
            var $data = {};
            $data.item_id = item_id;
            $.ajax({
            type: "POST",
            url: url,
            data: $data,
            cache: false,
            success: function(data){
                console.log(data)
                return data;
            }
            });
            return false;
        });

And below is the ItemController code, in which data passed from ajax request are pushed in the console log:
ItemController code:

    public function destroy(Request $request)
    {
        if ($request->ajax()){
            $item_id = $request->item_id;
          return "The item's ID is: ".$item_id;
        }
    }

And there's the second problem: the ajax post request will pass always the id of the first item. I tried to figure out what elements could cause these problems, without success. Sorry if I wrote too much, but I preferred be accurate.
Hoping this isn't a stupid question, thank you in advice.

2 Answers 2

1

I think var item = btn.data('item_id');, in your ajax setup file, should be var item_id = btn.data('item_id');.

Furthermore, you have an error in your functions.js. It should be:

$('.delete_btn').on('click', function (event) {
  var a = $(this);
  var item_name = a.data('item_name')
  var item_id = a.data('item_id')

  var modal = $('#modal')
  modal.find('#item_name').text(item_name)
  modal.find('#delete_btn_modal').attr('data-item_id',item_id)
  modal.modal('show');
});

You were assigning $('.delete_btn') to a. This will select all elements with class .delete_btn. If you later try to retrieve data from a, it will retrieve the data from the first element in the list. That is why you always got the the results for the first element. this instead refers to the specific element of the link that was clicked. That is where you are trying to get your data from.

Sign up to request clarification or add additional context in comments.

2 Comments

Unfortunately no, the modal still not updating and the ajax post request still passing only the first item data.
Thank you so much, it works now. So where is '$('.delete_btn')' and '$('.delete_btn_modal')' is to change in '$(this)'.
0

You have to call $(this) not $(.class-name) because it will get the first item of the returned array which have all the items with class attr equal to class-name

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.