Laravel 5: Returning Eloquent Model Object as an Ajax Response

I am trying to return an Eloquent Model Object as an Ajax Response that i get from search process and i want to pass it to the view.

JS

$(document).ready( function() {

    $(".client_search_option").change(function(){

        var selectedClientTypeVal = "";
        var selectedSmsDecisionVal = "";

        var selectedClientType = $('input[type=radio][name=clientType]:checked');
        var selectedSmsDecision = $('input[type=radio][name=sms_decision]:checked');

        if (selectedClientType.length > 0) {
            selectedClientTypeVal = selectedClientType.val();
        }

        if (selectedSmsDecision.length > 0) {
            selectedSmsDecisionVal = selectedSmsDecision.val();
        }

        //alert(selectedClientTypeVal);
        //alert(selectedSmsDecisionVal);

        var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
        $.ajax({
            url: 'http://localhost/pages/clientSearchAjax',
            type: 'POST',
            data: {_token: CSRF_TOKEN, selectedClientTypeVal:selectedClientTypeVal,selectedSmsDecisionVal:selectedSmsDecisionVal},
            dataType: 'JSON',
            success: function (data) {
                console.log(data);
            },
            error:function(){
                alert("An error has occured !");
            }         
        });
    });
});

Contoller

public function clientSearch(){
    $client_option = Input::get('selectedClientTypeVal');
    $sms_option = Input::get('selectedSmsDecisionVal');

    if($client_option == 'all' && $sms_option == 'all'){
        $ajax_clients = Client::with('clientType')->paginate(5);
    }else{
        $ajax_clients = Client::with('clientType')->where('clienttype_id', $client_option)->where('send_sms', $sms_option)->paginate(5);
    }

    return $ajax_clients->toJson();
}

I am sure that $ajax_client object is not null, i test it and i am able to get data from database but when i want to pass it to the view(or console) it shows up like undefined. How can pass it to the view(or console) and get the values of model’s columns. Any help would be appreciated.


Source: ajax

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.