Saturday, March 11, 2017

Laravel 5.2 HTML is returned instead of JSON

I am having trouble with ajax. I want to retrieve all the records of a certain table so i have this ajax call:

$('#chooseInvBtn').on('click', function(){
            $.ajax({
                type: "POST",
                url : "admin/officer_data",
                data: { _token: $('#csrf-token').val() },
                dataType : "json",
                success : function(data){
                    if(Object.keys(data).length > 0) {


                    }
                },
                error : function(xhr, status){
                    console.log(xhr);
                    console.log(status);
                }
            });
        });

With this, I get 200 ok parseerror. But when I change json datatype to html datatype, it does not return any error anymore. Unfortunately I need json to retrieve the data. This is what I have in my controller:

$officers_list = Officer::all();

        //Convert data to array
        $officers = array();

        foreach ($officers_list as $officer)
        {
            $officers['OfficerID'] = $officer->OfficerID;
            $officers['OfficerName'] = $officer->ORank . ' ' . $officer->OFirstName . ' ' . $officer->OMiddleName . ' ' . $officer->OLastName;
            $officers['Photo'] = isset($officer->OPhoto) ? $officer->OPhoto : "";
            $officers['ContactNumber'] = isset($officer->OContactNumber) ? $officer->OContactNumber : "";
        }

        return Response::json($officers);

This is also how I did it with other ajax calls. But I don't know why there is an error this time.



via Friency Fernandez

Advertisement