JSON inválido, porém meu JSON é válido!!
JSON inválido, porém meu JSON é válido!!
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
Have you followed the steps in the technical notes linked to in the error? That'll be the place to start,
Colin
Hi Colin, yes I followed the step by step
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
Hi Allan, and now?
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
Oh, and now? The table loads the records but they don't appear
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
The page here's in localhost
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"},
],
});
Above you indicate the JSON looks like this:
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 thedata
object.Kevin
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 } }
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:
I would start by validating the contents of
data.json
with the jsonllint site. Maybe thefile_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 thedata.json
data a second time.Kevin
Ok, now I have valid JSON? But response in datatable is empty
Did you remove the `"dataSrc": "", that I suggested before?
Kevin
Yeah, I removed now, but now:
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
andtd
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
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