TheSolarwin's avatar

Can not get object values from JSON array

Hi! I am stuck for hours, maybe someone can give an advice. I receive a response with JSON like this, but I can't access object values. It shows undefined. I tried to loop through the array of objects in many ways, but without success.

JSON response:

[{"id":1047,"school":null,"teacher_name_surname":"John Deere","date":"2021-09-05"},{"id":1048,"school":null,"teacher_name_surname":"John Deere","date":"2021-09-06"}]

Blade:

    <script>
        $(document).ready(function(){
            var _token = $('input[name="_token"]').val();
            //fetch_data();
            function fetch_data(from= '', to='')
            {
                $.ajax({
                    url:"{{ route('show-stats-in-range') }}",
                    method: "POST",
                    data:{from:from, to:to, _token:_token},
                    datatype:"json",
                    success:function (data){
                        var output = '';
                            for (var count = 0; count < data.length; count++) {
                                output += '<tr>';
                                output += '<td>' + data[count].first_score + '</td>';
                                output += '<td>' + data[count].second_score + '</td>';
                                output += '<td>' + data[count].id + '</td></tr>';

                            }

                        $('tbody').html(output);
                    }
                });
            }

Controller:

    public static function getSurveysStatsInDateRange(Request $request)
    {
        if ($request->ajax()) {
            if ($request->from != '' && $request->to != '') {
                $surveys = Survey::whereBetween('date', [$request->from, $request->to])->get();

            } else {
                $surveys = Survey::orderBy('id', 'ASC')->get();
            }
        }
        echo json_encode($surveys);
    }
0 likes
13 replies
jlrdw's avatar

From a previous example a while back:

   $data = '[{  
   "id":18296, "pro_number":232231, "driver":"Bettale", "tractor":null, "dateTime":"2018-08-27 07:00:00", "ShipperCustomerName":"ELECTROLUX HOME PRODUCTS", "ConsigneeCustomerName":"LINN STAR", "ShipperName":null, "ConsigneeName":null
},
{  
    "id":18298, "pro_number":232233, "driver":"Bettale", "tractor":null, "dateTime":"2018-08-28 07:00:00", "ShipperCustomerName":"ELECTROLUX HOME PRODUCTS", "ConsigneeCustomerName":"LINN STAR", "ShipperName":null, "ConsigneeName":null
}]';
        $loads = json_decode($data, true);
        $keys = array_keys($loads);
        for ($i = 0; $i < count($loads); $i++) {
            foreach ($loads[$keys[$i]] as $key => $value) {
                echo $key . " : " . $value . "<br>";
            }
        }

Just example, adjust to blade or js loop as needed.

Edit:

Your data output:

=================================
id : 1047
school :
teacher_name_surname : John Deere
date : 2021-09-05
=================================
id : 1048
school :
teacher_name_surname : John Deere
date : 2021-09-06

Also it's easier to use a server fetched partial here: Just suggestion.

https://laracasts.com/series/javascript-techniques-for-server-side-developers

JS would be like:

                   for (var i = 0; i < data.length; i++)
                    {
                        var item = data[i];
                        alert(item.id + " " + item.school ..........  etc);
                        //   example only
                    }
                },
2 likes
TheSolarwin's avatar

@jlrdw Thank you. Maybe a silly question, but how could i adjust this to javascript if i would like to stick with ajax?

jlrdw's avatar

@TheSolarwin I adjusted answer, the

                   for (var i = 0; i < data.length; i++)
                    {
                        var item = data[i];
                        alert(item.id + " " + item.school ..........  etc);
                        //   example only
                    }
                },

is in JS.

Edit, you probably need a get request if retrieving data to display.

Edit 2: Don't forget to use your network tab to assist you.

TheSolarwin's avatar

@jlrdw Thank you for your tiem, but it looks like there is something tricky here. :)

console.log(data.length);
//returns "10799"

and if i try to get any of values using your example it still shows undefined. Sorry i didn't understand the last sentence about get request.

tykus's avatar

@TheSolarwin is data a String rather than JSON? What does your code actually look like now?

1 like
TheSolarwin's avatar

@tykus data is a string.

here is ajax part of blade file:

                $.ajax({
                    url:"{{ route('show-stats-in-range') }}",
                    method: "POST",
                    data:{from:from, to:to, _token:_token},
                    datatype:"json",
                    success:function (data){
                        var output = '';
                        console.log(data);
                            for (var count = 0; count < 5; count++) {
                                var item = data[count];
                                console.log(data.teacher_name_surname);
                                //undefined
                                console.log(data.length);
                                //10779
                                console.log(typeof(data));
                                //string
                                
                                output += '<tr>';
                                output += '<td>' + item.id + '</td>';
                                output += '<td>' + item.teacher_name_surname + '</td>';
                                output += '<td>' + item.date + '</td></tr>';
                            }
                        $('tbody').html(output);
                    }
                });

controller:

    public static function getSurveysStatsInDateRange(Request $request)
    {
        if ($request->ajax()) {
            if ($request->from != '' && $request->to != '') {
                $surveys = Survey::whereBetween('date', [$request->from, $request->to])->get();

            } else {
                $surveys = Survey::orderBy('id', 'ASC')->get();
            }
        }
        //return Response::json($surveys);
             //returns error 500 network tab

        echo json_encode($surveys);
             //returns normal json response in network tab
    }
tykus's avatar

@TheSolarwin the Response facade should be either imported

use Response;

or resolved from the global namespace.

\Response::json($surveys);

Generally, we use the response() helper method instead.

return response()->json($surveys);

Why is data a String?

2 likes
jlrdw's avatar
jlrdw
Best Answer
Level 75

You are using POST, you need GET. And use your network tab.

And use

return Response::json($surveys);

Follow laravel conventions.

1 like
TheSolarwin's avatar

@jlrdw if i change method from "POST" to "GET" in ajax, it doesn't work.

return Response::json($surveys);

returns this:

{
    "message": "Class 'App\Http\Controllers\Response' not found",
    "exception": "Error",
    "file": "/var/www/html/vipapp/app/Http/Controllers/SurveyController.php",
    "line": 298,
    "trace": [
        {
            "file": "/var/www/html/vipapp/vendor/laravel/framework/src/Illuminate/Routing/Controller.php",
            "line": 54,
            "function": "getSurveysStatsInDateRange",
            "class": "App\Http\Controllers\SurveyController",
            "type": "::"
        },
        {
            "file": "/var/www/html/vipapp/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php",
            "line": 45,
            "function": "callAction",
            "class": "Illuminate\Routing\Controller",
            "type": "->"
        },
        {
            "file": "/var/www/html/vipapp/vendor/laravel/framework/src/Illuminate/Routing/Route.php",
            "line": 254,
            "function": "dispatch",
            "class": "Illuminate\Routing\ControllerDispatcher",
            "type": "->"
        },
        {
            "file": "/var/www/html/vipapp/vendor/laravel/framework/src/Illuminate/Routing/Route.php",
            "line": 197,
            "function": "runController",
            "class": "Illuminate\Routing\Route",
            "type": "->"
        },
        {
            "file": "/var/www/html/vipapp/vendor/laravel/framework/src/Illuminate/Routing/Router.php",
            "line": 695,
            "function": "run",
            "class": "Illuminate\Routing\Route",
            "type": "->"
        },
        {
            "file": "/var/www/html/vipapp/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
            "line": 128,
            "function": "Illuminate\Routing\{closure}",
            "class": "Illuminate\Routing\Router",
            "type": "->"
        },
        {
            "file": "/var/www/html/vipapp/app/Http/Middleware/IsAdmin.php",
            "line": 21,
            "function": "Illuminate\Pipeline\{closure}",
            "class": "Illuminate\Pipeline\Pipeline",
            "type": "->"
        },
        {
            "file": "/var/www/html/vipapp/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
            "line": 167,
            "function": "handle",
            "class": "App\Http\Middleware\IsAdmin",
            "type": "->"
        },
        {
            "file": "/var/www/html/vipapp/vendor/laravel/framework/src/Illuminate/Auth/Middleware/EnsureEmailIsVerified.php",
            "line": 30,
            "function": "Illuminate\Pipeline\{closure}",
            "class": "Illuminate\Pipeline\Pipeline",
            "type": "->"
        },
        {
            "file": "/var/www/html/vipapp/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
            "line": 167,
            "function": "handle",
            "class": "Illuminate\Auth\Middleware\EnsureEmailIsVerified",
            "type": "->"
        },
        {
            "file": "/var/www/html/vipapp/vendor/laravel/framework/src/Illuminate/Routing/Middleware/SubstituteBindings.php",
            "line": 50,
            "function": "Illuminate\Pipeline\{closure}",
            "class": "Illuminate\Pipeline\Pipeline",
            "type": "->"
        },
        {
            "file": "/var/www/html/vipapp/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
            "line": 167,
            "function": "handle",
            "class": "Illuminate\Routing\Middleware\SubstituteBindings",
            "type": "->"
        },
        {
            "file": "/var/www/html/vipapp/vendor/laravel/framework/src/Illuminate/Auth/Middleware/Authenticate.php",
            "line": 44,
            "function": "Illuminate\Pipeline\{closure}",
            "class": "Illuminate\Pipeline\Pipeline",
            "type": "->"
        },
        {
            "file": "/var/www/html/vipapp/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
            "line": 167,
            "function": "handle",
            "class": "Illuminate\Auth\Middleware\Authenticate",
            "type": "->"
        },
        {
            "file": "/var/www/html/vipapp/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php",
            "line": 78,
            "function": "Illuminate\Pipeline\{closure}",
            "class": "Illuminate\Pipeline\Pipeline",
            "type": "->"
        },
        {
            "file": "/var/www/html/vipapp/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
            "line": 167,
            "function": "handle",
            "class": "Illuminate\Foundation\Http\Middleware\VerifyCsrfToken",
            "type": "->"
        },
        {
            "file": "/var/www/html/vipapp/vendor/laravel/framework/src/Illuminate/View/Middleware/ShareErrorsFromSession.php",
            "line": 49,
            "function": "Illuminate\Pipeline\{closure}",
            "class": "Illuminate\Pipeline\Pipeline",
            "type": "->"
        },
        {
            "file": "/var/www/html/vipapp/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
            "line": 167,
            "function": "handle",
            "class": "Illuminate\View\Middleware\ShareErrorsFromSession",
            "type": "->"
        },
        {
            "file": "/var/www/html/vipapp/vendor/laravel/framework/src/Illuminate/Session/Middleware/AuthenticateSession.php",
            "line": 58,
            "function": "Illuminate\Pipeline\{closure}",
            "class": "Illuminate\Pipeline\Pipeline",
            "type": "->"
        },
        {
            "file": "/var/www/html/vipapp/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
            "line": 167,
            "function": "handle",
            "class": "Illuminate\Session\Middleware\AuthenticateSession",
            "type": "->"
        },
        {
            "file": "/var/www/html/vipapp/vendor/laravel/framework/src/Illuminate/Session/Middleware/StartSession.php",
            "line": 121,
            "function": "Illuminate\Pipeline\{closure}",
            "class": "Illuminate\Pipeline\Pipeline",
            "type": "->"
        },
        {
            "file": "/var/www/html/vipapp/vendor/laravel/framework/src/Illuminate/Session/Middleware/StartSession.php",
            "line": 64,
            "function": "handleStatefulRequest",
            "class": "Illuminate\Session\Middleware\StartSession",
            "type": "->"
        },
        {
            "file": "/var/www/html/vipapp/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
            "line": 167,
            "function": "handle",
            "class": "Illuminate\Session\Middleware\StartSession",
            "type": "->"
        },
        {
            "file": "/var/www/html/vipapp/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/AddQueuedCookiesToResponse.php",
            "line": 37,
            "function": "Illuminate\Pipeline\{closure}",
            "class": "Illuminate\Pipeline\Pipeline",
            "type": "->"
        },
        {
            "file": "/var/www/html/vipapp/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
            "line": 167,
            "function": "handle",
            "class": "Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse",
            "type": "->"
        },
        {
            "file": "/var/www/html/vipapp/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/EncryptCookies.php",
            "line": 67,
            "function": "Illuminate\Pipeline\{closure}",
            "class": "Illuminate\Pipeline\Pipeline",
            "type": "->"
        },
        {
            "file": "/var/www/html/vipapp/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
            "line": 167,
            "function": "handle",
            "class": "Illuminate\Cookie\Middleware\EncryptCookies",
            "type": "->"
        },
        {
            "file": "/var/www/html/vipapp/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
            "line": 103,
            "function": "Illuminate\Pipeline\{closure}",
            "class": "Illuminate\Pipeline\Pipeline",
            "type": "->"
        },
        {
            "file": "/var/www/html/vipapp/vendor/laravel/framework/src/Illuminate/Routing/Router.php",
            "line": 697,
            "function": "then",
            "class": "Illuminate\Pipeline\Pipeline",
            "type": "->"
        },
        {
            "file": "/var/www/html/vipapp/vendor/laravel/framework/src/Illuminate/Routing/Router.php",
            "line": 672,
            "function": "runRouteWithinStack",
            "class": "Illuminate\Routing\Router",
            "type": "->"
        },
        {
            "file": "/var/www/html/vipapp/vendor/laravel/framework/src/Illuminate/Routing/Router.php",
            "line": 636,
            "function": "runRoute",
            "class": "Illuminate\Routing\Router",
            "type": "->"
        },
        {
            "file": "/var/www/html/vipapp/vendor/laravel/framework/src/Illuminate/Routing/Router.php",
            "line": 625,
            "function": "dispatchToRoute",
            "class": "Illuminate\Routing\Router",
            "type": "->"
        },
        {
            "file": "/var/www/html/vipapp/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php",
            "line": 166,
            "function": "dispatch",
            "class": "Illuminate\Routing\Router",
            "type": "->"
        },
        {
            "file": "/var/www/html/vipapp/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
            "line": 128,
            "function": "Illuminate\Foundation\Http\{closure}",
            "class": "Illuminate\Foundation\Http\Kernel",
            "type": "->"
        },
        {
            "file": "/var/www/html/vipapp/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php",
            "line": 21,
            "function": "Illuminate\Pipeline\{closure}",
            "class": "Illuminate\Pipeline\Pipeline",
            "type": "->"
        },
        {
            "file": "/var/www/html/vipapp/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/ConvertEmptyStringsToNull.php",
            "line": 31,
            "function": "handle",
            "class": "Illuminate\Foundation\Http\Middleware\TransformsRequest",
            "type": "->"
        },
        {
            "file": "/var/www/html/vipapp/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
            "line": 167,
            "function": "handle",
            "class": "Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull",
            "type": "->"
        },
        {
            "file": "/var/www/html/vipapp/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php",
            "line": 21,
            "function": "Illuminate\Pipeline\{closure}",
            "class": "Illuminate\Pipeline\Pipeline",
            "type": "->"
        },
        {
            "file": "/var/www/html/vipapp/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TrimStrings.php",
            "line": 40,
            "function": "handle",
            "class": "Illuminate\Foundation\Http\Middleware\TransformsRequest",
            "type": "->"
        },
        {
            "file": "/var/www/html/vipapp/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
            "line": 167,
            "function": "handle",
            "class": "Illuminate\Foundation\Http\Middleware\TrimStrings",
            "type": "->"
        },
        {
            "file": "/var/www/html/vipapp/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/ValidatePostSize.php",
            "line": 27,
            "function": "Illuminate\Pipeline\{closure}",
            "class": "Illuminate\Pipeline\Pipeline",
            "type": "->"
        },
        {
            "file": "/var/www/html/vipapp/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
            "line": 167,
            "function": "handle",
            "class": "Illuminate\Foundation\Http\Middleware\ValidatePostSize",
            "type": "->"
        },
        {
            "file": "/var/www/html/vipapp/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/PreventRequestsDuringMaintenance.php",
            "line": 86,
            "function": "Illuminate\Pipeline\{closure}",
            "class": "Illuminate\Pipeline\Pipeline",
            "type": "->"
        },
        {
            "file": "/var/www/html/vipapp/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
            "line": 167,
            "function": "handle",
            "class": "Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance",
            "type": "->"
        },
        {
            "file": "/var/www/html/vipapp/vendor/fruitcake/laravel-cors/src/HandleCors.php",
            "line": 38,
            "function": "Illuminate\Pipeline\{closure}",
            "class": "Illuminate\Pipeline\Pipeline",
            "type": "->"
        },
        {
            "file": "/var/www/html/vipapp/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
            "line": 167,
            "function": "handle",
            "class": "Fruitcake\Cors\HandleCors",
            "type": "->"
        },
        {
            "file": "/var/www/html/vipapp/vendor/laravel/framework/src/Illuminate/Http/Middleware/TrustProxies.php",
            "line": 39,
            "function": "Illuminate\Pipeline\{closure}",
            "class": "Illuminate\Pipeline\Pipeline",
            "type": "->"
        },
        {
            "file": "/var/www/html/vipapp/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
            "line": 167,
            "function": "handle",
            "class": "Illuminate\Http\Middleware\TrustProxies",
            "type": "->"
        },
        {
            "file": "/var/www/html/vipapp/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
            "line": 103,
            "function": "Illuminate\Pipeline\{closure}",
            "class": "Illuminate\Pipeline\Pipeline",
            "type": "->"
        },
        {
            "file": "/var/www/html/vipapp/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php",
            "line": 141,
            "function": "then",
            "class": "Illuminate\Pipeline\Pipeline",
            "type": "->"
        },
        {
            "file": "/var/www/html/vipapp/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php",
            "line": 110,
            "function": "sendRequestThroughRouter",
            "class": "Illuminate\Foundation\Http\Kernel",
            "type": "->"
        },
        {
TheSolarwin's avatar

@jlrdw Thank you very much! Response::json() was the key, it works great with POST.

frankielee's avatar

"message": "Class 'App\Http\Controllers\Response' not found"

I think the error message is pretty clear.

1 like
jlrdw's avatar

@thesolarwin of course pull in any class you need, I use facade thus:

use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Response;

2 likes

Please or to participate in this conversation.