Behavior DIFFERS When SCRIPT in STATIC and DYNAMIC - javascript

It has an embedded system, which operates with an IP (example: 192.168.0.237) different from each device, where the Import/Load file functionality depends on JQuery. The goal is to get this feature to work without needing an internet connection, it is currently using pointing to https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js and it works without problems.
Changing the code, to access the "jquery.js" file locally.
The page that loads the UPLOAD functionality is operating on port 8989. This, the path can be placed in the HEAD of the files, like this:
<script type='text/javascript' src='jquery.js'></script>
When running, inspecting the NETWORK tab, we have the result path:
"192.168.0.237:8989\jquery.js"
that is, it maps through port 8989, it fails to find the file, as it is stored in the root with port 80. Therefore, to validate the solution FORCE doing:
<script src='http://192.168.0.237/jquery.js'></script>
I added this instruction at the top of the file inside HEAD, AND the file UPLOAD feature WORKED correctly. Validating, which solution is suitable.
But, in order to work correctly, it must obtain the IP of the device, so a SCRIPT was made using "window.location.hostname" to obtain the IP of the device and assemble the URL.
<script>
let k2 = '#http://';
let k3 = window.location.hostname;
let k4 = '#jquery.js';
let fim = `${k2} ${k3} ${k4}`;
fim = fim.replace(' #', '/');
fim = fim.replace('#', ' ');
fim = fim.replace('// ', '//');
fim = fim.trim();
document.getElementById('demo').innerHTML = window.jQuery;
document.getElementById('kkk').innerHTML = fim;
document.head.appendChild(document.createElement('script')).src = fim;
</script>
In this SCRIPT we have the last line "document.head.appendChild(document.createElement('script')).src = fim"
which inserts the statement to load JQuery into the HEAD. Clicking on the "Check JQuery Status" button, the message that JQuery is loaded and available appears.
But now comes the problem, when pressing the submit button, update, the shown below occurs:
Imagem upload1
Imagem upload2
Imagem upload3
In short, an error occurs because it points to "serverIndex:1" and the correct would be only "serverIndex".
In other words, we have the INITIATOR pointing to "serverIndex:1" which doesn't exist (it doesn't even have to adjust the instruction, a syntax error will happen).
So, in short, with statement adding "jquery.js" STATIC = WORKS, but with statement ADDING "jquery.js" DYNAMICLY DOES NOT WORK.
With the STATIC instruction inserted in the HEAD, we have the expected operation as indicated below: (Note the INITIATOR = serverIndex)
WORKS OK RESULT
I need guidance as I don't know how to solve and also if this solution is suitable.
Below is the rendered code:
<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'>
<script>
function checa() {
if(jQuery) {
alert('Jquery ONLOAD!');
} else {
alert('Jquery NOT HAVE - NUNCA EXECUTA');
}
}
</script>
<script src='http://192.168.0.237/jquery.js'></script>
</head>
<button onclick='checa()'>Check Status JQuery</button>
<form method='POST' action='#' enctype='multipart/form-data' id='upload_form'>
<h4>valor:</h4>
<p id='demo'> </p>
<p id='kkk'></p>
<h3>Verificador de preço</h3>
<h3>Update Firmware</h3>
<input type='file' name='update' id='file' onchange='sub(this)' style=display:none accept='.bin' required>
<label id='file-input' for='file'> Selecione o arquivo ...</label>
<input type='submit' class=btn value='Atualizar'>
<br>
<br>
<div id='prg'></div>
<br>
<div id='prgbar'>
<div id='bar'></div>
</div>
<br>
</form>
<script>
let k2 = '#http://';
let k3 = window.location.hostname;
let k4 = '#jquery.js';
let fim = `${k2} ${k3} ${k4}`;
fim = fim.replace(' #', '/');
fim = fim.replace('#', ' ');
fim = fim.replace('// ', '//');
fim = fim.trim();
document.getElementById('demo').innerHTML = window.jQuery;
document.getElementById('kkk').innerHTML = fim;
document.head.appendChild(document.createElement('script')).src = fim;
</script>
<script> <!-- DOWN IS SCRIPT UPLOAD FILE !-->
function sub(obj) {
var fileName = obj.value.split('\\');
document.getElementById('file-input').innerHTML = ' ' + fileName[fileName.length - 1];
How the code is structured: (it is enclosed in QUOTES because as soon as it is stored in the String)
Code up
Code bottom
Code call String serverIndex
Finally, I hope to be guided on how to resolve the situation and whether this solution is adequate and correct.

Related

Why can't I access javascript function from HTML file?

Fairly basic question here. I've run into a situation where I can't seem to access Javascript functions from within my HTML file, even though I've linked the JS file as a script src. It seems like a pretty simple issue but I can't figure out what the problem is.
I'm trying to add a function called startLogin to an HTML button. I added it as an onclick, but then when I try to click the button, the console says the function is undefined. However the function is clearly defined in the JS file and as far as I can tell the syntax I'm using for the onclick and the script src link is correct.
In addition I've confirmed that the JS file is linked to the HTML file. If I try to manipulate the DOM from the JS file just to do something simple, like set the background to red, that works fine. The problem is when I try to call a function defined in the JS file. Also I've made sure the function I'm trying to call does actually work. If I stick it right in the HTML file inside script tags, it works fine.
I've already tried moving the script tags inside the body at the end of the HTML, as I know that's often the issue, but in this case it didn't work. Can anyone help me identify why I'm unable to access the "startLogin" function from the HTML button?
FYI, this is a javascript project and I'm using Vite.js for bundling. All the other HTML/JS files in my project are playing nicely together, I'm only having an issue with the Login page.
file structure:
|-pages
|-login.html
|-login.js
login.html
<!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" />
<title>Document</title>
<!-- LINK JS FILE -->
<!-- MODULE TYPE IS RELATED TO VITE.JS -->
<script type="module" src="./login.js"></script>
</head>
<body>
<!-- email login form -->
<form name="emailLogin" id="emailLogin" style="display: none">
<div class="row" style="width: 600px">
<div class="col">
<div class="form-row" style="padding-bottom: 10px">
<input
type="email"
class="form-control"
id="emailAddress"
placeholder="email associated with your login"
style="width: 576px"
/>
</div>
</div>
<div class="form-row">
<br />
<button type="button" class="btn btn-primary" onclick="startLogin('email')">
Send Email Login
</button>
</div>
</div>
</form>
</body>
</html>
login.js
// start the login process by generating a code sent either SMS or EMAIL
function startLogin(login_type) {
// local variables
var ajaxResult;
var subs;
var tempString;
// get the login values and set up the call
if (login_type == "phone") {
// get the values
use_country_code = $("#country").val();
use_phone = $("#phoneNumber").val();
use_phone = use_phone.replace(/\D/g, "");
// do the validation
if (use_phone.length < 10) {
$("#errorText").html(
"Phone number doesn't have enough digits, please try again."
);
$("#errorModal").modal("show");
return;
}
// build the url
post_url =
"https://us-central1-dev-api-327415.cloudfunctions.net/user-login?cc=" +
use_country_code +
"&phone=" +
use_phone;
} else {
// get the values
use_email = $("#emailAddress").val();
// do the validation
if (!validateEmail(use_email)) {
$("#errorText").html(
"Email address does not appear to be valid, please check the format and try again."
);
$("#errorModal").modal("show");
return;
}
// build the url
post_url =
"https://us-central1-dev-api-327415.cloudfunctions.net/user-login?email=" +
use_email;
}
// send the request to the server and process the results
$.LoadingOverlay("show");
$.ajax({
type: "POST",
url: post_url,
// process the returned result of the Ajax call
success: function (ajaxResult) {
// see if we have a session token and handle the response
session_token = ajaxResult["session_token"];
if (session_token == "None") {
// hide the login and show the text message area if phone, otherwise hide email and show email message
if (login_type == "phone") {
$("#loginMethod").hide();
$("#phoneLogin").hide();
$("#codeLogin").show();
$("#loginMessage").hide();
$("#textMessage").show();
} else {
$("#loginMethod").hide();
$("#emailLogin").hide();
$("#loginMessage").hide();
$("#codeLogin").show();
$("#emailMessage").show();
}
} else {
// hide everything since already logged in and show the right message
$("#phoneLogin").hide();
$("#emailLogin").hide();
$("#loginMethod").hide();
$("#loginMessage").hide();
$("#codeLogin").hide();
$("#continueLoginAlready").show();
}
},
// process after the Ajax call has been fully completed
complete: function () {
$.LoadingOverlay("hide");
},
// handle total failure
error: function (jqXHR, exception) {
console.log(jqXHR);
console.log(exception);
json_error = jqXHR["responseJSON"];
$("#errorText").html(json_error.error_message);
$("#errorModal").modal("show");
},
});
}
Javascript modules work a bit differently. There, variables and functions are not exposed to the global scope.
If you want to use your function from other parts of the code, you have to set it explicitly on the window object:
function startLogin(...) {
...
}
window.startLogin = startLogin;
an other solution is to set the js at end of the html, than you don't need to use the window object (memory lag)
<html lang="en">
<head>...</head>
<body>
<button type="button" id="myButton">Title</button>
</body>
<script>
function myFunction(){
console.log('running myFunction');
}
const button = document.querySelector('#myButton');
button.addEventListener('click', function clickListener(
{
myFunction();
}
</script>
</html>
the browser is simply stupid, it loads the page from top to bottom and if you load your js after the body all your html is present and you can do it this way.

why does this code break the back button

I feel there is something fundamental missing here.
This is a node app and the getData is an AJAX database call that gets info about a blog post.
I can load the pages just fine, it simply splits the URL string and uses the right-hand side as the postid, then the post id is sent via getData. That part works but I noticed that if I hit the page twice, and hit back it won't load the old page, it just changes the URL in the address bar, but doesn't actually load the page again.
So if say I put http://localhost:3000/post/&2 it will load the post with the id of 2. I then put http://localhost:3000/post/&3 it will load post with the id of 3. Now from there, if I hit back button, I will have the URL in the bar go back to http://localhost:3000/post/&2 but it will retain the data of http://localhost:3000/post/&3
My current idea, is that the back button does not actually treat them as separate URL's for some reason, so it loads the cache it has from http://localhost:3000/post/&3 because http://localhost:3000/post/&2 and http://localhost:3000/post/&3 are the same to it.
<html>
<head>
<link rel="stylesheet" type="text/css" href="../css">
</head>
<body onLoad="buildPage()">
<div id='container'>
<div id='head'>header icons</div>
<div id='body'>
<div id='sidebar'>sidebar
<div id='sidebarLinks'></div>
<div id='sidebarAdSpace'></div>
</div>
<div id='mainpage'>mainpage</div>
</div>
</div>
<script src='../public/grabdata.js'>
</script>
<script>
function buildPage() {
var page=3;
var url= window.location.href.split('&');
var page=url[1];
//alert(param);
getData(page, function(str) {
str = JSON.parse(str);
var linkHTML = '';
var postHTML = '';
linkHTML += "<ul>";
for (var i in str) {
linkHTML += "<li><a href='../post/&" + str[i].id + "'>" + str[i].title + "<i>~" + str[i].published.slice(0, 10) + "</i></a></li>";
}
linkHTML += "</ul>";
postHTML+="<div class='poster'><div class='posterHead'><div class='postTitle'>"+str[0].title+"</div><div class='postSeries'>Part of the "+str[0].series+" series</div></div><div class='postBody'>"+str[0].body+"</div><div class='postAuther'>"+str[0].auther+"</div><div class='postPublished'>"+str[0].published+"</div></div>";
document.getElementById('sidebarLinks').innerHTML = linkHTML;
document.getElementById('mainpage').innerHTML = postHTML;
})
}
</script>
</body>
</html>
well, in case anyone else finds the question useful
i solved my own problem
i misunderstood how the history cache works. it never unloaded the data because it does not recognize a paramater change as a new page.
i solved my issue using pushState and altering the state inside the history itself.
thanks for trying though guys and gals.

How to load an XML file in JavaScript, get specific info from it, and then display it through alert()?

So, I want to make a program that will be able to get user data(a ton of bug names separated by commas), go through, get data for each one, then display all of that data in a table. I have been through rewriting this like 5 times and still nothing happens. Anyone know what is wrong with this code?
My html code:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1 align="center">Bugs</h1>
<p>In the area below, type in each of the insects you want information
about, seperate them with a comma.</p>
<textarea id="insects"></textarea>
<br>
<button type="button" id="go">Find out!</button>
<br>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
document.getElementById('go').onclick = function() {
var input = document.getElementById('insects').value;
var splitted = input.split(',');
for (i = 0; i<splitted.length; i++) {
var bug1 = splitted[i];
var part1 = // I need to assign it to bug1 without any whitespace
var finish = part1.toLowerCase();
find1(bug1);
}
}
function find1(bug) {
var xmlDocument = $.parseXML("externalfile:drive-77136639a78ffb21e72c7c4dfe7f7bb73604aeb3/root/Bugs/bugs.xml");
var pain = $(xmlDocument).find("value[type='" + bug + "'] pain").text();
alert(pain); <!-- This is to see if it works -->
}
</script>
</body>
Here is my XML code(btw the XML file is called bugs.xml and yes they are in the same exact folder in My Drive/Bugs:
<?xml version="1.0" encoding="UTF-8"?>
<bugs>
<bug type="blisterbeetle">
<name>Blister Beetle</name>
<pain>55</pain>
<conservation></conservation>
<habitat></habitat>
<rarity></rarity>
<class></class>
<order></order>
<family></family>
<species></species>
<dangerous></dangerous>
<external></external>
</bug>
</bugs>

how to get textarea input from another HTML page

In a.html:
I have a textarea that is converted into a link after the user clicks the submit button. When the user clicks on the link they are redirected to b.html.
<textarea id="sentenceId">
</textarea>
<br>
<button type="button" id="buttonId" onclick="createLink(document.getElementById('sentenceId').value)">Submit
</button>
<p id="demo">
<a id ="link" href="b.html"></a>
</p>
In b.html:
I would like to display the original text.
In script.js:
function createLink(val) {
document.getElementById("link").innerHTML = val;
document.getElementById('buttonId').style.display = 'none';
document.getElementById('sentenceId').style.display = 'none';
}
If you want to open a new page and get the text there, you could use a post-form and an input[type="hidden"] to send the text and display it afterwards.
If you wand the link to be sendable, you'd either have to encode the text as get-parameter or save it to a database and add the id of the entry to the link.
As #Kramb already mentioned, localStorage is a possibility, but only if you stay on the same browser and both pages have the same domain.
Using localStorage
The localStorage property allows you to access a local Storage object. localStorage is similar to sessionStorage. The only difference is that, while data stored in localStorage has no expiration time, data stored in sessionStorage gets cleared when the browsing session ends—that is, when the browser is closed.
a.html
function createLink(val) {
document.getElementById("link").innerHTML = val;
document.getElementById('buttonId').style.display = 'none';
document.getElementById('sentenceId').style.display = 'none';
localStorage.setItem("textArea", val);
}
b.html
function getText(){
var textVal = localStorage.getItem("textArea");
}
Another option would be to use a query string.
a.html
function navigateTo(val){
window.href.location = "b.html?text=" + val;
}
This will pass the value of the text from textarea with the url during navigation. Once b.html has loaded, you can do the following.
b.html
function getText(){
var url = window.location.href;
var queryIndex = url.indexOf("=") + 1;
var passedText = url.substring(queryIndex);
document.getElementById('foo').value = passedText;
}
This is possible using JavaScript. You can do an AJAX call to another page on you website, and search for an element to get its content. In you're case an textarea
I wrote an example on codepen.io for you. Click here
To make things simpler im using jQuery in this example.
So how does it work?
First of, include jQuery inside the <head> tag of you're website.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
I created the following structure
structure
root
scripts
jQuery.min.js
index.js
index.html
textarea.html
Contents of index.html
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Meta -->
<meta charset="UTF-8" />
<title>My New Pen!</title>
<script type="text/javascript" src="scripts/jquery.min.js"></script>
<!-- Styles -->
<link rel="stylesheet" href="styles/index.processed.css">
</head>
<body>
<button id="clickme">To load the textarea content, click me!</button>
<div id="content">The data from the textarea will be shown here, afte you click on the button :)</div>
<!-- Scripts -->
<script src="scripts/index.js"></script>
</body>
</html>
Contents of texarea.html
<textarea id="textarea">
I am the content of the textarea inside the textarea.html file.
</textarea>
Contents of index.js
(function() {
$(document).ready(function() {
/**
* The button which triggers the ajax call
*/
var button = $("#clickme");
/**
* Register the click event
*/
button.click(function() {
$.ajax({
url: "textarea.html",
type: "GET"
}).done(function(response) {
var text = $(response).filter("#textarea").html();
$("#content").append("<br/><br/><strong>" + text + "</strong>");
});
});
});
})()
So what does index.js do exactly?
As you can see i created an Ajax call to the textarea.html file. The .done function holds the response data. The data inside it can be anything depending on the content of the textarea.html file.
$(response).filter("#textarea").html();
The above piece of code filters out the #textarea div and then gets the innerHTML using the jQuery html() function.
If you want to get the value of the textarea through the [value] attribute, you can replace above line to
$(response).filter("#textarea").val();
I believe you want to do this:
function createLink() {
var textvalue = document.getElementById('sentenceId').value;
document.getElementById("link").innerHTML = textvalue;
document.getElementById("buttonId").className ="hideme";
document.getElementById("sentenceId").className ="hideme";
}
.hideme{
display: none;
}
<textarea id="sentenceId">
</textarea>
<br>
<button id="buttonId" onclick="createLink()">Submit
</button>
<p id="demo">
<a id ="link" href="b.html"/>
</p>

Why is FileReader.readAsText() returning null?

I am trying to read a file in the same directory of an HTML and JavaScript file however it seems to be returning null. Below I have added the code I have from each file.
HTML File:
<html>
<!-- Code to call the Google Maps API and link style.css sheet -->
<body>
<div class="content">
<div id="googleMap"></div>
<div id="right_pane_results">hi</div>
<div id="bottom_pane_options">
<button onclick="get_parameters()">Try It</button>
</div>
</div>
</body>
<script type="text/javascript" src="./javascript.js">
</script>
</html>
JavaScript File:
function get_parameters() {
alert("hi"); // Just to let me know the function is getting called
var freader = new FileReader();
var text;
freader.onload = function(e) {
text = freader.result;
}
freader.readAsText('./test.txt', "ISO-8859-1");
text = freader.result; // To my knowledge, this should be taking the current line freader is on and storing it into text
var div = document.getElementById('bottom_pane_options');
div.innerHTML = div.innerHTML + text;
}
test.txt
Iron
Aluminum
Steel
//etc. for x number of times (depends on data I have parsed previously)
All I would like is for JavaScript to read test.txt and parse it into an array (text). The issue is, when I click the button 'Try It', the alert pops up (telling me the function is being called) and text contains null. I am running all files off my computer and all are in the exact same directory.

Categories

Resources