JSON inválido, porém meu JSON é válido!!

JSON inválido, porém meu JSON é válido!!

GilbertoASJGilbertoASJ Posts: 13Questions: 3Answers: 0

Hi all.

I'm on a Laravel project, and I have the following situation:

I have the route /transactions that show my home screen, and I have the route /transactions/list, which your duty is to populate the DataTable through a JSON, so far ok, what happens is that it DOESN'T matter what I do(do seriously have tried everything), I have no success! My main idea is to popularize the datatable with data coming from the database, but I can't even get dummy data from a data.json file..

So I'll first talk about the current state with a dummy file, because if I can't even use it, let alone pull files from the database...

Come on... If in the "url": "...", from Ajax I put the direct path to the data.json file, a datatables is populated, but when in the Controller, I try to return this file I don't with me, the most intriguing thing of all, is that this function is being heard, but there is no error return, and please don't ask me to see the site http://datatables.net/tn/1, as I said already, no error is returned, then I'll send the codes for the files, because I use the datatable a little myself and I don't know if something is missing or if I have any wrong information....

web.php -Route file:

<?php

use Illuminate\Foundation\Application;
use Illuminate\Support\Facades\Route;
use Inertia\Inertia;
use App\Http\Controllers\TransactionsController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return Inertia::render('Welcome', [
        'canLogin' => Route::has('login'),
        'canRegister' => Route::has('register'),
        'laravelVersion' => Application::VERSION,
        'phpVersion' => PHP_VERSION,
    ]);
});

Route::get('/dashboard', function () {
    return Inertia::render('Dashboard');
})->middleware(['auth', 'verified'])->name('dashboard');


Route::resource('transactions', TransactionsController::class)->only('index', 'show')->middleware(['auth', 'verified']);
Route::get('transactions/list', [TransactionsController::class, 'list'])->middleware(['auth', 'verified'])->name('transactions.list');


require __DIR__.'/auth.php';

app.blade.php file - Where the datatable is used:

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title inertia>{{ config('app.name', 'Laravel') }}</title>

    <link rel="icon" href="https://user-images.githubusercontent.com/56325350/132005897-aba20f38-8eff-480c-8f4d-e21408678dd1.png">

    <!-- Jquery -->
    <script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>

    <!-- Datatable -->
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.0/css/dataTables.bootstrap5.min.css">
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.1/css/bootstrap.min.css">
    <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.11.0/js/jquery.dataTables.js"></script>
    <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.11.0/js/dataTables.bootstrap5.min.js"></script>

    <!-- Styles -->
    <link rel="stylesheet" href="{{ mix('css/app.css') }}">
    <style>
        body {
            font-family: 'Poppins', sans-serif !important;
            font-size: .835rem !important;
            background: #eef0f8 !important;
        }

        .btn-light-primary {
            background-color: #e1e9ff !important;
            border-color: transparent;
            color: #6993ff !important;
            font-size: 0.9rem;

        }
        .btn-light-primary:hover,
        .btn-light-primary:focus,
        .btn-light-primary:active {
            background-color: #6993ff !important;
            border-color: transparent;
            color: #FFF !important;
        }  
        
    </style>

    <!-- Scripts -->
    @routes
    <script src="{{ mix('js/app.js') }}" defer></script>

    <script>
        $(document).ready(function() {
            // DataTable - Tabela de transações e histórico
            $('#example').DataTable({
                language: {
                    url: 'https://cdn.datatables.net/plug-ins/1.11.1/i18n/pt_br.json'
                },
                ajax: {
                    url: '{{ route("transactions.list") }}',
                    dataSrc: '00000000',
                },
                columns: [
                    { "data": "Tipo" },
                    { "data": "Sequencial" },
                    { "data": "Placa" },
                    { "data": "Status" },
                    { "data": "Retorno" },
                    { "data": "Data" },
                    {
                        sortable: false,
                        "render": function ( data, type, full, meta ) {
                            var buttonID = "details_"+full.id;
                            return `<button 
                                        id="${buttonID}"
                                        type="button" 
                                        data-bs-toggle="modal" 
                                        data-bs-target="#exampleModal" 
                                        class="btn btn-light-primary"
                                    >
                                        Detalhes
                                    </button>
                            `
                        }
                    },
                ]
            });

            $('#historic-table').DataTable({
                language: {
                    url: 'https://cdn.datatables.net/plug-ins/1.11.1/i18n/pt_br.json'
                }
            });

        } );
    </script>
</head>
<body class="font-sans antialiased">
    @inertia
</body>
</html>

TransactionsController file, which uses the list function:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginRequest;
use App\Providers\RouteServiceProvider;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
use Inertia\Inertia;
use App\Models\transaction;

class TransactionsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {

        return Inertia::render('Transactions/Index')->withViewData(['teste' => 'Teste']);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

    /**
     * Return the TransactionList to DataTables
     *
     *  @param  int  $id
     *  @return \Illuminate\Http\Response
     */
    public function list()
    {

        $json = file_get_contents("http://localhost/valid-repos/renavam-serpro/resources/views/data.json");

        return $json;

            
    }
}

data.json - JSON valid!!

{
  "data": [
    {
      "id": "1",
      "Tipo": "233 - Envio",
      "Sequencial": "084774",
      "Placa": "PDC-0A00",
      "Status": "Sucesso",
      "Retorno": "5421",
      "Data": "2011/04/25 14:00:00"
    },
    {
      "id": "2",
      "Tipo": "233 - Envio",
      "Sequencial": "084774",
      "Placa": "PDC-0A00",
      "Status": "Sucesso",
      "Retorno": "8422",
      "Data": "2011/07/25 14:00:00"
    }
  ]
}

PRINTS:::::::

This question has an accepted answers - jump to answer

Answers

  • colincolin Posts: 15,112Questions: 1Answers: 2,583

    Have you followed the steps in the technical notes linked to in the error? That'll be the place to start,

    Colin

  • GilbertoASJGilbertoASJ Posts: 13Questions: 3Answers: 0

    Hi Colin, yes I followed the step by step :(

  • allanallan Posts: 61,438Questions: 1Answers: 10,052 Site admin

    Can you use the debugger to give me a trace please - click the Upload button and then let me know what the debug code is.

    Allan

  • GilbertoASJGilbertoASJ Posts: 13Questions: 3Answers: 0

    Hi Allan, and now?

  • allanallan Posts: 61,438Questions: 1Answers: 10,052 Site admin

    Thank you - the debugger shows me that the response from the server to the request to "http://localhost/renavam-serpro/public/transactions/list" is empty. That is indeed invalid JSON, which is why you are getting the error you are.

    What were you expecting it to return? Perhaps check your server's error logs to see if there is an error reported there.

    Allan

  • GilbertoASJGilbertoASJ Posts: 13Questions: 3Answers: 0

    Oh, and now? The table loads the records but they don't appear

  • allanallan Posts: 61,438Questions: 1Answers: 10,052 Site admin

    The debugger says an error occurred - unfortunately I can't see a trace because of that. I'd need an actual link to your web-page.

    Allan

  • GilbertoASJGilbertoASJ Posts: 13Questions: 3Answers: 0
    edited September 2021

    The page here's in localhost :open_mouth:

    My code:

    $('#example').DataTable({
    language: {
    url: 'https://cdn.datatables.net/plug-ins/1.11.1/i18n/pt_br.json'
    },
    ajax: {
    url: URL_BASE+'transactions/list',
    type: 'GET',
    "dataSrc": "",
    },
    columns: [
    {"data":"id"},
    {"data":"Tipo"},
    {"data":"Sequencial"},
    {"data":"Placa"},
    {"data":"Status"},
    {"data":"Retorno"},
    {"data":"Data"},
    ],
    });

  • kthorngrenkthorngren Posts: 20,141Questions: 26Answers: 4,736

    Above you indicate the JSON looks like this:

    {
      "data": [
        {
          "id": "1",
          "Tipo": "233 - Envio",
          "Sequencial": "084774",
          "Placa": "PDC-0A00",
          "Status": "Sucesso",
          "Retorno": "5421",
          "Data": "2011/04/25 14:00:00"
        },
        {
          "id": "2",
          "Tipo": "233 - Envio",
          "Sequencial": "084774",
          "Placa": "PDC-0A00",
          "Status": "Sucesso",
          "Retorno": "8422",
          "Data": "2011/07/25 14:00:00"
        }
      ]
    }
    

    Is that still the case? Use the browser's network inspector to see the actual response. If the row data is in the data object then remove the "dataSrc": "", so that Datatables will look for rows in the data object.

    Kevin

  • GilbertoASJGilbertoASJ Posts: 13Questions: 3Answers: 0

    With dataSrc="", response in inspector is;

    \"{\r\n \\"data\\": [\r\n {\r\n \\"id\\": \\"1\\",\r\n \\"Tipo\\": \\"233 - Envio\\",\r\n \\"Sequencial\\": \\"084774\\",\r\n \\"Placa\\": \\"PDC-0A00\\",\r\n \\"Status\\": \\"Sucesso\\",\r\n \\"Retorno\\": \\"5421\\",\r\n \\"Data\\": \\"2011\\/04\\/25 14:00:00\\"\r\n },\r\n {\r\n \\"id\\": \\"2\\",\r\n \\"Tipo\\": \\"233 - Envio\\",\r\n \\"Sequencial\\": \\"084774\\",\r\n \\"Placa\\": \\"PDC-0A00\\",\r\n \\"Status\\": \\"Sucesso\\",\r\n \\"Retorno\\": \\"8422\\",\r\n \\"Data\\": \\"2011\\/07\\/25 14:00:00\\"\r\n } }

  • kthorngrenkthorngren Posts: 20,141Questions: 26Answers: 4,736

    That is not valid JSON. You can use https://jsonlint.com/ to validate the JSON.

    I'm not familiar with PHP but it looks like this function is used to return the data:

        public function list()
        {
     
            $json = file_get_contents("http://localhost/valid-repos/renavam-serpro/resources/views/data.json");
     
            return $json;
     
                 
        }
    

    I would start by validating the contents of data.json with the jsonllint site. Maybe the file_get_contents() function is adding the extra \r\n and escaping the quotes (\\"). It looks like the data is JSON encoded twice. Maybe when the server script returns the response it is encapsulating the data.json data a second time.

    Kevin

  • GilbertoASJGilbertoASJ Posts: 13Questions: 3Answers: 0
    edited September 2021

    Ok, now I have valid JSON? But response in datatable is empty :(

  • kthorngrenkthorngren Posts: 20,141Questions: 26Answers: 4,736

    Did you remove the `"dataSrc": "", that I suggested before?

    Kevin

  • GilbertoASJGilbertoASJ Posts: 13Questions: 3Answers: 0

    Yeah, I removed now, but now:

  • kthorngrenkthorngren Posts: 20,141Questions: 26Answers: 4,736
    edited September 2021 Answer ✓

    According to the information element there are 78 rows. Is that correct?

    Right click on one of the rows then select Inspect. You should see the HTML for the tr and td for the rows displayed on the page. Do the rows have data in them, something like this?

    <td class="sorting_1" tabindex="0" style="outline: none;">Bradley Greer</td>

    Make sure you don't have styling applied that might be making the data invisible like color, transparency, etc

    Kevin

  • GilbertoASJGilbertoASJ Posts: 13Questions: 3Answers: 0

    After receiving the valid JSON as a response, and removing the dataSrc, it was the last way I showed, what happens is that I had to put the dataSrc="data", that way I was able to list the fictitious data, thanks a lot

Sign In or Register to comment.