Fetch JSON data from server to table - javascript

I would like to fetch JSON data from this server:
http://eso.vse.cz/~xvojs03/studenti.json
to a table, but I do not know how to read Keys and Values and even the Array together to fetch them to the table.
This might be really stupid question but I am beginner in jQuery.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>getJSON - tabulka studentů</title>
<!-- bootstrap -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
<script>
$(document).ready(function() {
$.getJSON("http://eso.vse.cz/~xvojs03/studenti.json")
.done(function(data) {
$.each(data, function(key, val) {
$.each(data.predmety, function() {
$("tr").append("<td>"
key + ": " + val + "</td><td>" + predmety.join(",") + " ")
});
});
});
});
</script>
</head>
<body>
<div class="container">
<h2>Následující JSON jsme získali Ajaxem ze serveru</h2>
<table>
<tr>
<th>Jméno</th>
<th>Příjmení</th>
<th>Stupeň</th>
<th>Semestr</th>
<th>Predměty</th>
</tr>
<tr></tr>
</table>
</div>
</body>
</html>

You can try this code with giving a id for the table and putting this js snippet:
$.each(data, function(key, val) {
$("#result-set").append("<tr><td>"+val.jmeno+"</td><td>"+val.prijmeni+"</td><td>"+val.stupen+"</td><td>"+val.semestr+"</td><td>"+val.predmety.join(",")+"</td></tr>");
});
Full page code would be:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>getJSON - tabulka studentů</title>
<!-- bootstrap -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
<script>
$(document).ready(function(){
$.getJSON( "http://eso.vse.cz/~xvojs03/studenti.json" )
.done(function(data){
$.each(data, function(key, val) {
$("#result-set").append("<tr><td>"+val.jmeno+"</td><td>"+val.prijmeni+"</td><td>"+val.stupen+"</td><td>"+val.semestr+"</td><td>"+val.predmety.join(",")+"</td></tr>");
});
});
});
</script>
</head>
<body>
<div class="container">
<h2>Následující JSON jsme získali Ajaxem ze serveru</h2>
<table id="result-set">
<tr>
<th>Jméno</th>
<th>Příjmení</th>
<th>Stupeň</th>
<th>Semestr</th>
<th>Predměty</th>
</tr>
</table>
</div>
</body>
</html>

You might have a syntax error in this line:
$("tr").append("<td>"key + ": " + val + "</td><td>" + predmety.join(",") + " ")
Insert a + between your <td> tag and the word key like so:
$("tr").append("<td>" + key + ": " + val + "</td><td>" + predmety.join(",") + " ")

The first fix was to add the reference to your blank table, as answered by #Juyal Ahmed.
Giving the table an id here:
<table id="result-set">
And then doing a query to look it up here:
$("#result-set").append
The problem I'm seeing now is a Cross-Origin issue. Check out the console:
output of the console showing CORS error

Related

Shopping Basket - add items to local storage

I have a csv file which contains items scraped from a supermarket website. I have now displayed them on html and added a "Add to cart" button. I want the item name and price to be saved on to local storage when the button is pressed.
The idea is to then show these saved data in the basket.
Showing my existing code below.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<!--<link href ="styles.css" type = "text/css" rel="stylesheet">-->
<title>CSV File to HTML Table Using AJAX jQuery</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<!-- Header-->
<div id="header">
<button type="button" class="button">Basket</button>
</div>
<!-- CSV FILE DATA WILL APPEAR HERE-->
<div class="container">
<div class="table-responsive">
<div id="order_list" onload="appendRow()"><p id="tableintro"> Choose your desired supermarket</p>
</div>
</div>
</div>
<!--THIS BUTTON WILL LOAD DATA FROM CSV FILE-->
<div id="sidebar">
<div align="center">
<button type="button" name="load_data" id="load_sainsburys" class="btn btn-info">Sainsburys Colindale</button>
</div>
</div>
//Save item to local storage - DOESNT SEEM TO WORK
<script>
function SaveItem() {
var usrObject = {};
usrObject.product = document.getElementsById("12at").value;
usrObject.price = document.getElementById("34at").value;
//Store User
localStorage[usrObject.product] = JSON.stringify(usrObject);
}
</script>
Below is the code i am using to retrieve data from my CSV file:
<script>
$(document).ready(function(){
$('#load_sainsburys').click(function(){
$.ajax({
url:"sainsburys.csv",
dataType:"text",
success:function(data)
{
var tesco_data = data.split(/\r?\n|\r/);
var table_data = '<table class="table table-bordered table-striped">';
for (var count = 0; count < tesco_data.length; count++)
{
var cell_data = tesco_data[count].split(",");
var name = cell_data[0];
var price = cell_data[1];
if (count === 0)
{
table_data += '<tr><th>' + name + '</th><th>' + price + '</th><th>action</th></tr>';
continue;
}
table_data += '<tr><td id="12at">' + name + '</td><td id="34at">' + price + '</td><td><button type="button onclick="SaveItem()">Add to cart</button></td></tr>';
}
table_data += '</table>';
$('#order_list').html(table_data);
}
});
});
});
</script>

How can i add weather geolocation on my website?

i want to add weather on my website. i tried to do it with json and jquery, but i have some problems. can you help me or advise me other way to do this, please? the problem is that in console show that these json links which i have in html page in are incorrect. please help me. what can i do?
here is my code
if("geolocation" in navigator){
navigator.geolocation.getCurrentPosition(function(position){
loadweather(position.coords.latitude + "," + position.coords.longitude);
});
}else {
loadweather("kolkata, in" );
}
$(document).ready(function(){
setInterval(getWeather, 10000);
});
function loadWeather (location, woeid){
$.simpleWeather({
location:location,
woeid:woeid,
unit:'c',
suncess:function(weather){
city = weather.city,
temp = weather.temp+'°';
wcode = '<img class="weathericon" src=images/weathericons/' + weather.code + '.svg';
wind = '<p>' + weather.wind.speed + '</p><p>' + weather.units.speed +'</p>';
humidity = weather.humidity + '%';
$(".location").text(city);
$(".temperature").html(temp);
$(".climate_bg").html(wcode);
$(".windspeed").html(wind);
$(".humidity").text(humidity);
},
error: function(error) {
$(".error").html('<p>' + error + '</p>');
}
});
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1.0">
<title>Weather App</title>
<link href="http://fonts.googleapis.com/css?family=Montserrat:400,700,inherit,400" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="css/standardize.css">
<link rel="stylesheet" href="css/index.css">
</head>
<body class="body page-index clearfix">
<div class="container clearfix">
<p class="location"></p>
<p class="temperature"></p>
<div class="climate_bg"></div>
<div class="info_bg">
<img class="dropicon" src="images/Droplet.svg">
<p class="humidity"></p>
<img class="windicon" src="images/Wind.svg">
<div class="windspeed"></div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.simpleWeather/3.1.0/jquery.simpleWeather.min.js"></script>
<script src="js/script.js"></script>
</body>
</html>

How to fix SyntaxError: function statement requires a name

I am trying to pull data from a json file and display it in a table on my web page. The json file is updated dynamically with data about movies from an api. The function that I am using right now is giving a syntax error about needing a name.
I have tried naming the function but so far nothing has worked. I'm new to web development so if it's an obvious answer I'm sorry.
index.html
<!DOCTYPE html>
<html>
<head>
<title>Furby</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<link href="static/layout/styles/layout.css" rel="stylesheet" type="text/css" media="all">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> </script>
<script>
$(function() {
var table = document.getElementById('userdata');
for(var i = table.rows.length - 1; i > 0; i--)
{
table.deleteRow(i);
}
$.getJSON('static/movies.json', function(data) {
$.each(data.movie, function(i, f) {
var url = "https://image.tmdb.org/t/p/w92/" + f.url;
var tblRow = "<tr>" + "<td>" + f.title + "</td>" + "<td>" + "<img id = 'url_img' >" + "</td>" + "</tr>"
$(tblRow).appendTo("#userdata tbody");
document.getElementById('url_img').src = url;
document.getElementById('url_img').id = url;
});
});
});
</script>
</head>
<body id="top">
<div id="pageintro" class="hoc clear">
<!-- ################################################################################################ -->
<div class="flexslider basicslider">
<ul class="slides">
<li>
<article>
<h3 class="heading">Find A Movie</h3>
<p>Search from thousands of online movies!</p>
<footer>
<form class="group" method="post" action="search" onsubmit="function();">
<fieldset>
<legend>Search:</legend>
<input type="text" value="" placeholder="Search Here…" name="search">
<button class="fa fa-sign-in" type="submit" title="Submit"><em>Submit</em></button>
</fieldset>
</form>
</footer>
</article>
<div class="wrapper">
<div class="profile">
<table id= "userdata" border="2">
<thead>
<th>Title</th>
<th>Cover</th>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</li>
</ul>
</div>
<!-- ################################################################################################ -->
</div>
<!-- ################################################################################################ -->
<script src="static/layout/scripts/jquery.min.js"></script>
<script src="static/layout/scripts/jquery.backtotop.js"></script>
<script src="static/layout/scripts/jquery.mobilemenu.js"></script>
<script src="static/layout/scripts/jquery.flexslider-min.js"></script>
</body>
</html>
The code below will update my table with the movie titles and images once but I have to do a hard refresh on the page to get it to update. I assume it's the name error that is preventing it from running this code every time I search a movie.
EDIT: Added more relevant code. Sorry this is my first time posting.
Remove the inline event listener from the form.
<form class="group" method="post" action="search">
Name your function
function performSearch () {
var table = document.getElementById('userdata');
for (var i = table.rows.length - 1; i > 0; i--) {
table.deleteRow(i);
}
$.getJSON('static/movies.json', function(data) {
$.each(data.movie, function(i, f) {
var url = "https://image.tmdb.org/t/p/w92/" + f.url;
var tblRow = "<tr>" + "<td>" + f.title + "</td>" + "<td>" + "<img id = 'url_img' >" + "</td>" + "</tr>"
$(tblRow).appendTo("#userdata tbody");
document.getElementById('url_img').src = url;
document.getElementById('url_img').id = url;
});
});
}
Call your function on page load.
$(function(){
performSearch();
});
And setup the form to perform the search on submit.
$(function(){
performSearch();
$('.group[action="search"]').on('submit', function(e){
e.preventDefault();
performSearch();
});
});
1 ) You have 2 jQuery Lib, that wrong, you need only one also check versions
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> </script>
. . .
<script src="static/layout/scripts/jquery.min.js"></script>
2) your HTML table is not valid : you forget placing forget <tr> .... </tr>
<table>
<thead>
<tr>
<th>Title</th>
<th>Cover</th>
</tr>
</thead>
<tbody id="userdata-tbody"></tbody>
</table>
I also place the id="userdata-tbody" on the <tbody> otherwise you also delete your <thead> row
so place your jQuery lib before the code :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Furby</title>
<link href="static/layout/styles/layout.css" rel="stylesheet" type="text/css" media="all">
<script src="static/layout/scripts/jquery.min.js"></script>
<script src="static/layout/scripts/jquery.backtotop.js"></script>
<script src="static/layout/scripts/jquery.mobilemenu.js"></script>
<script src="static/layout/scripts/jquery.flexslider-min.js"></script>
<script>
$(function () {
var tableUserData = document.getElementById('userdata-tbody');
...
for(var i = tableUserData.rows.length; i--;)
{
tableUserData.deleteRow(i);
}
...
});
</script>
</head>
<body>
...
<table>
<thead>
<tr>
<th>Title</th>
<th>Cover</th>
</tr>
</thead>
<tbody id="userdata-tbody"></tbody>
</table>
...
</body>
</html>

How to append a row in modal?

My table is given below.
i want to find out whenever click event handler calls on
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function() {
var t = $('#example').DataTable();
var counter = 1;
t.row.add( [
"<input type='checkbox'>",
"<a href='#'>"+ counter+'.1' +"</a>",
counter +'.3',
counter +'.4',
counter +'.5',
counter +'.6'
]).draw( true );
counter++;
t.row.add( [
"<input type='checkbox'>",
"<a href='#'>"+ counter+'.1' +"</a>",
counter +'.3',
counter +'.4',
counter +'.5',
counter +'.6'
]).draw( false );
counter++;
$("tr").click(function(context) {
var value = context.currentTarget.innerHTML;
$(".modal-body").after(value);
$("#11").prop("hidden",false);
});
$(".btn").click(function() {
$(".modal-body").empty();
$("#11").prop("hidden",true);
});
});
</script>
</head>
<body>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Sr No.</th>
<th name="aa">Modal View</th>
<th>Label1</th>
<th>Label2</th>
<th>Label3</th>
<th>Label4</th>
</tr>
</thead>
</table>
<div id="11" hidden="true" class="modal-content">
<div class="modal-header">
<h4 class="modal-title"></h4>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</body>
</html>
Here when on click of tr i am finding that modal view is opening but it is opening on click of any column of that row.
Also if i will not close that modal than it will append all other row data to that modal.i don't want that as well.
Given below may be the closest answer you want and also modern way of doing it. You can refer this link for further details of the way of creating modal dynamically.
$(document).ready(function() {
var t = $('#example').DataTable();
for (i = 1; i <= 10; i++) {
t.row.add([
'<input type="checkbox">',
'' + i + '.1' + '',
i + '.3',
i + '.4',
i + '.5',
i + '.6'
]).draw(true);
}
});
function showModal(rowid) {
BootstrapDialog.show({
title: 'Title goes here.',
message: function() {
var msg = '';
msg += '<table>';
msg += ' <thead>';
msg += ' <tr>' + $('#example thead tr').html() + '</tr>';
msg += ' </thead>';
msg += ' <tbody>';
msg += ' <tr>' + $('#example tbody tr:nth-child(' + rowid + ')').html() + '</tr>';
msg += ' </tbody>';
msg += '</table>';
return msg;
},
buttons: [{
label: 'Close',
action: function(dialog) {
dialog.close();
}
}]
});
}
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap3-dialog/1.34.7/css/bootstrap-dialog.min.css">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap3-dialog/1.34.7/js/bootstrap-dialog.min.js"></script>
<script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Sr No.</th>
<th name="aa">Modal View</th>
<th>Label1</th>
<th>Label2</th>
<th>Label3</th>
<th>Label4</th>
</tr>
</thead>
</table>

site works in firefox but no other browsers, why?

should do this:
a progress bar appears, followed by thunbnails.. if it' working.
Can someone please simply explain to me what i have written wrong in my markup?
I don't understand what might be the issue here so I am asking here,
My site: http://env-3884279.jelastic.servint.net/bot2/
if the 0% does not appear, it's working incorrectly,
refuses to run in any other browser except firefox. why?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>capri</title>
<!-- Bootstrap -->
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body class="container" style="background-color: white; color: #333; font-family: 'Segoe UI';">
<br /><br />
<div>
<div id="status" class="pull-left"></div>
<div id="total" class="pull-right bg-success table-bordered" style="padding: 6px;">0 Movies Processed.</div>
<div class="clearfix"></div>
<br />
<div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">
</div>
</div>
<br />
<div class="clearfix"></div>
<div class="row-fluid" id="pagelist" style="border-top: solid whitesmoke 4px;">
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script>
var processed = 0;
function ScanPage(pagenum, callback) {
$("#status").html("Please Wait... ");
$('.progress-bar').hide();
$('.progress-bar').css('width', 0 + '%').attr('aria-valuenow', 0).html(0 + '%');
$.ajax({
url: "movies/merdb/scanpage.php?token=" + Math.random() + "&p=" + pagenum,
cache: false,
async: true,
type: "GET"
}).done(function (html) {
var done = 0;
var json = JSON.parse(html);
var count = Object.keys(json).length;
$('.progress-bar').show();
$.each(json, function (iter) {
$.ajax({
url: "movies/merdb/parsepageresults.php?token=" + Math.random() + "&match=" + json[iter],
cache: false,
async: false,
type: "GET"
}).done(function (response) {
if (response != undefined && response != "") {
$("#status").html("<i class=\"fa fa-spinner fa-spin\"></i> Page <span class=\"badge\" style=\"background-color: whitesmoke; font-size: 16px;color: black;\">" + pagenum + "</span> Processing " + (done + 1) + " of " + count);
$("#pagelist").append("<div style=\"padding: 5px;\" class=\"col-xs-2\"><img src=" + response + " width=\"150\" height=\"225\"></div>");
var vpercent = parseInt(done * 100 / count);
$('.progress-bar').css('width', vpercent + '%').attr('aria-valuenow', vpercent).html(vpercent + '%');
}
done++;
processed++;
$("#total").html(processed + " Movies Processed.");
});
});
$("#status").html("Scanning Page " + pagenum + " has completed. <span class=\"glyphicon glyphicon-ok\" style=\"color: green\"> </span>");
callback(pagenum + 1);
});
}
function Begin(index) {
ScanPage(index, OnCompleted);
}
function OnCompleted(index)
{
$("#pagelist").html("");
Begin(index);
}
Begin(1);
</script>
</body>
</html>
Try to put all yours script's <script src="https://aja.... that you have on top.
Remove the
$('.progress-bar').hide();
if you want to see the 0%
Also the base64 returned is not correct and chrome is trying to download from a url
you are getting
"data:jpg;base64,......"
when you should be getting
"data:image/jpg;base64,...."
Your Ajax minified java script is not responding properly. Try to put both minified java script in head section of HTML. Try to download and save the minified code and run it through your machine so process will be little faster.

Categories