'Primary Expression Expected' in JavaScript Function - javascript

I'm new to JavaScript and JQuery. I'm trying to get my Json data to be stored on my Web Page as a HTML table. If I use the following code it works perfectly:
$(document).ready(function(){
$.getJSON("getAllFilms?format=json", function(data){
var filmInfo = '';
$.each(data, function(key, value){
filmInfo += '<tr>';
filmInfo += '<td>'+value.title+'</td>';
filmInfo += '<td>'+value.id+'</td>';
filmInfo += '<td>'+value.review+'</td>';
filmInfo += '<td>'+value.stars+'</td>';
filmInfo += '<td>'+value.director+'</td>';
filmInfo += '<td>'+value.year+'</td>';
filmInfo += '<tr>';
});
$('#table').append(filmInfo);
});
});
However, I would like this to be in a JavaScript file so that I can call this function when the user clicks a button. I tried the following but I get the error 'Primary Expression Expected'. Any ideas?
function allFilmsJsonTable(){
$.getJSON("getAllFilms?format=json", function(data){
var filmInfo = '';
$.each(data, function(key, value){
filmInfo += '<tr>';
filmInfo += '<td>'+value.title+'</td>';
filmInfo += '<td>'+value.id+'</td>';
filmInfo += '<td>'+value.review+'</td>';
filmInfo += '<td>'+value.stars+'</td>';
filmInfo += '<td>'+value.director+'</td>';
filmInfo += '<td>'+value.year+'</td>';
filmInfo += '<tr>';
});
$('#table').append(filmInfo);
});
});

Related

Downloading CSV contents via Ajax and PHP

I am trying to download CSV contents via PHP script hosted on the server.
This is the jquery code that executes and creates a table:
$(document).ready(function() {
$("#btnSubmit").click(function(){
$.ajax({
type: 'GET',
url: 'http://mydomaincom/wp-content/uploads/get-csv.php',
data: null,
success: function(text) {
var fields = text.split(/\n/);
fields.pop(fields.length-1);
var headers = fields[0].split(','),
html = '<table>';
html += '<tr>';
for(var i = 0; i < headers.length; i += 1) {
html += '<th scope="col">' + headers[i] + '</th>';
}
html += '</tr>';
var data = fields.slice(1, fields.length);
for(var j = 0; j < data.length; j += 1) {
var dataFields = data[j].split(',');
html += '<tr>';
html += '<td>' + dataFields[0] + '</td>';
html += '<td>' + dataFields[1] + '</td>';
html += '<td>' + dataFields[2] + '</td>';
html += '</tr>';
}
html += '</table>';
$(html).appendTo('body');
}
});
});
});
Contents of get-csv.php file:
<?php
header('Content-Type: text/plain');
$csv = file_get_contents('http://mydomaincom/wp-content/uploads/csv-samples.csv');
echo $csv;
?>
Here is the code for button:
<!-- Begin Button -->
<div class="demo">
<input id = "btnSubmit" type="submit" value="Get It"/>
</div>
<!-- End Button -->
From browser:
I can access http://mydomaincom/wp-content/uploads/get-csv.php - no issues
I can access http://mysitecom/wp-content/uploads/csv-samples.csv - no issues
When I click on button nothing happens.
Thanks
Below I tried to put together a working snippet where you can possibly see how it works when it works ...
$(document).ready(function () {
$("#btnSubmit").click(function () {
$.ajax({
type: 'GET',
// url: 'http://mydomaincom/wp-content/uploads/get-csv.php',
// url: 'https://jsonplaceholder.typicode.com/users', // --> JSON
url: "https://data.cdc.gov/api/views/45um-c62r/rows.csv",
data: null,
success: function (text) {
var fields = text.split(/\n/);
fields.pop(fields.length - 1);
var headers = fields[0].split(','), html = '<table>';
html += '<tr>';
for (var i = 0; i < (headers.length,3); i += 1) {
html += '<th scope="col">' + headers[i] + '</th>';
}
html += '</tr>';
var data = fields.slice(1, fields.length);
for (var j = 0; j < data.length; j += 1) {
var dataFields = data[j].split(',');
html += '<tr>';
html += '<td>' + dataFields[0] + '</td>';
html += '<td>' + dataFields[1] + '</td>';
html += '<td>' + dataFields[2] + '</td>';
html += '</tr>';
}
html += '</table>';
$(html).appendTo('body');
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btnSubmit">get data</button>
After looking around a bit further I did actually find some publicly available CSV data ("Rates of TBI-related Emergency Department Visits, Hospitalizations, and Deaths - United States, 2001 – 2010" from the U.S. Department of Health & Human Services) and I am now using that to demonstrate the AJAX process.
So, your code basically works. It could be simplified of course but that is not the point. I guess that the problems you encounter with your site are probably CORS-related.

Return values from an API in a JSON array

I have this website that calls data from the API, renders the data in a table but every single cell returns undefined.
The data in the API is inside an array like [] but the there are multiple data sets with {} inside them which I'm not sure how to define in JavaScript. How would I fix this?
This is the link to the API from where I wish to render the data. Here is an example of this data:
[
{
"id": "40129",
"employee_name": "EllakZa",
"employee_salary": "56106",
"employee_age": "311",
"profile_image": ""
},
{
"id": "40212",
"employee_name": "Amit Negi111",
"employee_salary": "123456",
"employee_age": "44",
"profile_image": ""
}
]
My code follows:
$(document).ready(function(){
$.getJSON("http://dummy.restapiexample.com/api/v1/employees", function(data){
var employeeData = '[]';
console.log(data);
$.each(data, function({key, value}){
employeeData += '<tr>';
employeeData += '<td>'+data.id+'</td>';
employeeData += '<td>'+data.employee_name+'</td>';
employeeData += '<td>'+data.employee_salary+'</td>';
employeeData += '<td>'+data.employee_age+'</td>';
employeeData += '<td>'+data.profile_image+'</td>';
employeeData += '<tr>';
});
$('#tracerouteTable').append(employeeData);
});
});
Do like this:
$(document).ready(function(){
$.getJSON("http://dummy.restapiexample.com/api/v1/employees", function(data){
var employeeData = '';
console.log(data);
$.each(data, function(key, value){
employeeData += '<tr>';
employeeData += '<td>'+value.id+'</td>';
employeeData += '<td>'+value.employee_name+'</td>';
employeeData += '<td>'+value.employee_salary+'</td>';
employeeData += '<td>'+value.employee_age+'</td>';
employeeData += '<td>'+value.profile_image+'</td>';
employeeData += '<tr>';
});
$('#tracerouteTable').append(employeeData);
});
});
To know more about jquery each follow this link
'data' is the the array returned from the api, so 'data.id' is undefined. You need to access the properties of each object within the array, so iterate over the array und use each item for accessing the properties.
use
data.forEach((item) => {
employeeData += '<tr>';
employeeData += '<td>'+item.id+'</td>';
employeeData += '<td>'+item.employee_name+'</td>';
employeeData += '<td>'+item.employee_salary+'</td>';
employeeData += '<td>'+item.employee_age+'</td>';
employeeData += '<td>'+item.profile_image+'</td>';
employeeData += '<tr>';
});
instead.
Data is an array of JSON objects. So in your code key is the index of the current JSON object and value is the current JSON object.
Access the data inside the JSON object like this:
$.getJSON("http://dummy.restapiexample.com/api/v1/employees", function(data){
console.log(data);
$.each(data, function({key, value}){
var employeeData = '';
employeeData += '<tr>';
employeeData += '<td>' + value.id + '</td>';
employeeData += '<td>' + value.employee_name + '</td>';
employeeData += '<td>' + value.employee_salary + '</td>';
employeeData += '<td>' + value.employee_age + '</td>';
employeeData += '<td>' + value.profile_image + '</td>';
employeeData += '<tr>';
$('#tracerouteTable').append(employeeData);
});
});

How to reorder columns with Knex?

I am pulling all of my data from an Sqlite3 table using Knex, electron and JavaScript and I wish to reorder the columns either on the Knex query or in the HTML/JavaScript side.
My sqlite3 db has the following header data:
id|Role|Password|Reference
With the following code, the table displays in the following order:
Password|Reference|Role|id
I have attempted to utilize the .orderBy method in Knex and have also attempted to reorder in JavaScript, but I cannot seem to reorder the columns.
The Electron side of things, I have:
ipcMain.on('getUserTable:all', (event) => {
let getUserTable =
knex('User').select(['id','Role','Reference','Password']).orderBy('Role');
getUserTable.then(function(tableData){
newWin.webContents.send("userResultSent", tableData);
});
});
In the HTML side of things, I have:
ipc.on('userResultSent', (event, tableData) => {
var html = '<table>';
html += '<tr>';
for( var j in tableData[0] ) {
html += '<th>' + j + '</th>';
}
html += '</tr>';
for( var i = 0; i < tableData.length; i++) {
html += '<tr>';
for( var j in tableData[i] ) {
html += '<td>' + tableData[i][j] + '</td>';
}
}
html += '</table>';
document.getElementById('db_output_container').innerHTML = html;
});
I wish to be able to query the db so that the array displays in the exact order as in the table.
The problem with your current approach is that object are unordered bags of properties. So it does not matter how order your columns - properties order is not guaranteed.
If you need specific order you could use Array instead.
Since you have general code to display tabular data you could do the following
ipcMain.on('getUserTable:all', (event) => {
const columns = ['id','role','reference','password']
let getUserTable =
knex('User').select(columns).orderBy('role');
getUserTable.then(function(tableData){
newWin.webContents.send("userResultSent", {columns, tableData});
});
});
When creating html
ipc.on('userResultSent', (event, {columns, tableData}) => {
var html = '<table>';
html += '<tr>';
columns.forEach(column => {
// if you want to capitalize names just do it here
html += '<th>' + column + '</th>';
})
html += '</tr>';
for( var i = 0; i < tableData.length; i++) {
html += '<tr>';
columns.forEach(column => {
html += '<td>' + tableData[i][column] + '</td>';
})
html += '</tr>';
}
html += '</table>';
document.getElementById('db_output_container').innerHTML = html;
})
At the end of the second for loop, you should close the tr tag. Indeed, you open it right after the second for loop but you don't close it.
I haven't tested yet but it should work.
Your html file should looks like this.
ipc.on('userResultSent', (event, tableData) => {
var html = '<table>';
html += '<tr>';
for( var j in tableData[0] ) {
html += '<th>' + j + '</th>';
}
html += '</tr>';
for( var i = 0; i < tableData.length; i++) {
html += '<tr>';
for( var j in tableData[i] ) {
html += '<td>' + tableData[i][j] + '</td>';
}
html += '</tr>'; /* i added this line here */
}
html += '</table>';
document.getElementById('db_output_container').innerHTML = html;
});

Adding Parameter to Javascript AJAX

this is my simple hardcoded version.
$(document).ready(function(){
$.support.cors = true;
var this_id = '123456789123456';
$.ajax({
url: 'https://thisservice/delivery/'+this_id,
type: "get",
dataType: "json",
data: { },
success: function(response){
console.log(response);
var html = '';
html += '<tr>';
html += '<th>Customer Name: </th><td>'+response.custName+'</td>';
html += '</tr>';
html += '<tr>';
html += '<th>Address Line1:</th><td>'+response.addrLine1+'</td>';
html += '</tr>';
html += '<tr>';
html += '<th>Address Line2:</th><td>'+response.addrLine2+'</td>';
html += '</tr>';
html += '<th>Address Line3:</th><td>'+response.addrLine3+'</td>';
html += '</tr>';
html += '<th>Address Line4:</th><td>'+response.addrLine4+'</td>';
html += '</tr>';
html += '<th>Address Line5:</th><td>'+response.addrLine5+'</td>';
html += '</tr>';
html += '<th>Address Line6:</th><td>'+response.addrLine6+'</td>';
html += '</tr>';
html += '<th>Customer PostCode:</th><td>'+response.custPostCode+'</td>';
html += '</tr>';
$('#theDelivery').append(html);
}
})});
the code above works perfectly fine, however im now working to make this_id as a url parameter, so when the webpage is called along with a valid 16th digit number as a substring, it will return the contents of the objects that i am trying to access from this webservice.
How exactly is it done? i have attempted to do this in the code below, but no luck.
<script type="text/javascript">
function getthisId(this_id){
$.support.cors = true;
$.ajax({
type: "get",
url: 'https://thisservice/delivery/'+this_id,
dataType: "json",
cache: false,
data: { this_id },
success: function (response) {
console.log(response);
var html = '';
html += '<tr>';
html += '<th>Customer Name: </th><td>'+response.custName+'</td>';
html += '</tr>';
html += '<tr>';
html += '<th>Address Line1:</th><td>'+response.addrLine1+'</td>';
html += '</tr>';
html += '<tr>';
html += '<th>Address Line2:</th><td>'+response.addrLine2+'</td>';
html += '</tr>';
html += '<th>Address Line3:</th><td>'+response.addrLine3+'</td>';
html += '</tr>';
html += '<th>Address Line4:</th><td>'+response.addrLine4+'</td>';
html += '</tr>';
html += '<th>Address Line5:</th><td>'+response.addrLine5+'</td>';
html += '</tr>';
html += '<th>Address Line6:</th><td>'+response.addrLine6+'</td>';
html += '</tr>';
html += '<th>Customer PostCode:</th><td>'+response.custPostCode+'</td>';
html += '</tr>';
$('#theDelivery').append(html);
}
});
}
$(document).ready(function () {
getthisId(this_id);
});
this error occurs:
Uncaught ReferenceError: this_id is not defined
at HTMLDocument.<anonymous> (1032987988503654:59)
at i (jquery-1.12.3.min.js:2)
at Object.fireWith [as resolveWith] (jquery-1.12.3.min.js:2)
at Function.ready (jquery-1.12.3.min.js:2)
at HTMLDocument.K (jquery-1.12.3.min.js:2)
im very new to this, any help would be great :)
The server side is expecting the value in a parameter named parcel_id, so you need to provide that as the key in the object you provide to data, like this:
data: { parcel_id: this_id },
you should do like this
'https://thisservice/delivery/?id='+this_id

Web page content not shownig after JQuery loading

Above code generate HTML table using JSON output.
But, my problem is, after this JQuery runs, other page content is not shown.
<script>
$(document).ready(function () {
var html = '<table class="table table-striped">';
html += '<tr>';
var flag = 0;
var data2 = <?php echo $data; ?>;
$.each(data2[0], function(index, value){
html += '<th>'+index+'</th>';
});
html += '</tr>';
$.each(data2, function(index, value){
html += '<tr>';
$.each(value, function(index2, value2){
html += '<td>'+value2+'</td>';
});
html += '<tr>';
});
html += '</table>';
$('body').html(html);
console.log(html);
});
</script>
when the page loads, content should disappear and it should shows particular table only.
change this
$('body').html(html);
with
$('body').append(html);
Probably cause is
$('body').html(html);
Because html() method will change the content of body elements. You should use
$('body').append(html);
to insert content at the end of body elements.
you miss : html += '</tr>';
please check with full code
<script>
$(document).ready(function () {
var html = '<table class="table table-striped">';
html += '<tr>';
var flag = 0;
var data2 = <?php echo $data; ?>;
$.each(data2[0], function(index, value){
html += '<th>'+index+'</th>';
});
html += '</tr>';
$.each(data2, function(index, value){
html += '<tr>';
$.each(value, function(index2, value2){
html += '<td>'+value2+'</td>';
});
html += '</tr>';
});
html += '</table>';
$('body').html(html);
console.log(html);
});
</script>

Categories

Resources