0

I make a ajax call on click button and then send the array data to the controller. So this is the ajax call:

const saveBtnOnClick = () => {
        //e.preventDefault();
        loopMarker(poly);
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            url: "{{ route('storeRouteMap') }}",
            type: 'POST',
            data: {markers: markers},
            success: function (response) {
                console.log(response);
            },
            error: function (response) {
                console.log("Error " + response);
            }
        })
    }

And the data passing in payload developer tools looks like this:

markers[0][lat]: 3.2845171928345853
markers[0][long]: 101.8885194254942
markers[0][sequence]: 0
markers[0][route_id]: 5
markers[1][lat]: 3.591580368128944
markers[1][long]: 102.5367127848692
markers[1][sequence]: 1
markers[1][route_id]: 5

In the controller:

public function store(Request $request): JsonResponse
{
    $out = new ConsoleOutput();
    $routeMaps = $request->all();

    $out->writeln($routeMaps[1]['long']);

    try{
        foreach($routeMaps as $key=>$value){
            $out->writeln($value['lat']);
            $out->writeln($value['long']);
            $out->writeln($value['sequence']);
            $out->writeln($value['route_id']);
        }

But $out->writeln($value['lat']) gives error, Undefined array key 'lat' and $out->writeln($routeMaps[1]['long']) gives error, Undefined array key 1; So how did this array structured for me to iterate?

1 Answer 1

2

You are passing data in form of key value i.e. markers: markers. So your request parameter in controller would be like: $request->markers. You need to iterate through $request->markers.

$routeMaps = $request->markers;

foreach($routeMaps as $key => $value){
   $out->writeln($value['lat']);
   $out->writeln($value['long']);
   $out->writeln($value['sequence']);
   $out->writeln($value['route_id']);
}

Hopefully this would work :)

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

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.