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

Crazylife's avatar

How to pass an array to ajax and accessible in controller?

I have an array

[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24]

How can i pass this array to ajax and get it from controller?

  $(document).on('click', '#print', function(){
        var code = $(this).attr('data-code');
        $.ajax({
            type: 'GET',
            url: 'print',
            data: {code: code,option: array here},
            dataType: 'html',
            success: function (html) {
                w = window.open(window.location.href,"_blank");
                w.document.open();
                w.document.write(html);
                w.document.close();
            },
            error: function (data) {
                console.log('Error:', data);
            }
        });
    });

In controller

Input::get('option');
0 likes
7 replies
salomon022's avatar

$i = array(1,2,3,4,5,6,7,8,9,0);

$k =0;

foreach($i as $j)

{

$k = $k+1;  

}

for($n=0; $n<$k; $n++)

{

echo $i[$n];    

}

vanderb's avatar
var arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24];

...

data: {code: code, arr: arr}


MyController {

    public function ajaxRouteEndoint(Request $request) {
        
        $array = $request->get('arr');

        // Do whatever you want to do

        $html = '<h1>Boo</h1>';
        
        // Return as json
        return response()->json(['arr' => $arr, 'html' => $html]);
    }

}

success: function (response) {
    arr = response.arr;

    w = window.open(window.location.href,"_blank");
    w.document.open();
    w.document.write(response.html);
    w.document.close();
},
Crazylife's avatar

@vanderb Can i ask, is that possible to pass an array return from view1 controller to view 2 and then from view 2 pass it to another controller?

salomon022's avatar

use App\Http\otherController;

$otherController = new OtherController();

$value = $otherController->view($data);

Crazylife's avatar

@vanderb E.g. i have a dropdownlist from view1 which allow multiselect, after that using query builder to filter data based on the dropdown selection and then return to view2. In view2, i need to get the dropdown selection from view 1 for the ajax call for printing. This is why actually i want to do this.

Crazylife's avatar

I can't get it. This is how my controller function 1 look like

// this is the array get from dropdown list
 $categoryOption = Input::get('categoryOption'); 

.....

return View::make('view2')->with($categoryOption);
 

When in view2, user click a button and will call controller function 2

return View::make('view3')..;

In view2 i need to get the $categoryOption array value from function 1. How can i make it works?

Please or to participate in this conversation.