Monday, March 13, 2017

(Laravel) How can I return a variable to the .blade.php view with AJAX?

When the user changes the category with the select field, I want to only show the requests with that category on the view--and to do this using an AJAX request. I want to pass the object that is being returned from the Controller to AJAX's success handler into the view (the $requests variable as seen in the code below), and for the view to update the requests shown.

The data is being returned to AJAX's success handler correctly as I can console.log the object, but it doesn't update the $requests variable.

How do I achieve this, and what am I missing here?

The view that shows the requests from the DB

@extends('layouts.app')

@section('content')


<div class="container">
    <div class="row requests-row">
        <div class="col-md-12">
            <h2>New requests</h2>
            <select name="category" class="form-control category">
                <option value="" disabled selected>Choose a category...</option>
                <option value="Electronics and Computers">Electronics and Computers</option>
                <option value="Hardware">Hardware</option>
            </select>
            <hr>
            <p class="block"></p>
            @foreach ($requests as $request)
                @include('components.requests')
            @endforeach
        </div>
    </div>
</div>

@endsection

The AJAX Request

$('.category').change(function() {
    $.ajax({
        method: "GET",
        url: "/category",
        data: $(this).serialize(),
        success: function(data) {
            console.log(data);
            return data;
        },
        error: function(data){
            console.log("Error: " + data);
        },
    });
});

The controller on the backend that handles the AJAX request

public function changeCategory(Request $request)
{
    $posts = Post::where('category', $request->category)->get();
    return $posts;
}



via Jonas Anker Jahr

Advertisement