'How can I send JSON data from local storage to controller in Laravel?

I want to send the json data from view to controller using ajax. How can I achieve that?

The data in local storage is

[{"productId":2,"productCost":"630","productQty":"3"}]

Ajax

  function saveData(){
    const localStorageData=localStorage.getItem('myItems');
    $.ajax({
        headers: {
               'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
              },
                method:"POST",
                url: "{{route('user.plan.insertData')}}",
                dataType: "json",
                data:{localStorageData:localStorageData,
                },
                success:function(data){

                     alert(data);

                }
           });
}

Controller

    function insertData(Request $request)
{
    $localStorageData = $request->input('localStorageData');
    print_r($localStorageData);exit;
}


Solution 1:[1]

correct your ajax like this :

    data:{
        localStorageData: localStorageData,
        '_token' : '{{ csrf_token() }}'
    },

and also change the controller like this :

$localStorageData = $request->localStorageData;

remember to add @csrf inside (at the beggining) the form tag.

  • it depends on that what localStorageData really is. Depends on it, you can work with it. if it is a string , no problem but if it is an array, you should do different thing ...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ali Safaei