form button not recognising function - javascript

I have an HTML file with a basic form. I am calling a function on button click, but on click I receive "function is not defined". Everything appears to be in order vis-a-vis pointing to files, so I'm not sure where the disconnect is.
This is the layout:
and these are my index.html and main.js, respectively:
<!--index.html-->
<form action="" method="get" class="form">
<label for="form-input">Paste Key Here: </label>
<input type="text" name="Key Input" id="form-input">
<button id="form-button" type="button" onclick="GWAPIUser()">Click Here!</button>
<script type="application/javascript;charset=utf-8" src="/public/javascripts/main.js"></script>
</form>
/* main.js */
const key = 'authkey';
async function GWAPIUser() {
const response = await fetch(`https://api.guildwars2.com/v2/account/achievements?access_token=${key}`);
const data = await response.json();
console.log(data);
};
Directory was made with express-generator. This is my first time using it, so I'm not sure if that means anything.
Finally, this is the error I receive:
Uncaught ReferenceError: GWAPIUser is not defined at HTMLButtonElement.onclick (?Key+Input=:18)

Browsers do not like application/javascript;charset=utf-8 as a value for the type attribute.
"Non-modular JavaScript" is the default type for a script so you should omit the type attribute entirely in this case. Only include it if you need to specify type="module" or as a hack to store data in an element without rendering it.
<script src="/public/javascripts/main.js"></script>

Related

How to prevent html form refresh on submit?

Hello after searching and trying a lot , i am not able to find the issue so that I am seeking your help to solve my issue.
Here I have a form while clicking on submit button it should call the javascript function and should not redirect or refresh the page .
Here I want to send mail using SMTPJS with attachments by filling the form and choosing the image once the form submitted it should call the sendEmail() function and mail should be send, but when i click on the submit button it's refreshing the page and it's not working accordingly.
<form onsubmit="sendEmail(); reset(); return false">
<div class="col-md-12">
<div class="form-floating">
<input type="file" class="form-control" id="fileupload" required>
<label for="phone">Upload file</label>
</div>
</div>
<div class="col-12">
<button class="btn btn-primary w-100 py-3" type="submit" style="background-color: #0e2e50;">Upload</button>
</div>
</div>
</form>
<script>
function sendEmail() {
var file = event.srcElement.files[0];
var reader = new FileReader();
reader.readAsBinaryString(file);
reader.onload = function () {
var dataUri = "data:" + file.type + ";base64," + btoa(reader.result);
Email.send({
Host: "smtp.elasticemail.com",
SecureToken :"************"
To: 'mail#mail.com',
From: "mail#mail.com",
Subject: "Form Enquiry",
Body : "Sending file:" + file.name,
Attachments : [
{
name : file.name,
data : dataUri
}]
}).then(
message => alert(message)
);
};
}
</script>
I think the issue is in this line 'var file = event.srcElement.files[0];' because from this line it's refreshing the page and a Question mark (?) is coming in the URL. ex.page.html?
One more thing if i am calling the sendEmail() function in the onchange event of the input type file then it's working fine, why so?
You have two problems.
Typo
The first is a typo and is highlighted by the browser telling you:
Uncaught SyntaxError: missing } after property list note: { opened at line 24, column 19
This exception is preventing the function from being created, so the onsubmit function errors when it calls it, and you never reach the return false that prevents the form submission.
Read the error messages in the console in the browser developer tools.
You are missing a comma between SecureToken :"************" and To: 'mail#mail.com'.
Forms don't have files
You said:
var file = event.srcElement.files[0];
Which gets the element that triggered the event (since it is a submit event, that is the <form>) and you try to read the files property from it.
The browser tells you this:
Uncaught TypeError: event.srcElement.files is undefined
Read the error messages in the console in the browser developer tools.
The files property can be found on <input type="file">, not on the <form>.
You need to find the correct element:
var file = event.srcElement.querySelector('[type="file"]').files[0];
Asides
To generally make life easier and avoid these sorts of issues:
Use a linter, like ESLint, and an editor that can use it as a plug in
Use a code formatter to indent code and help locate syntax errors
Don't use intrinsic event attributes (like onsubmit); do use addEventListener
Pay attention to what your debugging tools are telling you
Just change it a little bit:
<form onSubmit="sendEmail(event)">
...
</form>
function sendEmail(event) {
event.preventDefault();
...
}

HTML Form Input to External Javascript Variable

Most of the solutions I have found deal with localized javascript instead of an external file so I am posting this question.
Links to attempted solutions:
Turn HTML Form Input into JavaScript Variable
I want to take a html form input and use that input in an external javascript file.
The html form input comes from index.html
<script src="script/our.js"></script>
<div class="searchbar">
<form action="">
<input type="text" placeholder="search ..." name="query" onchange=formChange()>
<button type="submit">sendit bro</button>
</form>
</div>
<script>
function formChange(){
var searchThis = document.getElementsByName("query").value;
}
</script>
Then, our.js tries to use the variable like so:
var Manager;
(function ($) {
$(function () {
Manager.store.addByValue('q', searchThis);
});
})(jQuery);
With my current setup, if I searched a term ("unlock") the form will send and the page will show it has found 0 documents. It does not say that searchThis is undefined
The back end of my js works with searchThis being replaced by "*:*" to display all records instead of those with the searched string.
EDIT #1 : Manager.jquery.js to see if I need to allow for search term to be a variable an not just a string
REDACTED
EDIT #2 :
I have been trying suggestions below. Currently:
index.htmlchanged
<script>
function formChange(){
var searchThis = document.getElementsByName("query")[0].value;
console.log(searchThis);
window.searchThis = searchThis;
console.log(window.searchThis);
}
</script>
our.jschanged
Manager.store.addByValue('q', window.searchThis);
The console.logs in index.html return my search term. However if I do the same just before window.searchThis is called in our.js it returns as undefined.
EDIT #3
I have been playing with importing the searchThis variable. I cannot import window.searchThis because I get an error for unexpected . In full when I try:
import searchThis from "../index.html"
It gives me an error stating:
Failed to load module script: The server responded with a
non-JavaScript MIME type of "text/html". Strict MIME type checking is
enforced for module scripts per HTML spec.
EDIT #4 : my <form> + <script> section with adjustments
<div class="searchbar">
<form>
<input type="text" placeholder="search Nicola..." name="query" onsubmit=formChange() >
<button type="submit">sendit bro</button>
</form>
</div>
<script>
function formChange(){
searchThis = document.getElementsByName("query")[0].value;
term = searchThis;
console.log(term);
}
</script>
<script defer="defer" src="script/our.js" type="module"></script>
Ive added my form section because I could be doing something wrong here too. When I go to my main page the console.log on our.js has already been logged as undefined. When I enter a search term with onchange instead of onsubmit the console logs from my <script>. Once I hit submit, the page flashes and the log for our.js is again at the top and undefined.
EDIT #5 : pic of logs described above (before submit)
You could use the window object.
Add a new property named searchThis to the window object and assign the obtained value of the searchThis variable.
function formChange() {
var searchThis = document.getElementsByName("query")[0].value;
window.searchThis = searchThis;
}
Then, just call it by using window.searchThis:
var Manager;
(function($) {
$(function() {
Manager.store.addByValue('q', window.searchThis);
});
})(jQuery);
Update: document.getElementsByName("query") returns a NodeList. You could use document.getElementsByName("query")[0] to refer to a single element.
The availability of a variable for reuse in another external file depends on the order of loading or initialization.
The issue that you have is that our.js is running before the window.searchThis is declared.
You can do:
Add a defer attribute in the script tag. Example: <script defer="defer" src="script/our.js"></script>.
OR
Put the <script src="script/our.js"></script> at the end.
Something like this:
<script>
function formChange() {
var searchThis = document.getElementsByName("query")[0].value;
window.searchThis = searchThis;
}
</script>
<script src="script/our.js"></script>

javascript function not defined when hit back button

I have the following example files:
index.html
<body>
<input type="file" name="image" onchange="handleUpload()">
<script>
function handleUpload() {
window.location = 'aa.html';
}
</script>
</body>
aa.html
<body>
success
</body>
After file upload I'm redirected to another page.
When I hit browser back button I get Uncaught ReferenceError: handleUpload is not defined at HTMLInputElement.onchange.
Can someone explain why is this happening? I understand why handleUpload is triggered but why it's undefined?
Update
My app is more complex. I use webpack to bundle my js files into a single file then I reference it in layout before closing body tag.
What i'm trying to do is a image preview when input file is filled. Everything works great but if I hit back button after the form was submitted I get that error.
I manage to avoid this problem by removing onchange from html and added a event listener in one of js file. This approach has a delay on opening the select file window.
Here is your Answer
<input type="file" name="image" onchange="window.location='aa.html'">

Find script that changed the value attribute of a <input /> tag

<form id="search" action="/search" method="get" autocomplete="off">
<div>
<input type="button" name="test_button" value="test" />
</div>
</form>
<script>
document.getElementById("test_button").value = "changed_test"
</script>
Just as the HTML code above shows, I have defined a button with name test_button and value test and changing its value with the code in the script tag.
Now I am debugging a large webpage which is using a mechanism like this using Firebug and Firefox in Linux.
I want to know how I can find the script that changes the value attribute of the <input ... />, but the web page is too large, various <script> and anonymous functions which are auto-executed made it nearly impossible to find the specific script manually.
Since I am in Linux, I cannot use any Microsoft tools to search the whole web page. I only have Firebug and Chrome. Can Firebug realize that? Does anyone have a good idea of how to find the specific <script> that changed the value?
Add some code like this to the document, right after the form with the button:
<script>
var node = document.getElementById("test_button");
Object.defineProperty(node, 'value', {
set: function() { throw new Error('button value modified'); }
});
</script>
This will throw an error when anything tries to modify the button's value.
Expand the error and click the last line number shown. This will take you straight to the line that set the value of the button.
Here's a demo: http://jsfiddle.net/XSJZN/
Tested in Chrome 17.

Uncaught Reference Error: function is not defined

I'm working on an app for webOS that will take a megaupload link(assuming its a video), parse it into a direct link and stream it to a ffplay port for webos called TouchPlay.
I'm working on a basic prototype that will just take the end code on a megaupload link and return a direct link.
Now that I have laid out the basic parts of my application, on to my question. I want to take data in a form in an html page and feed it into a function in an external js script.
Here's the html portion
<html>
<head>
<script LANGUAGE="JavaScript" src="source/main.js"></script>
</head>
<body>
<form NAME="myform" ACTION="" METHOD="GET">
Enter the MegaUpload Code, ex. megaupload.com/?d=glgrn8f1 -> glgrn8f1: <BR>
<INPUT TYPE="text" NAME="inputbox" VALUE="">
<INPUT TYPE="button" NAME="button" Value="Click" onClick="javascript:codeIn(this.form);">
</form>
</body>
</html>
And in my main.js file is in a subdirectory called source and it contains function codeIn(code){ plus the rest of the functions.
Yet when I enter some test data in my web page and hit submit, I get an error in the chrome dev console saying Uncaught Reference Error: codeIn is not defined
I have a very limited experience with html and javascript, but I cant seem to figure this out, I imagine its something really simple that I'm missing.
EDIT: Here's main.js, and yes, I have checked for typos. Just ask if you need to see the contents of any of these functions, but I didn't think they were neccesary.
function codeIn(code){
...
}
function getInfo(url){
...
}
function waiting(timer){
...
}
Ive looked through all these suggestions and it all seems to point to a syntax error, yet when I try to put all the js functions into the head of the html, it works. So thats what I'm doing. I don't change a single thing when I reference it from source/main.js, but whatever.
From the look of it, I think you then need to double check the location of main.js. Verify whether your HTML file is in a location from where main.js can be accessed as source/main.js, rather than something like ../source/main.js (in case your HTML file is in a folder parallel/sibling to the source folder)
The RefereceError in general related to the scope of function that is present and the function call that is being made. It might the source path of the js, html/xhtml/jsp or function scope with in the js file. Hope this helps. Thanks.

Categories