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

NickCourage's avatar

How can I use AJAX to get a list of records in the view for a jQuery array?

I'm trying to populate a jQuery array with the values from a column of a table. I tried:

var dataTitle = {!! json_encode(array_column($dataTitles->toArray(), 'my_data_title')) !!}

I now want to use ajax to do this. I've created a route that references a function in the controller and returns the data in JSON:

    public function getDataTitles(){

        $dataTitles = DataTitle::all();

        return response()->json(['data' => $dataTitles]);


    }

I've create the route for it to use as the URL parameter and have tried:

url = "{{route('get-data-titles')}}";

$.ajax({
    url: url,
    type:'get',
    dataType:'json',
    success:function (response) {

        console.log(data)
    }
})     

but am getting nothing. I've spent some time trying to Google and search for similar examples I can use but so far haven't found anything

0 likes
4 replies
jlrdw's avatar
      
     return response()->json($dataTitles);

Use those browser developer tools to help troubleshoot I constantly use them especially with Ajax.

Make sure the URL is correct. Etc.

NickCourage's avatar

@jlrdw thank you - it didn't solve it for me but I don't think I would have cracked it without that point in the right direction. I got there with:

        url = "{{route('test')}}";

        $.ajax({
            url: url,
            type:'get',
            dataType:'json',
            success:function (data) {
                
                $.each(data, function (index, item) {
                
                    return dataTitle = item.map(function(item){ return item; });

                }) 

            }
        });

and was then able to access them based on the selection of a dropdown by accessing dataTitle.

Thanks!

Please or to participate in this conversation.