So what I'm trying to do is get data from a stored procedure and put it into a table on my website. When I call the API functions from my JS file (using XML REQUEST), the if statement never runs, and I never get a result back. Im not too sure where my error is because I don't get any error message, I just get no data returned into my table.
Function that calls to API from JS file
function getStudentTopicQuizResult()
{
console.log("step 1");
var req = new XMLHttpRequest();
req.open('POST', 'https://localhost:44303/api/JSON/getStudentTopicQuizResult', true);
req.setRequestHeader('Content-Type', 'application/json');
req.onreadystatechange = function() { // Call a function when the state changes.
if (this.readyState === XMLHttpRequest.DONE && this.status === 200)
{
var result = req.response;
console.log("step 2");
}
}
return false;
}
ASP.NET API Functions
[System.Web.Http.HttpPost]
public object getStudentTopicQuizResult()
{
var response = Request.CreateResponse(HttpStatusCode.OK);
string sql = "getStudentTopicQuizResult";
var json = ExecuteSPGetStudentTopicQuizResult(sql);
response.Content = new StringContent(json);
return response;
}
private static string ExecuteSPGetStudentTopicQuizResult(string queryString)
{
string json = "";
string connectionString = ConfigurationManager.AppSettings["dbconn"].ToString();
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
// 1. create a command object identifying the stored procedure
SqlCommand cmd = new SqlCommand(queryString, conn);
// 2. set the command object so it knows to execute a stored procedure
cmd.CommandType = CommandType.StoredProcedure;
// execute the command
using (SqlDataReader rdr = cmd.ExecuteReader())
{
// iterate through results, printing each to console
while (rdr.Read())
{
json += "{\"name\":\"" + (string)rdr[0].ToString() + " " + (string)rdr[1].ToString() + "\",\"";
json += "\"topic\":\"" + (string)rdr[2].ToString() + "\",\"";
json += "\"score\":\"" + (string)rdr[5].ToString() + "\",\"";
json += "\"ids\":\"" + (string)rdr[3].ToString() + "|" + (string)rdr[4].ToString() + "\"\"},";
Console.WriteLine(json);
}
}
return json;
}
}
SQL stored procedure code
USE [Capstone]
GO
/****** Object: StoredProcedure [dbo].[getStudentTopicQuizResult] Script Date: 3/29/2021 6:01:59 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[getStudentTopicQuizResult]
AS
BEGIN
select FirstName, LastName, QuizName, [StudentQuizScore].StudentID, [StudentQuizScore].QuizID, QuizScore
from [dbo].[StudentQuizScore]
inner join Student
on Student.StudentID = [StudentQuizScore].StudentID
inner join Quiz
on quiz.QuizID = [StudentQuizScore].QuizID
END
HTML code for website page with table (Script code at bottom)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="apple-touch-icon" sizes="76x76" href="../assets/img/apple-icon.png">
<link rel="icon" type="image/png" href="../assets/img/favicon.png">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<title id=tabtitle>
Teacher Home
</title> <!-- dependent on student login -->
<meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0, shrink-to-fit=no' name='viewport' />
<!-- Fonts and icons -->
<link href="https://fonts.googleapis.com/css?family=Montserrat:400,700,200" rel="stylesheet" />
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.1/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
<!-- CSS Files -->
<link href="../assets/css/bootstrap.min.css" rel="stylesheet" />
<link href="../assets/css/now-ui-kit.css?v=1.3.0" rel="stylesheet" />
<!-- CSS Just for demo purpose, don't include it in your project -->
<link href="../assets/demo/demo.css" rel="stylesheet" />
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.24/css/jquery.dataTables.css">
</head>
<body class="profile-page sidebar-collapse">
<!-- Navbar -->
<nav class="navbar navbar-expand-lg bg-primary fixed-top navbar-transparent " color-on-scroll="400">
<div class="container">
<div class="collapse navbar-collapse justify-content-end" id="navigation" data-nav-image="../assets/img/blurred-image-1.jpg">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="welcome-page.html">Welcome/Overview</a>
</li>
</ul>
</div>
</div>
</nav>
<!-- End Navbar -->
<div class="page-header clear-filter page-header-small" >
<div class="page-header-image" data-parallax="true" style="background-image:url('../assets/img/capstone/space-bg.jpg');">
</div>
<div class="container">
<h1 id="pagetitle" class="title">Class's Future <!-- dependent on student login --></h1>
</div>
</div>
<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Dropdown button
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<a class="dropdown-item" href="#">Something else here</a>
</div>
</div>
<div class="col-xl-10 ml-auto mr-auto text-center">
<table class="display" id="example">
<thead>
<tr>
<th>Student Name</th>
<th>Topic</th>
<th>Score</th>
<th>Quiz Response</th>
</tr>
</thead>
</table>
</div>
<footer class="footer">
<div class=" container ">
<nav>
<ul>
<li>
<a href="https://mhs.monroeps.org/" target="_blank">
Masuk High School
</a>
</li>
<li>
<a href="https://classroom.google.com/h" target="_blank">
Google Classroom
</a>
</li>
</ul>
</nav>
<div class="copyright" id="copyright">
©
<script>
document.getElementById('copyright').appendChild(document.createTextNode(new Date().getFullYear()))
</script> Designed and coded by Mike Aiello</a>
</div>
</div>
</footer>
<!-- Core JS Files -->
<script src="../assets/js/core/jquery.min.js" type="text/javascript"></script>
<script src="../assets/js/core/popper.min.js" type="text/javascript"></script>
<script src="../assets/js/core/bootstrap.min.js" type="text/javascript"></script>
<!-- Plugin for Switches, full documentation here: http://www.jque.re/plugins/version3/bootstrap.switch/ -->
<script src="../assets/js/plugins/bootstrap-switch.js"></script>
<!-- Plugin for the Sliders, full documentation here: http://refreshless.com/nouislider/ -->
<script src="../assets/js/plugins/nouislider.min.js" type="text/javascript"></script>
<!-- Plugin for the DatePicker, full documentation here: https://github.com/uxsolutions/bootstrap-datepicker -->
<script src="../assets/js/plugins/bootstrap-datepicker.js" type="text/javascript"></script>
<!-- Google Maps Plugin -->
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY_HERE"></script>
<!-- Control Center for Now Ui Kit: parallax effects, scripts for the example pages etc -->
<script src="../assets/js/now-ui-kit.js?v=1.3.0" type="text/javascript"></script>
<script src="../assets/js/core/helperFunctions.js" type="text/javascript"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.24/js/jquery.dataTables.js"></script>
</body>
<script>
$(document).ready(function(){
//var userName = getCookie('myFutureUserName');
var userName = localStorage.getItem('myFutureUserName');
var userID = localStorage.getItem('myFutureUserID');
const urlParams = new URLSearchParams(window.location.search);
const myParam = urlParams.get('dataKey');
var responseObj = getStudentTopicQuizResult();
/*var responseObj = [
{ "name":"A1", "topic": "A1", "score": "100", "ids": "1009|10" },
{ "name":"A2", "topic": "A1", "score": "100", "ids": "1009|1" }
];
*/
$('#example').dataTable({
"data": responseObj,
"columns": [
{ "data": "name" },
{ "data": "topic" },
{ "data": "score" },
{
"data": "ids",
"render": function(data, type, row, meta){
//if(type === 'display'){
data = '<button type="button" class="btn btn-info btn-sm" onclick="openModal(\'' + data + '\')" >Show Quiz Response</button>';
//}
return data;
}
}
]
});
});
function openModal(quizID) {
alert(quizID);
localStorage.setItem('quizResponseID', quizID);
$("#myModal").modal();
}
</script>
</html>
Related
I am creating a page to do a basic search for breweries and am displaying information pulled from an API about breweries and would like to display the location on a map from the MapQuest API.
I know how to make a static marker, but is it possible to create a marker after a click event that uses the latitude and longitude from the JSON file? So after entering in a search term to populate the results, I want to be able to click a result and then have a marker added to the map. Is this even possible?
picture of my website project
Here is my code for the map:
var L;
window.onload = function() {
L.mapquest.key = 'hidden';
// 'map' refers to a <div> element with the ID map
var map = L.mapquest.map('map', {
center: [38.584487, -90.266699],
layers: L.mapquest.tileLayer('hybrid'),
zoom: 11
});
map.addControl(L.mapquest.control({
position: 'bottomright'
}));
L.marker([38.584487, -90.266699], {
icon: L.mapquest.icons.marker({
primaryColor: '#22407F',
secondaryColor: '#3B5998',
shadow: true,
size: 'sm',
symbol: 'A'
})
})
.bindPopup('Welcome to St. Louis! <br> Find more info here! ')
.addTo(map);
}
-- and my code for displaying each brewery below the map:
// search bar using JS
const breweryList = document.getElementById('result');
const searchBar = document.getElementById('searchBar');
let brewerySpots = [];
searchBar.addEventListener('keyup', (e) => {
const searchString = e.target.value.toLowerCase();
const filteredBreweries = brewerySpots.filter(data => {
return (
data.name.toLowerCase().includes(searchString) ||
data.city.toLowerCase().includes(searchString)
);
});
displayBreweries(filteredBreweries);
});
const loadBreweries = async () => {
try {
const res = await fetch('https://raw.githubusercontent.com/openbrewerydb/openbrewerydb/master/breweries.json');
brewerySpots = await res.json();
displayBreweries(brewerySpots);
} catch (err) {
console.error(err);
}
};
const displayBreweries = (breweries) => {
const htmlString = breweries
.map((brewery) => {
return `
<li class="brewery col">
<h3>${brewery.name}</h3>
<address> Location: ${brewery.street},
${brewery.city}, ${brewery.state}</address>
<p>Type: ${brewery.brewery_type}</p>
<i style='font-size:24px' class='fas' ></i>
</li>`
})
.join('');
breweryList.innerHTML = htmlString;
};
loadBreweries();
It seems like all of the examples and tutorials I have found pertain to clicking on the map to add a marker, but I want to click a hyperlink on my page that will use the latitude and longitude from the JSON data to add a marker.
Here is my HTML code:
<!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.0">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.4/css/all.css" integrity="sha384-DyZ88mC6Up2uqS4h/KRgHuoeGwBcD4Ng9SiP4dIRy0EXTlnuz47vAwmeGwVChigm" crossorigin="anonymous">
<script src="https://api.mqcdn.com/sdk/mapquest-js/v1.3.2/mapquest.js"></script>
<link type="text/css" rel="stylesheet" href="https://api.mqcdn.com/sdk/mapquest-js/v1.3.2/mapquest.css"/>
<link rel="stylesheet" href="../styles/style.css" />
<title>Beer30!</title>
</head>
<body>
<nav class="navbar">
<a href="#" class="navbar__logo">
<i class="fas fa-beer"></i>
</a>
<div class="navbar__bars">
<i class="fas fa-bars"></i>
</div>
<div class="navbar__menu">
Home
Breweries
About
Sign Up
Log In
</div>
</nav>
<!-- map placeholder -->
<div id="map"></div>
<!-- search field-->
<div class="container" style="width:900px">
<h2 align="center" style="color: rgb(231, 231, 231)">Search for Breweries</h2>
<h4 align="center" style="color: rgb(231, 231, 231)">Use the search field below to filter by city or brewery name!</h4>
<br>
<div id="searchWrapper">
<input type="text" name="searchBar" id="searchBar" placeholder="Search for a brewery" class="form-control">
</div>
<br>
<ul class="list-group" id="result"></ul>
</div>
<br><br>
<hr>
<!-- area to hold list of breweries -->
<select id="breweries-dropdown" name="breweries"></select>
<br><br>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous"></script>
<script src="../app/script.js"></script>
</body>
</html>
NICE! I used the Untappd API to do something similar several years ago.
I think your link will need to have an index/reference back to the list of breweries so the code can grab the correct lat/lng from the link, place the marker on the map (the same way the initial St Louis marker is added) and recenter on it.
I am new to ext.js and I need some explaination.
I wanto to use the ext.js features in a base html, without any use of html tags
I put the ext.js script tags in the html and I created an Application.js file which I reference in the html itself and which contains a simple Ext.application (....) (taken from a sencha blog).
My question is, can I simply use ext.js by inserting the script libraries references in the html, or should I do something else beforehand ?
I saw the sencha cmd on the sencha site, but i suspect its just used to create the structre of the application itself , putting the right files in the right places.
Since I can't visualize anything (apart from a js "alert" which I put at the beginning to seeif i call the right file), what am I doing wrong ?
This is my html :
#{
ViewData["Title"] = "Home Page";
}
<link href='~/ExtJS/Content/Css/prova.css' rel='stylesheet' />
<link rel="stylesheet" href="~/ExtJs/Content/Css/ext-all.css" />
<link rel="stylesheet" href="~/ExtJs/Content/Css/ext-all-debug.css" />
<script src="~/ExtJS/Scripts/ext-all-dev.js"></script>
<script src="~/ExtJS/Scripts/ext-all.js"></script>
<script src="~/ExtJS/Scripts/ext-lang-it.js"></script>
<script src="~/ExtJS/Src/Application.js"></script>
<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>Learn about building Web apps with ASP.NET Core.</p>
</div>
This is my MVC layout file :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>#ViewData["Title"] - ExtJSApplication1</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" />
</head>
<body>
<header>
#*<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
<div class="container">
<a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">ExtJSApplication1</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse">
<ul class="navbar-nav flex-grow-1">
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
</li>
</ul>
</div>
</div>
</nav>*#
</header>
<div class="container">
<main role="main" class="pb-3">
#RenderBody()
</main>
</div>
<footer class="border-top footer text-muted">
<div class="container">
© 2021 - ExtJSApplication1 - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
</div>
</footer>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
#RenderSection("Scripts", required: false)
</body>
</html>
and this is my Application.js file :
alert('launch');
Ext.application({
launch: function () {
Ext.Viewport.add({
xtype: 'grid',
title: 'Users',
columns: [
{ text: 'Name', width: 100, dataIndex: 'name' },
{ text: 'Email Address', flex: 1, dataIndex: 'email' },
{ text: 'Phone Number', width: 200, dataIndex: 'phone' }
],
data: data,
listeners: {
select: onSelect
},
});
}
}
);
function onSelect(sender, record) {
var r = record[0].data;
var text = r.name + ' - ' + r.email + ' - ' + r.phone;
Ext.Msg.alert('Row Clicked', text);
};
var data = [
{ name: 'Lisa', email: 'lisa#simpsons.com', phone: '555-111-1224' },
{ name: 'Bart', email: 'bart#simpsons.com', phone: '555-222-1234' },
{ name: 'Homer', email: 'homer#simpsons.com', phone: '555-222-1244' },
{ name: 'Marge', email: 'marge#simpsons.com', phone: '555-222-1254' }
]
If you are planning to add ExtJS as a library instead of using it as a framework, you should do a build of the ExtJS abb beforehand and include the build files into your html.
Framework Approach
Install Sencha CMD
Start Windows PowerShell (or command line on your system)
follow this documentation to generate a workspace and an app
Run sencha app build production
Use the index.html from the build
If you need additional sources you can add them into the app.json file, that way all is loaded into the html file using ExtJS.
Library Approach
same as above, but instead of using the ExtJS html...
copy the js file and the css files into your own html (folder)
how I did was:
use ExtJS gpl cdn. OR down load and store it locally
in extjs use renderTo: your_div_id ,// to render ext component on particular div
note: I have extjs license.
I'm working on a web development project where I can retrieve JSON & HTML data from JS file by using AJAX, Get, Express and Node JS.
When the user clicks on one of the lists, I want the JSON & HTML data to show up in my HTML file. I created all the templates, but for unknown reason it's not working properly..
HTML
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
<link rel="stylesheet" href="main.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<title>J MEDICAL | SURREY</title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid">
<a class="navbar-brand" id = "title" href="#">J MEDICAL</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarScroll" aria-controls="navbarScroll" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarScroll">
<ul class="navbar-nav me-auto my-2 my-lg-0 navbar-nav-scroll" style="--bs-scroll-height: 100px;">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">HOME</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">MEDICATION</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarScrollingDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
ABOUT
</a>
<ul class="dropdown-menu" aria-labelledby="navbarScrollingDropdown">
<li><a class="dropdown-item" href="#">Action</a></li>
<li><a class="dropdown-item" href="#">Another action</a></li>
<li><hr class="dropdown-divider"></li>
<li><a class="dropdown-item" href="#">Something else here</a></li>
</ul>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">RESOURCES</a>
</li>
</ul>
<form class="d-flex">
<input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success" type="submit">Search</button>
</form>
</div>
</div>
</nav>
<div class = "container">
<div id = "question"><h3>INFORMATION</h3></div>
<div id = "faq">
<ul id = "questions">
<li>CLINIC OPENING</li>
<li>COVID-19 VACCINES WE CARRY</li>
<li>OTHER MEDICAL CENTRES</li>
<li>TYPES OF RESTRICTION OF ACQUIRING VACCINE</li>
</ul>
</div>
</div>
<!-- Optional JavaScript; choose one of the two! -->
<script src="main-ajax.js"></script>
<!--Option 1: Bootstrap Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta2/dist/js/bootstrap.bundle.min.js" integrity="sha384-b5kHyXgcpbZJO/tY9Ul7kGkf1S0CWuKcCD38l8YkeH8z8QjE0GmW1gYU5S9FOnJ0" crossorigin="anonymous"></script>
</body>
</html>
JSON & HTML data in JavaScript file
const openingInfo = {
"Monday": "9-5",
"Tuesday": "9-5",
"Wednesday": "9-5",
"Thursday": "9-5",
"Friday": "11-5",
"Saturday": "CLOSED",
"Sunday": "CLOSED"
}
const openingInfo = [
{
"day": "Monday",
"hours": "9-5"
},
{
"day": "Tuesday",
"hours": "9-5"
},
{
"day": "Wednesday",
"hours": "9-5"
},
{
"day": "Thursday",
"hours": "9-5"
},
{
"day": "Friday",
"hours": "11-4"
},
{
"day": "Saturday",
"hours": "CLOSED"
},
{
"day": "Sunday",
"hours": "CLOSED"
}
]
const vaccineTypes = "<ol><li>Moderna - 18 years older</li><li>Pfizer-BioNTech - 16 years older</li><li>AstraZeneca - 18 years older</li><li>Janssen - 18 years older</li></ol>";
const restrictInfo = "<ul><li>Individuals who have travelled outside of Canada less than two weeks prior.</li><li>Been in contacted with person(s) with COVID-19.</li><li>Have been infected with COVID-19 less than 2 months prior.</li><li>Any signs of symptoms (cough, fever, diahrrea)</li><li>Participated in any gathering of more than 10 people.</li></ul>";
JavaScript file to retrieve JSON & HTML file by using AJAX, GET and Node JS.
const express = require("express");
const bodyParser = require("body-parser");
const path = require("path");
const app = express();
const { JSDOM } = require('jsdom');
const fs = require("fs");
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.use('/js', express.static('files'))
app.use('/css', express.static('files'))
app.get("/", (req, res) => {
const html = fs.readFileSync('./files/main.html', "utf8");
res.send(html);
});
app.get("/retrieve-AJAX-info", (req, res) => {
const formatOfResponse = req.query['format'];
const dataList = null;
if(formatOfResponse == 'opening-hour') {
res.setHeader('Content-Type', 'text/html');
dataList = lists.opening-hour();
res.send(dataList);
} else if(formatOfResponse == 'vaccine-types') {
res.setHeader('Content-Type', 'application/json');
dataList = lists.vaccine-types();
res.send(dataList);
} else if(formatOfResponse == 'location') {
res.setHeader('Content-Type', 'application/json');
dataList = lists.location();
res.send(dataList);
} else if(formatOfResponse == 'not-permitted') {
res.setHeader('Content-Type', 'application/json');
dataList = lists.not-permitted();
res.send(dataList);
} else {
res.send({msg: 'Wrong format!'});
}
});
app.use(function (req, res, next) {
res.status(404).send("<html><head><title>Page not found!</title></head><body><p>Nothing here.</p></body></html>");
})
// RUN SERVER
let port = 8000;
app.listen(port, function () {
console.log('You are listening to port ' + port + '.');
})
The variable dataList is defined as a const and should be let or var. Also the list variable isn't defined anywhere.
Perhaps inspecting the web browser console will show any other errors in the code.
I am making a test app and User registration is going all fine but my Login button won't login because the server responds with 404 on controllers that have the logging in function.
The code for server.js is below:
var mongoose = require('mongoose');
var bodyParser = require ('body-parser');
var express = require('express');
var multiPart = require('connect-multiparty');
var multipartMiddleware = multiPart();
var app =express();
var authenticationController = require('./server/controllers/authenticationController');
var profileController = require('./server/controllers/profileController');
mongoose.connect('mongodb://localhost:27017/timeWaste');
app.use(bodyParser.json());
app.use(multipartMiddleware);
app.use('/app',express.static(__dirname + "/app"));
app.use('/node_modules', express.static(__dirname+"/node_modules"));
//Authentication
app.post ('/users/signup', authenticationController.signup);
app.post('/users/login', authenticationController.login);
//Profile
app.post('/profile/edit', multipartMiddleware, profileController.updatePhoto);
app.post('/profile/updateUsername', profileController.updateUsername);
app.post('/profile/updateBio', profileController.updateBio);
app.get('/', function(req,res) {
res.sendfile('index.html');
});
app.listen(3000, function() {
console.log('Listening');
});
The code for my navigationController where the login function is written is as follows:
(function(){
angular.module('TimeSuck')
.controller('navigationController',["$scope","$state","$http", function($scope, $state, $http){
if(localStorage['UserData']) {
$scope.loggedIn = true;
}
else {
$scope.loggedIn = false;
}
$scope.logUserIn = function() {
$http({
method: 'POST',
url:'users/login',
}).success(function(response){
localStorage.setItem('UserData', JSON.stringify(response));
}).error(function(error){
console.log(error);
})
}
}])
})();
and the code for my html is as follows:
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
<link rel="shortcut icon" href="">
<script src="node_modules/angular/angular.js"> </script>
<script src="app/app.js"> </script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.3.1/angular-ui-router.js"> </script>
<script src="/app/signup/SignUpController.js"> </script>
<script src="/app/profile/edit-profile-controller.js"> </script>
<script src="/server/controllers/navigationController.js"></script>
<script src="/server/controllers/profileController.js"></script>
</head>
<body ng-app="TimeSuck" ng-controller="SignUpController">
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="/index.html"> Deav's Blog </a>
</div>
<ul class="nav navbar-nav">
<li> <div ng-show="!loggedIn">
Email: <input type="text" ng-model="login.email"> Password: <input type="password" ng-model="login.password">
<button type="submit" ng-click="logUserIn()"> login </button> <a ui- sref="signUp"> Create an Account </a> </li>
</ul>
<div ng-show="loggedIn"> <a ui-sref="editProfile"> </a> </div>
</div>
</nav>
<div class="container">
<div class="jumbotron">
<h1> The Smartphones </h1>
<p> This page features all the smartphones you'd want to buy and use </p>
</div>
</div>
<div ui-view> </div>
</body>
<!-- Libraries -->
<script src="node_modules/ng-file-upload/dist/ng-file-upload-all.js"></script>
<script src="node_modules/ng-file-upload/dist/ng-file-upload-shim.js"></script>
<script src="node_modules/ng-file-upload/dist/ng-file-upload.js"> </script>
Screenshot of the error:
Screenshot of the error
Why 404 error in console
In your node server ,
you defined like this one.
app.use('/app',express.static(__dirname + "/app"));
// its fine if app folder is within your root folder.
means your static resources come under app folder.
Here you,saying that your JS file come under app folder.
check second parameter.(__dirname + "/app").
So,whatever you include is script,it should contain path starts from app.
e.g.
<script src="/server/controllers/navigationController.js"></script> //its wrong
it should be
<script src="app/server/controllers/navigationController.js"></script>
In your service.js your controller paths are as follows :
'./server/controllers/profileController', './server/controllers/authenticationController'
But in your html, the paths are
<script src="/server/controllers/navigationController.js"></script>
<script src="/server/controllers/profileController.js"></script>
Are they pointing to proper paths? Pls make sure the paths are proper.
I'm having trouble getting click events from list items. In this page:
http://bec-systems.com/list-click.html
The first the entries in the list fire click events. However, if I dynamically add 3 more events by pushing the "Refresh Update List" button, the next 3 list entries do not generate click events.
Appreciate any suggestions as to how I can make this work, or generally improve the code.
Thanks,
Cliff
Code is also listed below:
<!DOCTYPE html>
<html>
<head>
<title>Status</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.1/jquery.mobile-1.1.1.min.css" />
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.1.1/jquery.mobile-1.1.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#refreshUpdateButton").on("click", function(event, ui) {
console.log("refreshUpdateButton")
versions = ["0.3", "0.4", "0.5"]
for (var i=0; i < versions.length; i += 1) {
$("#updateVersionsList").append('<li><a id="updateVersionItem-' + (i+3) + '">' + versions[i] + '</a></li>');
if ($("#updateVersionsList").hasClass('ui-listview')) {
$("#updateVersionsList").listview("refresh");
} else {
$("#updateVersionsList").trigger('create');
}
}
})
$('[id^=updateVersionItem]').on("click", function(event, ui) {
console.log("updateVersion, selected = " + $(this).attr('id'));
})
});
</script>
</head>
<body>
<!-- Software update page -->
<div data-role="page" id="software-update-page">
<div data-role="header">
<h1>Software Update</h1>
</div><!-- /header -->
<div data-role="content">
<h1>Select Software version:</h1>
<ul data-role="listview" id="updateVersionsList">
<li><a id="updateVersionItem-0">0.0</a></li>
<li><a id="updateVersionItem-1">0.1</a></li>
<li><a id="updateVersionItem-2">0.2</a></li>
</ul>
<br>
<a data-role="button" class="ui-btn-left" id="refreshUpdateButton">Refresh Update list</a>
</div><!-- /content -->
</div>
</body>
</html>
Use this form of .on() (per comments below).
$(document).on("click", '[id^=updateVersionItem]', function(event, ui) {
console.log("updateVersion, selected = " + $(this).attr('id'));
})
Example: http://jsfiddle.net/saluce/YaAEJ/
Otherwise, whenever you dynamically add the new elements, you need to attach the click event to those items.
Assuming the following code:
function doThisOnClick(event, ui) {
console.log("updateVersion, selected = " + $(this).attr('id'));
}
$('[id^=updateVersionItem]').on("click", doThisOnClick);
You can either unbind the handler and reattach to all matching items:
$('[id^=updateVersionItem]').off("click", doThisOnClick);
$('[id^=updateVersionItem]').on("click", doThisOnClick);
Or just dynamically add it to the new items once you add it:
$("#updateVersionsList").append('<li><a id="updateVersionItem-' + (i+3) + '">' + versions[i] + '</a></li>').on("click", doThisOnClick);
create a new function and call it for default and dynamic elements
<a onclick="myfunction()">