Submit a text string plus file - edited - javascript

I am trying to submit a text string (downloadstr) and 1 second later to submit a file.
I have to do this in plain JS/HTML (microcontroller webserver)
I submit the text using 'GET' to avoid the 'name=' in the string.
I submit the file using POST.
I need to access the file locally first to get the file size which is needed in the text string.
I can get it partially working - BUT
I cannot seem to change the <input id="DN" .value to the variable 'downloadstr' in JS.
NOTE ***** - There seems to be a problem with the JS variable 'downloadstr'.
I can give it any sort of textual value and it will upload fine, but the string ' LOAD(NAND,"EXT/tu480a.ppf?size=641&useack=1"); ' will upload a corrupted string. I cannot see what is wrong with this string.
It displays correctly, but will not upload.
This is the string that it tries to upload:
LOAD NAND � 2.186360E-77XT0.000000tu480a.ppf0.000000size134219621641 2779096485seack6039898721 %29 B
Can some kind person tell me whats wrong? Thanks. Chris
(I've updated via the comments - thanks)
<!DOCTYPE html>
<html>
<body>
<form id="predataform" method="get" action="/index.shtml" accept-charset="utf-8">
<input id="DN" type="hidden" name="DNDATA" value="xxx">
<script>
console.log("downloadstr");
</script>
</form>
<form id="uploadform" action="/index.shtml" enctype="multipart/form-data" method="post">
<p>Please specify a ppt file to upload :
<br>
<input type="file" name="datafilemnu" size="40" onchange="checkFile()">
<input type="button" value="UPLOAD" name="dnip" onclick="submitboth()">
</p>
</form>
<div>
<p id="downstring"></p>
<p id="fsize"></p>
</div>
<script>
var downloadstr = "";
document.getElementById("DN").value = downloadstr;
function checkFile() {
var sFileName = "";
var sFileExtension = "";
var iFileSize = 0;
var iConvert = "";
var node = "";
var node_list = document.getElementsByName("datafilemnu");
for (var i = 0; i < node_list.length; i++) {
node = node_list[i];
if (node.getAttribute("type") == "file" && node.files.length > 0) {
console.log(node.files[0]);
sFileName = node.value;
sFileExtension = sFileName.split(".")[sFileName.split(".").length - 1];
iFileSize = node.files[0].size;
iConvert = node.files[0].size.toFixed(0);
}
if (sFileExtension == "ppf" && iFileSize > 0) {
document.getElementById("fsize").innerHTML =
"Size=" +
iConvert +
" bytes. Estimated time to download = " +
((iConvert * 10) / 115200 / 60).toFixed(1) +
" minutes ";
downloadstr =
'LOAD(NAND,"EXT/' +
node.files.item(0).name +
'?size=' +
iFileSize +
'&useack=1")';
document.getElementById("downstring").innerHTML = downloadstr;
document.getElementById("DN").value = downloadstr;
console.log(downloadstr);
}
}
}
function submitboth() {
document.getElementById("predataform").submit();
setTimeout(function () {
document.getElementById("uploadform").submit();
window.location.reload();
}, 1000);
}
</script>
</body>
</html>

Thanks everybody.
I have found the answer to the main problem of corruption.
The webserver itself was converting the '(' to %28 - hex value (and some of the other characters) for some reason when it was being received.
I will have to check the webserver code. Sorry to cause so much confusion!
However, I have learnt to watch out for miss-spelling in my javascript!!

Related

JavaScript returning null on a function for a simple guessing game

I created a guessing game using JavaScript. Initially, I wrote it in codepen where it ran fine, and when I moved it over to sublime to test it in the browsers as a standalone, the code did not work. I am getting this error: "Uncaught TypeError: Cannot read property 'value' of null at guess" which is line 14 var guessValue = parseInt(guessIn.value); and links back to the HTML of line 20 which is Guess
I can't figure out where the null is coming from. What am I doing wrong or haven't defined properly that is causing the null? I removed the CSS to blank slate it and make sure that wasn't screwing anything up.
//Generate random number between 1 and 500
var randomNumber = Math.floor((Math.random() * 500) + 1);
//Create variables to store info for loops and displaying info back to user
var guessIn = document.getElementById('userGuess');
var guessOut = document.getElementById('guessesMade');
var counter = 0;
//function runs when the guess button is hit
function guess() {
//declare temp local var and store as an integer for conditional testing
var guessValue = parseInt(guessIn.value);
//if statement for finding the value and reporting to the user
//check if the counter is less than 10 and guessValue is not empty
if (counter < 10 && guessValue) {
counter++;
}
//the guess is correct
if (guessValue == randomNumber) {
guessOut.value = guessOut.value + '\n' + "Guess " + counter + " is " + guessIn.value + ':' + ' You have correctly guessed the number. You may escape.';
}
// the guess is greater
if (guessValue > randomNumber) {
guessOut.value = guessOut.value + '\n' +"Guess " + counter + " is " + guessIn.value + ':' + ' Your guess is incorrect. The number I am thinking of is lower.';
}
//the guess is lower
if (guessValue < randomNumber) {
guessOut.value = guessOut.value + '\n' + "Guess " + counter + " is " + guessIn.value + ':' + ' Your guess is incorrect. The number I am thinking of is higher.';
}
//when all 10 guesses are used
else if (counter == 10) {
guessOut.value = guessOut.value + '\n' + "You did not guess the number I was thinking, " + randomNumber + "." + " You have met your end. Goodbye.";
}
return false;
}
//Show the number to guess upon clicking the checkbox for Cheat
function cheat() {
if (document.getElementById('cheat').checked) { document.getElementById('cheatNumber').value = randomNumber;
document.getElementById('cheatShow').style.display = 'inline';
}
else { document.getElementById('cheatNumber').value = '';
document.getElementById('cheatShow').style.display = 'none';
}
}
//function to reset the game
function reset() {
//reset guess value
userGuess.value = "";
//reset text area
guessesMade.value = "";
//reset counter
counter = 0;
//set new random number for play
randomNumber = Math.floor((Math.random() * 500) + 1);
return false;
}
<html>
<head>
<title>Do You Wanna Play A Game?</title>
<script src="game.js"></script>
</head>
<body>
<h1>Do You Wanna Play A Game?</h1>
<h3>A Guessing Game</h3>
<fieldset>
<legend>The Game Starts Now</legend>
<p>Welcome. You have stumbled upon this page. As a consequence, you have been trapped. To get out, the objective is simple.</p>
<p>I am thinking of a number. This number is between 1 and 500. You get ten guesses.</p>
<p>Good luck.</p>
<div id="guessingarea">
<input type="text" id="userGuess" value="394" /><br />
<button onClick="guess();">Guess</button>
<button onClick="reset();">Reset</button>
<br />
<input id="cheat" type="checkbox" value="cheat" onClick="cheat();" />
<label for="cheat">Cheat</label>
<div id="cheatShow" style="display: none;">
<input id="cheatNumber" type="text"/>
</div>
</div>
</fieldset>
<p></p>
<fieldset>
<legend>Let's examine your guess, shall we?</legend>
<textarea id="guessesMade" rows="14" style="width: 100%;"></textarea>
</fieldset>
</body>
</html>
It looks like you are including the script before your html document.
document.getElementById('userGuess');
is called before the element 'userGuess' exists.
I can think of two solutions to this, either include the script at the end of the document, or access this element only when you need it, rather than declaring it at the beginning like so:
var guessValue = parseInt(document.getElementById('userGuess').value);
You have included the script, before the element is available. As soon as the parser, hits the JS file, it will stop the rendering of the page and try to parse javascript. When the script is encountered, the element is still not available.
You have 2 options to make this work.
Move the script tag to before the close of the body element. This will make sure the page has the available elements before manipulating them.
<fieldset>
<legend>Let's examine your guess, shall we?</legend>
<textarea id="guessesMade" rows="14" style="width: 100%;"></textarea>
</fieldset>
<script src="game.js"></script>
</body>
Query the elements every single time inside the guess method since it is only invoked on a click action, which happens only after page is rendered.
function guess() {
var guessIn = document.getElementById('userGuess');
var guessOut = document.getElementById('guessesMade');
//declare temp local var and store as an integer for conditional testing
var guessValue = parseInt(guessIn.value);
......
......
The reason it works on code pen is because, the scripts are executed are deferred to onLoad which makes sure the elements are available on the page.
If you move the variable declarations inside the function it will work. The issue is that the JavaScript code is executed before the document is ready so the guessIn and guessOut variables are initialised to null.
Alternatively you can wrap your JavaScript code in a function that will execute when the DOM is complete.
document.onreadystatechange = function () {
if (document.readyState === "complete") {
// your code goes in here
}
}
See MDN for more details.

Why do I get a type error when trying to access the value of an element stored in a variable?

I’m having trouble storing an input element in a JavaScript variable. Please see the code below. The commented out bits do not work. The code works as it is; however, it is not DRY. It is overly verbose. Storing the element in a variable would clean things up, but when I attempt to do that (and push the value to the x array) I get an “Uncaught type error: cannot read property value of null”.
Please see the markup and script attached. Why do I get this error when I use the variable form of document.getElementById, but not when I hardcode the element over and over?
JavaScript:
var x = [];
var y = [];
//var xInput = document.getElementById("xInput");
//var yInput = document.getElementById("yInput");
//var dataBox = document.getElementById("display");
function insert() {
x.push(document.getElementById("xInput").value);
y.push(document.getElementById("yInput").value);
clearAndShow();
}
function clearAndShow() {
//Clear fields
xInput.value = "";
yInput.value = "";
//Show output
document.getElementById("display").innerHTML = "";
document.getElementById("display").innerHTML += "X: " + x.join(", ") + "</br>";
document.getElementById("display").innerHTML += "Y: " + y.join(", ") + "</br>";
}
HTML:
<body>
<div class="container">
<form>
<h2>Delay Discounting - Enter X (Delay) and Y (Value)</h2>
<input id="xInput" type="number" placeholder="x (delay)" />
<input id="yInput" type="number" placeholder="y (value)" />
<input type="button" value="save/show" onclick="insert()" />
</form>
<div id="display"></div>
</div>
</body>
Paul Roub left a comment that fixed it. I was loading the script in the head of the HTML document with the rest of my source files. This was problematic because the elements referenced by the JS were not created on the DOM yet. When I moved the script to the end of the HTML document, I could then store the element in the variable.

How to stop an automatic refresh using JS

I'm using javascript to create a file explorer in my website.
I have a function wich read each file from my website and change them into a caracters chain with a chain.split() for each file.
Then, in the array created, I search words that I take from a form. And then, with an innerHTML, I rewrite my HTML page with the answers.
It works, but, when the page is rewrite, it automaticly refresh, and I lose all my search reults...
I tried to stop refresh with window.stop(), document.execCommand('stop'), and it's still refresh...
Here my form :
<form name="recherche" onsubmit="javascript:maFonction()">
<INPUT class="finder" type="text" name="maRecherche" placeholder="Enter your search"/>
<input class="press" type="submit" name="search" value="Search"/>
<p style="margin-left:5%">It may take five secondes...</p>
</form>
And here, the writing part of my JS function :
var mesResultats = "";
if (bin > 0)
{
a = 0;
mesResultats += 'your search <u><b>' + words + '</u></b> can be found here : <BR><BR>';
for (var i = 0; i < mesLiens.length; i++)
{
if (mesLiens[i] != mesLiens[i-1] )
{
var monLien = '<div style="margin-left:5%; margin-right:5%; text-align:justify;">' + mesTitres[a] + '' + '<BR></div>';
mesResultats += monLien + '<hr>';
}
a++;
}
}
else
{
var monLien = 'Homepage';
mesResultats += 'No answer corresponding to your search <u><b>' + words + '</u></b>... ' + monLien + '</div>';
}
elemnt = document.getElementById("result");
elemnt.innerHTML = mesResultats;
If anyone have an idea of how to keep my search results, thank you !
(PS : I can't show you with a link...)
Add return false into the onsubmit event, to don't refresh the page.
HTML :
<form name="recherche" onsubmit="return myFunction();">
Javascript :
function myFunction(){
return false;
}
In case someone has the same situation as me, the application was using <meta http-equiv="refresh" content="3"> and was refreshing the content every 3 seconds. The solution for me was to execute window.stop(); directly from the console.

Create a inputbox which writes to textarea(php)

Just for fun am I creating a chatroom for one of my school classes.
What I'm after is a JavaScript, with a inputbox which pops up, once a button (add url) is pushed, where the user can paste a url which then gets written in the textarea.
I want this feature just so "http://" gets placed in front of the added url.
Been trying with this script (which looks correct to me... but it doesn't work)
<input type="button" id="s_5" onclick="addUrl()">
<script>
function addUrl()
{
var x;
var nettside=prompt("Type in URL:","www.example.com");
if (nettside!=null)
{
x="http://" + nettside + ";
document.getElementById("area").innerHTML=x;
}
}
</script>
yeah, the textarea it's supposed to write to:
<textarea name="txt" id="area" class="typo_vind" placeholder="......" autofocus title="Type your message here, have a great day!"></textarea>
EDIT
HTML:
<input type="button" id="s_5" onclick="javascript:formatText(addUrl())">
JS:
<script>
function addUrl()
{
var x;
var nettside=prompt("Skriv inn lenkeadressen her:","www.testtest.com");
if (nettside!="")
{
x="" + "BESKRIVELSE AV LENKEN" + "";
document.getElementById("area").value=x;
}
}
</script>
Two problems remains.
I don't want that script to clean out the textarea
I don't want the <undefined></undefined> to get added to the end
This is the result with the script as it is now:
<a href=http://www.eksempel.com>__BESKRIVELSE_AV_LENKEN__</a><undefined></undefined>
EDIT 2
Solved the problem where the script cleaned out the texarea with this:
<script>
function addUrl()
{
var x;
var nettside=prompt("Skriv inn lenkeadressen her (uten http://):","www.eksempel.com");
{
x="<a target =_blank href=http://" + nettside + ">" + "__BESKRIVELSE_AV_LENKEN__" + "</a>";
var Field = document.getElementById('area');
var val = Field.value;
var selected_txt = val.substring(Field.selectionStart, Field.selectionEnd);
var before_txt = val.substring(0, Field.selectionStart);
var after_txt = val.substring(Field.selectionEnd, val.length);
Field.value = before_txt + x + after_txt;
}
}
</script>
So now all that's missing is removal of the <undefined></undefined>-tags.
HTML: <input type="button" id="s_5" onclick="javascript:addUrl()">
SOLVED!
You should check the console of your browser - it always notifies about what error has occurred.
You have a typo in this line:
x="http://" + nettside + ";
The ending + " should be deleted.
Also, here:
document.getElementById("area").innerHTML=x;
you should use value instead (normally you do this with for elements):
document.getElementById("area").value=x;
This might not cause problems in the browser you are using, but might lead to strange behaviour under certain circumstances :).

How do I import, edit, and replace text in a txt file?

Using a client side script in a webpage (no server code), like javascript, how do I import, edit, and replace text in a txt file? I am simply trying to use two variables (Name and IP Address) and replace them in a text file. The existing text file is very long and I would like to automate this process. It would be nice for the script to also automatically create a new text file each time it is submitted. THANKS!
Here's my code:
<html>
<head>
<title>TExt File Changer v1</title>
<script type="text/javascript">
function findaNamendReplaceAll() {
var findaName = "Site_Name";
var findaCIP = "192.168.0.5";
var replaceaName = document.myInput.replaceWithName.value;
var replaceaCIP = document.myInput.replaceWithCIP.value;
var fulltexta = document.myInput.fulltext.value;
/*
var nr = new RegExp(findaName,"ig");
var tmp = fulltexta.replace(/Site_Name/gi, replaceaName).replace(/192.168.0.5 /gi,replaceaCIP);
document.myInput.fulltext.value = tmp;
*/
document.myInput.fulltext.value = fulltexta.replace(/Site_Name/gi, replaceaName).replace(/192.168.0.5/gi,replaceaCIP);
}
var str += ‘SECTION ethernet’/n;
str += ‘ETHERNET=UP’/n;
str += ‘BOOTP=server’/n;
str += ‘HOSTNAME=Site_Name’/n;
str += ‘IPADDR=192.168.0.4’/n;
str += ‘NETMASK=255.255.255.0’/n;
str += ‘DNS=‘/n;
str += ‘DHCP_RANGE_L=192.168.0.20’/n;
str += ‘DHCP_RANGE_U=192.168.0.100’/n;
str += ‘SEARCH=‘/n;
str += ‘ZEROCONF=YES’/n;
str += ‘ETH0_ADD_DEFAULT=on’/n;
str += ‘ENDSECTION ethernet’/n;
str += ‘‘;
</script>
</head>
<body>
<form name="myInput" onsubmit="return false">
<h1>Configuration Tool</h1>
New Site Name: <input type="text" id="replaceWithName" name="replaceWithName" value="">
<br><br>
New Camera IP: <input type="text" id="replaceWithCIP" name="replaceWithCIP" value="">
<br><br>
<button onclick="findaNamendReplaceAll()">Go</button>
<br><br>
<textarea id="fulltext" name="fulltext" rows="20" cols="100">
SECTION ethernet
ETHERNET=UP
BOOTP=no
HOSTNAME=Site_Name
IPADDR=192.168.0.4
NETMASK=255.255.255.0
DNS=
DHCP_RANGE_L=
DHCP_RANGE_U=
SEARCH=
ZEROCONF=YES
ETH0_ADD_DEFAULT=on
ENDSECTION ethernet
</textarea>
<br>
<button onclick="document.getElementById('fulltext').value = ''">Clear</button>
<button onclick="document.getElementById('fulltext').value = str">Restore</button>
</form>
</body>
</html></pre>
You can do it easily, provided you adhere to two limitations.
1) Internet Explorer on windows
2) Use of ActiveXObjects
I did a project that required assembling various data as found in excel spreadsheets. My input file was a hand-edited json file - specifying things like filenames and paths. Once the json was loaded, I used an ActiveXObject to open and control Excel in just the same manner as one would from within a VBA program.
As a result, I don't have any code to load arbitrary data from an arbitrary filename.
However, this snippet should give you enough to get started.
Note: The code assumes that IE still gives you a fully qualified path for any file selected with an <input type='file'/> Chrome, FF and Opera only give you the filename - they do not tell you which folder it resides in.
function byId(e){return document.getElementById(e);}
function writeDataToFile()
{
var mFSO = new ActiveXObject("Scripting.FileSystemObject");
var mFile = mFSO.createtextfile(outputFilename);
mFile.write( byId('outputTextArea').value );
mFile.close();
alert("text saved to '" + outputFilename + "'");
}

Categories