Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ponnydalen's avatar

Load data from checkboxes array ajax

Hello. Building a booking form where I've got 3 checkboxes. I display them by loop trough the db table(it's only 3 results in table and will always be)

@foreach($services as $service)
<label class="py-4 col-md-12 cursor-pointer checkbox_label_div">
    <div class="custom-control custom-checkbox">
        <input type="checkbox" class="custom-control-input services" value="{{ $service['id']}}" name="service_id[]">
        <label class="custom-control-label">{{$service->name}}</label>
        <span class="float-right"> {{$service->price}}</span>
    </div>
</label>
@endforeach

Table(services) looks like this

id  	- name  	- price  - description 
1   	- Charging 	- 250	 - Charging of electric car
2	- Wheelchange 	- 350 	 - Change tires
3	- Heating 	- 280	 - Heating of car

My ajax request:

function loadData() {

    var serviceValue = [];
        $('.services:checked').each(function(){
            serviceValue.push($(this).val());
    })

    //  Hmmm....
    // serviceValue = JSON.stringify(serviceValue)

    $.ajax({
        url: "{{ route('get.data') }}",
        type: 'GET',
        dataType: 'json',
        data: {
            _token: $("input[name='_token']").val(),
            service: serviceValue

        },
        success: function(data) {
           
            var html = `<li class="list-group-item lh-condensed">
                            <div class="d-flex justify-content-between">
                                <span> Here the name should be </span>
                                <span class="text-muted"> Here the price should be </span>
                            </div>
                        </li>
                        `;

            $.each( data.service, function(){
                if(data.service) {
                    $(".display_services").append(html)
                }
                else{
                    $(".display_services").remove(html)
                }
                
            });
        }
    });
};

And controller (trait) I ask for each of the services that matches the id's in the array adn then load into controller

//Trait

public function calculateService (Request $request) 
    {

        $services = Service::whereIn('id', $request->service ?: [])->get();

        $item = [];
        
        $services->each(function ($item) {
            $services  = ([
                'price' => $item->price,
                'name' => $item->name,
            ]);
        });

        return json_encode($services);
    
    }

//Controller

function getData(Request $request) 
    {

        $data = ([
            'service' => json_decode($this->calculateService($request)),

        ]);

        return response()->json($data);
    }

I get this result response (when all 3 are chekced) :

service: [{id: 1, created_at: "2020-10-08T23:33:28.000000Z", updated_at: "2020-10-08T23:33:28.000000Z",…},…]
0: {id: 1, created_at: "2020-10-08T23:33:28.000000Z", updated_at: "2020-10-08T23:33:28.000000Z",…}
1: {id: 2, created_at: "2020-10-08T23:33:28.000000Z", updated_at: "2020-10-08T23:33:28.000000Z",…}
2: {id: 3, created_at: "2020-10-08T23:34:22.000000Z", updated_at: "2020-10-08T23:34:22.000000Z",…}

So..I get the data I need yes and in my success function I do this

      success: function(data) {
           
            var html = `<li class="list-group-item lh-condensed">
                            <div class="d-flex justify-content-between">
                                <span> Here the name should be </span>
                                <span class="text-muted"> Here the price should be </span>
                            </div>
                        </li>
                        `;

            $.each( data.service, function(){
                if(data.service) {
                    $(".display_services").append(html)
                }
                else{
                    $(".display_services").remove(html)
                }
                
            });
        }

The list items is getting added in the summary box so it's working BUT three questions.

  1. How can I remove the item if I uncheck the checkbox because .remove() does not work.
  2. How can I put the price and name data from the controller into that html ?
  3. Do I make this very much harder than it actually is? Other solutions? I know there is only 3 checkboxes and I can do it manually by just hide and show each list item, but I want to know how it is done this way. (if there was example 1000 records).

Thanks for reading. Andreas.

0 likes
1 reply
thewebartisan7's avatar

In controller the problem seem to be here:

 $services->each(function ($item) {
            $services  = ([
                'price' => $item->price,
                'name' => $item->name,
            ]);
        });

You are doing strange thing here, can you see?

On JS side your success method should looks something like:


 if(data.service) {

            $.each( data.service, function(item){
               
                    $(".display_services").append(
`<li class="list-group-item lh-condensed">
                            <div class="d-flex justify-content-between">
                                <span>${item.name}</span>
                                <span class="text-muted">${item.price}</span>
                            </div>
                        </li>`
)
                }
            });

                else{
                    $(".display_services").html('')
                }

I can't see the whole picture of your code, but there are several way to do this, and can be improved.

Maybe try to solve firstly how you can and in case you have some question, create new question, making it more specific.

Please or to participate in this conversation.