Tuesday, March 7, 2017

Laravel 5: Request data is null when using an Ajax Post Request

I have some problems with receiving data when using an ajax call to EDIT my data. I'm trying to get data that the user has filled in but every time my data is empty or 'null'. Do i need to pass data in ajax call? Or are there other ways in laravel to get the data?

My code at the moment as we speak:
showuser.blade.php

    <div class="comments">
    @if(count($user->cars))
        <h1>Auto in reparatie</h1>
        <hr>
        @foreach($user->cars as $car)
        <!-- Form to show each car and edit / delete the cars -->
            <!--<form action="" method="POST">-->
            <form>
                <div class="form-group">
                    <label for="brand">Merk:</label><br>
                    <select name="brand">
                        @foreach($brands as $brand)
                            <option value=""></option>
                        @endforeach
                    </select>
                </div>
                <div class="form-group">
                    <label for="year">Bouwjaar:</label><br>
                    <input type="text" value="" name="year">
                </div>
                <div class="form-group">
                    <label for="licentsplate">Kenteken:</label><br>
                    <input type="text" value="" name="licenseplate">
                </div>
                <div style="float: left; width: 80px">
                    <input type="submit" class="btn btn-primary" value="Edit" id="" name="editcar" />
                </div>
            </form>
            <form>
                <div class="form-group">
                    <button class="btn btn-primary" name="deletecar" id="">Delete</button>
                </div>
            </form>
        @endforeach
    @endif
</div>

Script

<script type="text/javascript">
    $( document ).ready(function() {
        $('[name="editcar"]').click(function (e){
            e.preventDefault();
            $.ajax({
                type: "POST",
                url: '/users//cars/'+this.id,
                success:function(data){
                    if(!data.error){
                      location.reload(true);
                    }
                }
            })
        });
    });
</script>

Routes

 Route::post('/users/{userId}/cars/{carId}', 'CarController@edit');

CarController.php

    // Function to edit a car by ID
public function edit($userId, $carId)
{
    $car = Car::where('id', $carId)->where('user_id', $userId)->first();
    $car->brand_id = request('brand');
    dd(request('year'));
    $car->year = request('year');
    $car->licensplate = ('licenseplate');
    $car->save();
}

If I dump and die request('brand'), request('year'), request('licenseplate') i get 'null'.

EDIT: If I dd $car in my controller, i get the car that i need. Means that there is no problemen finding the right car.

Thx for reading!



via Koen van de Sande

Advertisement