0

I have a Laravel route returning a JSON, and I have a JS file that dynamically generates a table with the results in a JSON. I just need to use this JSON in my JS table. That's all.

JS code (registroCarros should receive the value from the JSON, route or whatever)

function CreateTableFromJSON() {
    

    var registroCarros = []

    // EXTRAI VALOR PARA O HEADER HTML 
    var col = [];
    for (var i = 0; i < registroCarros.length; i++) {
          for (var key in registroCarros[i]) {
            if (col.indexOf(key) === -1) {
                col.push(key);
            }
        }
    }

    // CREATE TABLE 
    var table = document.createElement("table");
    table.id = 'myTable';



   
    var tr = table.insertRow(-1);                   //ROW.

    for (var i = 0; i < col.length; i++) {
        var th = document.createElement("th");      //HEADER.
        th.innerHTML = col[i];
        tr.appendChild(th);
    }

    for (var i = 0; i < col.length; i++) {
       var td1 = document.getElementsByTagName("tr");      //HEADER.
       td1.id="teste;"
   }

    // ADD JSON IN TABLE AS ROWS.
    for (var i = 0; i < registroCarros.length; i++) {

        tr = table.insertRow(-1);

        for (var j = 0; j < col.length; j++) {
            var tabCell = tr.insertCell(-1);
            tabCell.innerHTML = registroCarros[i][col[j]];
        }
    }

    
    var divContainer = document.getElementById("showData");
    divContainer.innerHTML = "";
    divContainer.appendChild(table);


    
}

My Controller (dbtest is a function in my model that have the SELECT im using):

 public function returnJSON()
    {
        $teste   = new user();
        return response()->json(($teste->dbtest()));
        
    }

and my route:

Route::get('returnJSON', 'App\Http\Controllers\Controller@returnJSON',           ['names' => 'returnJSON']);

all I need is to use this route in my JavaScript.

3 Answers 3

1

Your Controller

public function returnJSON()
{
    $teste = new user();
    return response()->json($teste->dbtest());    
}

Then your Route should look like this:

Route::get(
    'returnJSON',  // URL
    'App\Http\Controllers\Controller@returnJSON'  // Controller
)->name('returnJSON');  // Route name

Then finally in your blade file (JS code), you can use it as:

// behind any event (e.g. button click or value change etc.)
fetch("{{ route('returnJSON') }}")       // This is the route name given in your route
// OR fetch("{{ url('returnJSON') }}")   // and this is the URL (either can be used)
.then(res => res.json())
.then(data => CreateTableFromJSON(data));

/* 🔴REMEMBER */
// Your "CreateTableFromJSON" function must require an argument
// so that it can take the response (returned JSON) in it    
function CreateTableFromJSON(registroCarros = []) {
    // EXTRAI VALOR PARA O HEADER HTML 
    var col = [];
    for (var i = 0; i < registroCarros.length; i++) {
        for (var key in registroCarros[i]) {
            if (col.indexOf(key) === -1) {
                col.push(key);
            }
        }
    }

    // CREATE TABLE 
    var table = document.createElement("table");
    table.id = 'myTable';

    var tr = table.insertRow(-1);                          //ROW.

    for (var i = 0; i < col.length; i++) {
        var th = document.createElement("th");             //HEADER.
        th.innerHTML = col[i];
        tr.appendChild(th);
    }

    for (var i = 0; i < col.length; i++) {
    var td1 = document.getElementsByTagName("tr");        //HEADER.
    td1.id="teste;"
    }

    // ADD JSON IN TABLE AS ROWS.
    for (var i = 0; i < registroCarros.length; i++) {

        tr = table.insertRow(-1);

        for (var j = 0; j < col.length; j++) {
            var tabCell = tr.insertCell(-1);
            tabCell.innerHTML = registroCarros[i][col[j]];
        }
    }

    
    var divContainer = document.getElementById("showData");
    divContainer.innerHTML = "";
    divContainer.appendChild(table);    
}

NOTE
This JS code must be in your blade file otherwise you have to put exact URL in fetch, like: fetch('xyz.com/returnJSON')


Also verify if the controller & model is working fine and you're gettting proper data. You can do it in:

either Controller:

public function returnJSON()
{
    $teste = new user();
    $data = $teste->dbtest();
    dd($data);    // HERE

    return response()->json($data);    
}

or JS (in beginning of 'CreateTableFromJSON' function):

function CreateTableFromJSON(registroCarros = []) {
    console.log(registroCarros);    // HERE

    ...
}
Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

fetch('{{ route('returnJSON') }}')
    .then((res) => res.json())
    .then( data => CreateTableFromJSON(data))

And remove the empty array inside the function

function CreateTableFromJSON(registroCarros) {
  //var registroCarros = [] remove this line

Change route:

Route::get('returnJSON', 'App\Http\Controllers\Controller@returnJSON')->name('returnJSON');

1 Comment

I think this will solve your problem. @Dan
0

So, if I understand your code properly, the missing piece is just the question how you fetch remote data. This is how you do it:

fetch('returnJSON')
    .then((res) => res.json())
    .then(CreateTableFromJSON)

function CreateTableFromJSON(registroCarros) {
    // ...

8 Comments

i will try it right now,but i just got a little bit confused. Where did you put "fetch('returnJSON') .then((res) => res.json()) .then(CreateTableFromJSON)" is this in the controller?
No problem, this has to be in your JS Code
Thanks,but this is still not working. Absolutely nothing happens,my table is not even generated. Probably because it can't find the variable to generate it
Have you removed the line registroCarros = []?
Yes,i did. Does the "fetch('returnJSON') .then((res) => res.json()) .then(CreateTableFromJSON)" goes outside the function 'CreateTableFromJSON'?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.