Use Laravel route in javascript? - javascript

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.

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
...
}

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');

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) {
// ...

Related

Datatable does not work searching function after table is created

After table row created js script is run finished, datatable's search function does not work for table row data
var geturl = 'http://joinernsg.com/pos/api.php?categories=get';
var tbody = document.getElementById("tr-cl");
axios.get(geturl).then(function (res) {
for(var i=0; i<res.data.length; i++){
var row = tbody.insertRow(i);
row.insertCell(0).innerHTML = res.data[i].id;
row.insertCell(1).innerHTML = res.data[i].name;
}
});
$('#datatable').dataTable();
This works.
let data = [{"id":"18","name":"Breakfast"},{"id":"29","name":"buff"},{"id":"27","name":"cake"},{"id":"26","name":"coffee"},{"id":"17","name":"Dessert"},{"id":"20","name":"Dinner"},{"id":"19","name":"Lunch"},{"id":"28","name":"tea"}];
var tbody = document.getElementById("tr-cl");
for(var i=0; i<data.length; i++){
var row = tbody.insertRow(i);
row.insertCell(0).innerHTML = data[i].id;
row.insertCell(1).innerHTML = data[i].name;
}
<table id="tr-cl"></table>
<table id="tr-cl"></table>
<script>
var tbody = document.getElementById("tr-cl");
fetch(`http://joinernsg.com/pos/api.php?categories=get`)
.then((response) => {
return response.json();
})
.then((data) => {
data = JSON.parse(data)
for(var i=0; i<data.length; i++){
var row = tbody.insertRow(i);
row.insertCell(0).innerHTML = data[i].id;
row.insertCell(1).innerHTML = data[i].name;
}
})
</script>

When create checkbox in JavaScript got [object HTMLInputElement]

This is my code
data = [{
name: 'Yemen',
code: 'YE'
},
{
name: 'Zambia',
code: 'ZM'
},
{
name: 'Zimbabwe',
code: 'ZW'
}
];
function addKeyValue(obj, key, data) {
obj[key] = data;
}
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.name = "key";
checkbox.id = "id";
newinfo = data.map(function(person) {
return addKeyValue(person, 'checkbox', (checkbox)); });
var columnHeadings = Object.keys(data[0]);
var columnCount = columnHeadings.length;
var rowCount = data.length;
var table = document.createElement('table');
document.getElementById("data-list").appendChild(table);
var header = table.createTHead();
var row = header.insertRow(-1);
for (var i = 0; i < columnCount; i++) {
var headerCell = document.createElement('th');
headerCell.innerText = columnHeadings[i].toUpperCase();
row.appendChild(headerCell);
}
var tBody = document.createElement('tbody');
table.appendChild(tBody);
for (var i = 0; i < rowCount; i++) { // each row
var checkbox = document.createElement('input');
row = tBody.insertRow(-1);
for (var j = 0; j < columnCount; j++) { // each column
var cell = row.insertCell(-1);
cell.setAttribute('data-label', columnHeadings[j].toUpperCase());
var obj = data[i];
cell.innerText = obj[columnHeadings[j]];
}
}
In a tabular format I do have to get checkboxes with the json data. So firstly I have defined my json and then I have append checkboxes for each row.I am planning to add check boxes in every json object. But in my final output it is giving [object HTMLInputElement] instead of a checkbox.
You are adding the element object to your newinfo array, if you want the html for it you need to add it to the dom which it looks like you want to do at some point later in your code, to do this you would for example do document.body.appendChild(checkbox) if you wanted to add the checkbox to body.

Generate HTML Table with 2 javascript Arrays

Hello I try to generate an HTML Table with two arrays. Where one array is for the Headers and the other one is for the rows. The arrays work like a blast but the generation of the HTML-Table wont work.....
Here is my little Function: (For the arrays and they work like a blast)
function loadDepartments() {
var query = "$select=DepartmentID,WEBName";
getListItems("example.at", "WEBepartments", query, function (results) {
results.forEach(function (result) {
departments.push({
name: result.WEBName,
id: result.DepartmentID
});
});
loadCountries();
},
function (error) {
console.log(error);
});
}
function loadCountries() {
var query = "$select=CountryID,WEBName,Acronym";
getListItems("https://intranet.windkraft.at/", "WEBCountries", query, function (results) {
results.forEach(function (result) {
countries.push({
name: result.WEBName,
id: result.CountryID,
acronym: result.Acronym
});
});
doNextSteps();
},
function (error) {
console.log(error);
});
}
And here my latest Try:
function doNextSteps() {
//Create a HTML Table element.
var table = document.createElement("TABLE");
table.border = "1";
//Get the count of columns and rows.
var columnCount = departments.length;
var rowCount = countries.length;
//Add the header row.
var row = table.insertRow(-1);
for (var i = 0; i < columnCount; i++) {
var headerCell = document.createElement("TH");
headerCell.innerHTML = columnCount[0];
row.appendChild(headerCell);
}
//Add the data rows.
for (var i = 1; i < countries.length; i++) {
row = table.insertRow(-1);
for (var j = 0; j < rowCount; j++) {
var cell = row.insertCell(-1);
cell.innerHTML = rowCount[0];
}
}
var dvTable = document.getElementById("dvTable");
dvTable.innerHTML = "";
dvTable.appendChild(table);
}
But wont work the only thing i get is nothing or undefined. And i have no clue why becouse its the first time i try to generate a HTML Table with javascript. So any help would be great.
Thx for your Time and Help.

Create table from Json pure javascript

I have a Json with multiple keys that can change, something like this:
Var children = [{num = 6, name = me, phone = 7}, {num = 8, name = him, phone = 9}]
And I want a table with the headers (num, name, phone)
How can I do it with only JavaScript? (No JQuery)
var children = [{num: 6, name: 'me', phone: 7}, {num: 8, name: 'him', phone: 9}];
function addHeaders(table, keys) {
var row = table.insertRow();
for( var i = 0; i < keys.length; i++ ) {
var cell = row.insertCell();
cell.appendChild(document.createTextNode(keys[i]));
}
}
var table = document.createElement('table');
for( var i = 0; i < children.length; i++ ) {
var child = children[i];
if(i === 0 ) {
addHeaders(table, Object.keys(child));
}
var row = table.insertRow();
Object.keys(child).forEach(function(k) {
console.log(k);
var cell = row.insertCell();
cell.appendChild(document.createTextNode(child[k]));
})
}
document.getElementById('container').appendChild(table);
<div id="container"></div>
The below method will draw a table based on json.
First Copy the javascript and html
javascript
<script type="text/javascript">
function jsonToTable(json) {
var parsejson=JSON.parse(json);
var columns=[];
var tablethread="<thead><tr>";
for (x in parsejson[0]) {
columns.push(x);
tablethread+="<th>"+x+"</th>";
}
tablethread+="</tr></thead>";
document.getElementById("tableID").innerHTML=tablethread;
var table_rows='<tbody>';
for (var i = 0; i < parsejson.length; i++) {
var x= parsejson[i];
var json2=x;
var row="<tr>"
for (d in x) {
var sty=x[d];
if (sty!=null) {
var st=sty.toString();
var reps='<\\';
row+="<td><p>"+st.split('<').join('<')+"</p></td>";
}
else {
row+="<td><p>null</p></td>";
}
}
row+="</tr>"
table_rows+=row;
}
table_rows+='</tbody>';
document.getElementById("tableID").innerHTML+=table_rows;
}
</script>
HTML
<table id="tableID" class="table"></table>
Now Call Method
jsonToTable("YOUR_JSON");
Example
var jsonstring = '[{ "name":"John", "age":30, "car":"BMW"},'+
'{ "name":"Wick", "age":50,"car":"DODGE" }]';
jsonToTable(jsonstring);
fetch('https://jsonplaceholder.typicode.com/todos').then(response => response.json()).then(data => createTable(data)).catch(error=>console.log(error))
const createTable = (data) => {
const tableData = data;
const headerData = Object.keys(tableData[0]);
const table = document.createElement('table');
const tr = table.insertRow(-1);
for(let i=0; i<headerData.length; i++){
const th = document.createElement('th');
th.innerHTML = headerData[i];
tr.appendChild(th)
}
for(let i=0; i<tableData.length; i++){
const tr = table.insertRow(-1);
const obj = tableData[i];
for(let key in obj) {
const td = document.createElement('td');
td.innerHTML = obj[key];
tr.appendChild(td);
}
}
document.body.appendChild(table);
}
Javascript
var _table_ = document.createElement('table'),
_tr_ = document.createElement('tr'),
_th_ = document.createElement('th'),
_td_ = document.createElement('td');
// Builds the HTML Table out of myList json data from Ivy restful service.
function buildHtmlTable(arr) {
var table = _table_.cloneNode(false),
columns = addAllColumnHeaders(arr, table);
for (var i=0, maxi=arr.length; i < maxi; ++i) {
var tr = _tr_.cloneNode(false);
for (var j=0, maxj=columns.length; j < maxj ; ++j) {
var td = _td_.cloneNode(false);
cellValue = arr[i][columns[j]];
td.appendChild(document.createTextNode(arr[i][columns[j]] || ''));
tr.appendChild(td);
}
table.appendChild(tr);
}
return table;
}
// Adds a header row to the table and returns the set of columns.
// Need to do union of keys from all records as some records may not contain
// all records
function addAllColumnHeaders(arr, table)
{
var columnSet = [],
tr = _tr_.cloneNode(false);
for (var i=0, l=arr.length; i < l; i++) {
for (var key in arr[i]) {
if (arr[i].hasOwnProperty(key) && columnSet.indexOf(key)===-1) {
columnSet.push(key);
var th = _th_.cloneNode(false);
th.appendChild(document.createTextNode(key));
tr.appendChild(th);
}
}
}
table.appendChild(tr);
return columnSet;
}
document.body.appendChild(buildHtmlTable([
{"num" : "6", "name" : "me", "phone" : "7"},
{"num" : "8", "name" : "him", "phone" : "9"}
]));
CSS
th, td {
border: 1px solid;
}
th {
font-weight : bold
}

displaying table in the right style

I have a problem in displaying the borders of my table correctly ,I work with jsPDF library ,this is the result that I get :
this is my code that selecet every row and display the data:
function tableToJson(table) {
var data = [];
// first row needs to be headers
var headers = [];
for (var i=0; i<table.rows[0].cells.length,i<5; i++) {
headers[i] = table.rows[0].cells[i].innerHTML.toLowerCase().replace(/ /gi,'');
}
data.push(headers);
// go through cells
for (var i=1; i<table.rows.length;i++) {
var tableRow = table.rows[i];
var rowData = {};
for (var j=0; j<tableRow.cells.length,j<5 ; j++) {
rowData[ headers[j] ] = tableRow.cells[j].innerHTML;
}
data.push(rowData);
}
return data;
}
function callme(){
var table = tableToJson($('#table').get(0));
var doc = new jsPDF('l','pt','letter',true);
$.each(table, function(i, row){
$.each(row, function(j,cell){
if(j=="email"){
doc.cell(1,10,190,20,cell,i);
}
else{
doc.cell(1,10,100,20,cell,i);
}
});
});
thanks for help

Categories