I'm trying to push suspect records in the firebase database, everything is working correctly, but the pushing part doesn't seem to be working. It works very rarely, not every time.
Here is the function:
async function storeSuspectData() {
var name = document.getElementById("name").value;
var height = document.getElementById("height").value;
var weight = document.getElementById("weight").value;
var idnumber = document.getElementById("idnumber").value;
var dob = document.getElementById("dob").value;
var crime = document.getElementById("crime").value;
var hypo = document.getElementById("hypo").value;
var gender;
if (document.getElementById("male").checked) {
gender = 'male';
}
else if (document.getElementById("female").checked) {
gender = 'female';
}
console.log(sessionStorage.getItem("userKey") + ' ' + name + ' ' + height + ' ' + weight + ' ' + idnumber + ' ' + dob + ' ' + gender + ' ' + crime + ' ' + hypo);
console.log('/users/' + sessionStorage.getItem("userKey") + '/suspectList/');
let token = await database.ref('/users/' + sessionStorage.getItem("userKey") + '/suspectList/');
await token.push().set({
name: name,
height: height,
weight: weight,
idnumber: idnumber,
dob: dob,
gender: gender,
crime: crime,
hypo: hypo,
});
alert('Record added successfully');
}
The last alert statement is not getting executed and data is not being pushed
Here is the database
I'm also getting this error on console, but I'm not using document.write() anywhere
BrowserPollConnection.ts:480 [Violation] Avoid using document.write().
The page is getting refreshed when I click the button on which the function is called as the button is a submit button in a form. I get this
Navigated to file:///D:/MyPrograms/CredibilityAnalyzer/front-end/pages/selectSuspect.html?name=afs&crime=0&height=1&weight=1&idnumber=1&dob=2021-01-01&hypo=asdf&gender=none
Here is the HTML code:
<!DOCTYPE html>
<html>
<head>
<title>Credibility Analyzer</title>
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700" rel="stylesheet">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.5.0/css/all.css"
integrity="sha384-B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU" crossorigin="anonymous">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="../style/selectSuspect.css">
<script src="https://www.gstatic.com/firebasejs/8.7.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.7.1/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.7.1/firebase-analytics.js"></script>
<script src="../script/form2.js"></script>
</head>
<body onload="fillSuspectList()">
<div class="testbox">
<form>
<div class="banner">
<h1>Credibility Analyzer</h1>
</div>
<div class="btn-block">
<button type="submit" onclick="showInputForm()">Enter new suspect record</button>
<button type="submit" onclick="showSelectSuspect()">Select suspect</button>
</div>
<div class="showInputForm" id="showInputForm" style="display: none;">
<p>Suspect Information</p>
<div class="item">
<label for="name">Name<span>*</span></label>
<input id="name" type="text" name="name" required />
</div>
<div class="btn-block">
<button type="submit" onclick="storeSuspectData()">SUBMIT</button>
</div>
</div>
</form>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
crossorigin="anonymous"></script>
</body>
</html>
It works very rarely, not every time.
This typically indicates a race condition. In this case I suspect that your storeSuspectData is being called when the user submits a form. If that's the case: the default behavior for a form is to send the data to the server, and then redirect to a different page. So unless your handler function cancels this default behavior, the page will be redirected and this may/will interrupt the write to the database.
The solution for this is to cancel the default behavior of the form by calling e.preventDefault() on the event that triggers it, and returning false from the handler.
Related
I use Bootstrap tooltips to create beautiful HTML tooltips for items. I basically have a skill image in the form of a .png image
<img id="skill" src="ice-bolt-inactive.png" data-toggle="tooltip" data-html="true" title="" />
i define the image into a variable
let skillImage = document.getElementById('skill');
then i initiate the tooltip like this:
skillImage.title = '<p class="skill-title">' + iceBolt.name + '</p><p class="skill-text">' + iceBolt.description + '</p><p class="skill-text">' + iceBolt.setLevel() + '</p><p class="skill-text">' + iceBolt.setDamage() + '</p><p class="skill-text">' + iceBolt.setDuration() + '</p><p class="skill-text">' + iceBolt.setManaCost() + '</p><p class="skill-title">' + iceBolt.name + ' Receives Bonuses From: </p><p> ' + iceBolt.description + '</p>';
Now when i click on the skill image, i fire up an onclick function which increments the iceBolt.level++; . This successfully does that ( i also log the iceBolt.level into the console so i confirm it's changing) but the bootstrap tooltip remains unchanged (doesn't reflect the iceBolt.level, even though i've set it up to display it)
Is my usage of the bootstrap tooltip bad or is it that the bootstrap tooltips won't handle something like this. I want to use them as they are responsive and easy to use.
UPDATE:
Code snipper shared, will help you update your tooltip title whenever some particular event occurs in your application.
The idea is: Setting my title dynamically using a function call which returns the updated data.
$("#skill").tooltip({
placement: "right",
title: userDetails, // userDetail() is a function which will return our updated data
html: true,
});
Function will look something like;
// Get user details for tooltip
function userDetails() {
return tooltipText;
}
The event handler in which we update the content of tooltip.
document.querySelector("button").addEventListener("click", () => {
tooltipText += "Add"; // Updating my data
userDetails();// Sending updated Title
})
FULL CODE:
$(document).ready(function () {
// Add tooltip
$("#skill").tooltip({
placement: "right",
title: userDetails,
html: true,
});
});
var tooltipText = "Hello";
// Get user details for tooltip
function userDetails() {
return tooltipText;
}
document.querySelector("button").addEventListener("click", () => {
tooltipText += "Add";
userDetails();
});
<html lang="en">
<head>
<title>Dashboard</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
/>
<link
rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"
/>
<link rel="stylesheet" href="./style.css" />
</head>
<body>
<img
id="skill"
class="skill"
src="https://picsum.photos/100"
data-toggle="tooltip"
data-html="true"
data-selector="true"
alt="skill image"
/>
<p id="ice-bolt-level"></p>
<button>Click Me</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script src="script.js"></script>
</body>
</html>
YOU CAN USE THE SAME LOGIC TO PROCEED FORWARD IN YOU APPLICATION.
For anyone who is looking in the future. This solution is for Bootstrap - 5, using JQuery and Javascript.
Init the Tooltip
var tootTipTitleText = 'True or False';
$(document).ready(function () {
//Enable ToolTip
$('[data-bs-toggle="tooltip"]').tooltip(
{
title: tootTipTitleText,
html: true,
}
);
});
Remove the Previous Tooltip on Button Click
$('[data-bs-toggle="tooltip"]').tooltip("dispose");
Get the value to check.
if(checkBoxValue == true) {
tootTipTitleText = 'true';
} else {
tootTipTitleText = 'false';
}
Init another tooltip
$('[data-bs-toggle="tooltip"]').tooltip(
{
title: tootTipTitleText,
html: true,
}
);
Display The Tooltip
$('[data-bs-toggle="tooltip"]').tooltip("show");
Sample HTML and JS Function
function changeToolTipTitle()
{
$('[data-bs-toggle="tooltip"]').tooltip("dispose");
var checkBoxValue = $("#toolTipCheckBox").is(":checked");
if(checkBoxValue == true)
{
//title="Checked or Unchecked"
tootTipTitleText = 'Checked';
}
else
{
tootTipTitleText = 'Unchecked';
}
$('[data-bs-toggle="tooltip"]').tooltip(
{
title: tootTipTitleText,
html: true,
}
);
$('[data-bs-toggle="tooltip"]').tooltip("show");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<div id="toolTipCheckBoxDiv" class="form-check inputCheckBox" data-bs-toggle="tooltip" title="">
<input class="form-check-input" type="checkbox" id="toolTipCheckBox" value="true" onchange="changeToolTipTitle();" />
<label class="form-label" for="toolTipCheckBox">Check</label>
</div>
Im creating a bus finder application. I want the user to be redirected to a new page after they have input information for the ajax api request. At the moment the information is inserted after page one but on the same page. How do I create a new page with the ajax results once the user has inout the information and sent the request. I have a variable created with the results as a virtual page.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Dublin Concert Listings</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/custom.css" />
<link rel="stylesheet" href="css/theme.min.css" />
<link rel="stylesheet" href="css/jquery.mobile.icons.min.css" />
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile.structure-1.4.5.min.css" />
<script type="text/javascript" src="jquery-3.3.1.min.js"></script>
</head>
<body>
<div data-role="page" id="pageone">
<div data-role="header">
<h1>Get Next Bus Details</h1>
</div>
<div data-role="content">
<div class="content-primary">
<div data-demo-html="true">
<div class="ui-input-search ui-shadow-inset ui-input-has-clear ui-body-inherit ui-corner-all">
<input data-type="search" placeholder="Bus Stop Id" id="bus_stop_id" name="bus_stop_id">
</div>
<input type="button" value="Get Current Update" id="button_get_bus">
</div>
</div>
</div>
</div>
<script type="text/javascript">
//On click of button this function get call
$('#button_get_bus').click(function(){
//Get Enter Bus Id
var bus_stop_id = document.getElementById("bus_stop_id").value;
//If Id is blank then given error
if(bus_stop_id == "")
{
alert("Please enter bus stop number");
return false;
}
// This Function post request to API with the given bus stop id
$.ajax({
url: "https://data.smartdublin.ie/cgi-bin/rtpi/realtimebusinformation?stopid="+bus_stop_id+"&format=json",
dataType: 'json',
success: function(results){
// It returnes json data
var str = JSON.stringify(results);
// Code for parsing json
var myObj = JSON.parse(str);
var destination = myObj.results[0].destination;
var origin = myObj.results[0].origin;
var arrivaldatetime = myObj.results[0].arrivaldatetime;
var departuredatetime = myObj.results[0].departuredatetime;
var routenumber = myObj.results[0].route
var virtualPage = "";
virtualPage +=
'<div data-role="page" data-theme="a" id="virtualPage">'
+ '<div data-role="header">'
+ '<h1>' + origin + '</h1>'
+ '<div data-role="content">'
+ '<h3>Venue: ' + destination + '</h3>'
+ '<h3>Date: ' + arrivaldatetime + '</h3>'
+ '<h3>Time: ' + departuredatetime + '</h3>'
+ '</div'
+ '<div class="wrapper"><a data-role="button" data-transition="slide" href="#pageone">Back</a></div>'
+ '</div>'
+ '</div>';
$(virtualPage).insertAfter($('#pageone'));
}
});
});
</script>
</body>
</html>
Before AJAX request
After AJAX request
I have seen many questions similar to this one on here but none of them seem to fix the problem I am having.
I keep getting the following error-
Uncaught SyntaxError: Unexpected token <
It says the error is in line one of the js file but the sources only shows a red line on line one of the html file.
Should also mention it is running on a go server.
Thanks a mil!
Here is my HTML
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hello, world!</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Sourcing jquery and ajax -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!--external script.js file-->
<script type = "text/JavaScript" src="ChatBot.js"></script>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<style>
body {
padding-top: 65px;
padding-bottom: 100px;
}
</style>
</head>
<body>
<nav class="navbar fixed-top navbar-dark bg-dark">
<a class="navbar-brand" href="#">Eliza chat bot</a>
</nav>
<div class="container-fluid">
<ul class="list-group">
<div class="fixed-bottom bg-dark p-2">
<div class="container">
<div>
<ul class="list-group"></ul>
</div>
<form action="/Chat" method="GET">
<div class="form-group">
<input type="text" class="form-control" id="userInput" placeholder="Talk to eliza...">
</div>
</form>
</div>
</div>
</ul> </div>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
</body>
</html>
and here is my js
const form = $("#userInput");
const listItem = $("#list-group");
//add the keypress function for when the user types an input for eliza to compute
$(document).ready(()=>{
form.keypress(function(event){
const keyCodes = {
ENTER : 13
}
let keyCode = event.keyCode;
//for enter
if(event.keyCode != keyCodes.ENTER){
return;
}
event.preventDefault();
const input = form.val();
form.val(" ");
listItem.append("<li class='list-group-item list-group-item-success'>"+"User : " + input + "</li>");
// GET/POST
const queryParams = {"userInput" : input }
$.get("/Chat", queryParams)
.done(function(response){
var nextListItem = "<li class='list-group-item list-group-item-info'>"+"ELiza : " + response + "</li>";
setTimeout(function(){
listItem.append(nextListItem)
}, 1000);//set timeout to give wait to response
}).fail(function(){
var nextListItem = "<li class='list-group-item list-group-item-danger' >Sorry I'm not home right now.</li>";
list.append(nextListItem);
});
});
});
Does your webserver happen to have a rule where if the requested resources is not found it will default to serving the index.html file? This is a popular configuration for Single Page Applications.
If that is the case, if the server can not find the js file requested it will serve the contents of the html file, which the browser will try parse as JavaScript. Since the first character on the first line of the html file is < you'll get a syntax error since that is not valid JavaScript.
I'm looking to overwrite a div using JS but the issue is that I'm using append so the script keep writing data at the end of the div, I have no idea how to fix that, I tried window.location.reload(true) but, obviously, the data is lost.
Can someone point me to the right direction, actually I'm lost. My goal is to refresh / erase or update the div content, preferably, whiteout reloading the page. Here's a runnable code so you can see the problem. Thanks for you help.
$("#getnews").on("click", function() {
setTimeout(function() {
var path = "https://api.iextrading.com/1.0/stock/"
var stock = document.getElementById('userstock').value
var end = "/news"
var url = path + stock + end
$.getJSON(url, function(data) {
data.forEach(function (article) {
$('#data').append(
$('<h4>').text(article.headline),
$('<div>').text(article.summary),
$('<hr>').text(" "),
);
});
});
},200);
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
<div class="container">
<p>Search for a stock (E.g: msft, aapl or tsla)</p>
<p><input type="text" id="userstock"></p>
<p><a class="btn btn-dark btn-large text-white" id="getnews">Browse</a></p>
<row id="data"></row>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.js"
integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
crossorigin="anonymous"></script>
$("#getnews").on("click", function() {
setTimeout(function() {
var path = "https://api.iextrading.com/1.0/stock/"
var stock = document.getElementById('userstock').value
var end = "/news"
var url = path + stock + end
$.getJSON(url, function(data) {
var html = $("<div></div>");
data.forEach(function (article) {
html.append($('<h4>').text(article.headline));
html.append($('<div>').text(article.summary));
html.append($('<hr>').text(" "));
});
$('#data').html(html);
});
},200);
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
<div class="container">
<p>Search for a stock (E.g: msft, aapl or tsla)</p>
<p><input type="text" id="userstock"></p>
<p><a class="btn btn-dark btn-large text-white" id="getnews">Browse</a></p>
<row id="data"></row>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.js"
integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
crossorigin="anonymous"></script>
Can't you just set the HTML of the container:
var html = $("<div></div>");
html.append($('<h4>').text(article.headline));
html.append($('<div>').text(article.summary));
html.append($('<hr>').text(" "));
$('#data').html(html);
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