phpjsonajaxlaravellaravel-12

access form data in controller via request variable


I have a form modal and I am trying to send data using ajax post method to the controller method 'store' via my blade file.

//// temp.blade.php file

    <script type="text/javascript">
    $(document).ready(function() {

        $('#productForm').on('submit', function(e) {
            
            let data = $('#productForm').serialize();

            $.ajax({
                url: "posts",
                type: "POST",
                datatype: "json",
                data: {
                    "_token": "{{ csrf_token() }}",
                    data: data
                },
                success: function(response) //call back function
                {
                    $('#respanel').html(response);
                    $('#productForm')[0].reset();                    
                    alert(response.message);
                },
                error: function(error) {
                    console.log(error);
                    alert(error.message);
                }
            });
        });
    });
</script>

route file

//// web.php file

Route::get('posts', [PostController::class, 'index']);
Route::post('posts', [PostController::class, 'store']);

controler class::

class PostController extends Controller
{
   
    public function store(Request $request)
    {
        try {

            return response()->json([
                'status'=>200,
                'message'=> $request->data 
                ]);

             } catch (Exception $e) {
            return response()->json([
                'status'=>200,
                'message'=>$e->getMessage()
            ]);
        }

    }
   
}

When I send data as name = 'test' and detail = 'dummy-details' from my blade file, the controller store method show response as

id=&name=test&detail=dummy-details

but when I change the return response message variable to

return response()->json([
                'status'=>200,
                'message'=> $request->name // or $request->input('name')
                ]); 

the response message is null

and when I do

return response()->json([
                'status'=>200,
                'message'=> $request->all()
                ]);

it shows [object Object]

What is the problem with the data format? How to get the data from the request variable? Thank You!!!


Solution

  • You're wrapping the input data in the data field, which is why $request->name won't work since the data is within the $request->data property.

    data: { "_token": "{{ csrf_token() }}", data: data}, // here you're wrapping the input data in the data field
    

    To fix, you could simply do instead:

    data: $('#productForm').serialize(),
    

    and then you can access properties in the controller as:

    $request->name

    Note: Make sure you have @csrf tag within the form.