no matter what i try it wont write to the file
HTML
<label> Firstname </label>
<input type="text" id="firstname" size="15"/> <br> <br>
<label> Lastname: </label>
<input type="text" id="lastname" size="15"/> <br> <br>
<label> number of people: </label>
<input type="number" id="number" size="15"/> <br> <br>
<label>what day would you like:</label><br>
<input type="text" id="day" size="15"/> <br> <br>
<button onclick="WriteToFile; document.getElementById('firstname').value = '';
document.getElementById('firstname').value = ''; document.getElementById('lastname').value = '';
document.getElementById('lastname').value = '';
document.getElementById('number').value = '';
document.getElementById('day').value = ''">book on in</button>
<br>
Script
const booking = {
firstName:getElementById("firstname"),
lastName:getElementById("lastname"),
people:getElementById("number")
};
import java.io.FileWriter; // Import the FileWriter class
import java.io.IOException; // Import the IOException class to handle errors
function WriteToFile {
try {
FileWriter myWriter = new FileWriter("book.txt");
myWriter.write(booking);
myWriter.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
here is my code, ugly as it may be, I've been going at this for weeks and I have no clue why its not doing what I'm telling it to do
It looks like you are loading libraries from Java, not JavaScript (import java.io.FileWriter...). Javascript in a browser cannot write data to files. You can use something like ajax and php, where you send data from your Javascript to php, and then use php to write the data to a file.
Here is some more info that should help you get started with using Ajax/PHP:
https://code.tutsplus.com/tutorials/how-to-use-ajax-in-php-and-jquery--cms-32494
Remember you will need jQuery to use ajax.
There are also other ways you can do this, ajax/php is just one of them.
Related
Problem: I want to read a user input on the client-side, do some processing on the variable using JavaScript, still on the client-side, then POST the modified variable to the server-side (Node.js).
Research: There are a few similar questions on Stackoverflow, but the answers are not the questions to my requirement. I read about Ajax and Fetch, but they focused on collecting info from the server rather than sending a JS variable from the client-side to the server. I am not sure about using WebSockets for such a simple task.
Code:
The following code is in an EJS template.
I want to POST variable name to Node.js in the following code:
<body>
<div>
<label for="name">Name: </label>
<input id = "name" type="text"> <br><br>
<label for="name">City: </label>
<input id = "city" type="text"> <br><br>
<button id="submit">Submit</button>
<button id="capitalize">Capitalize Everything</button>
<button id="clear">Clear</button>
</div>
<p>
Your name is <span id="outputName">____</span>. The city in which you live is <span id = "outputCity">____.</span>
</p>
<script>
var submit = document.getElementById("submit");
submit.onclick = () => {
var name = document.getElementById("name").value;
var city = document.getElementById("city").value;
name = "+" + name //some processing on varibale name, can be anything else
document.getElementById("outputName").innerText = name;
document.getElementById("outputCity").innerText = city;
}
</script>
<form action="/posty" method="post">
<label for="verse"></label>Search The Bible <br></label>
<input type="hidden" id ="id" name = "name" value = "name">
<button type="submit">Submit</button>
</form>
</body>
The related serverside code:
app.post('/posty', (req,res) => {
console.log(req.body.name)
})
In the following:
<input type="hidden" id ="id" name = "name" value = "name">
what is transferred to the server is the string "name" , not the content of the JS variable name. I tried to put the name between <%= %> as it was an ejs template, but it didn't work.
Problem Summary: How to read the user input on the client-side, modify it with JS on the client-side, and then POST it to the sever-side (Node.js)?
Thank you
You should use Ajax to Post data to your route (/posty).
$(document).on("click", "#submit", function () {
var name=$('#name').val()
var city =$('#city').val()
var outputName=$('#outputName').text('name')
var outputCity=$('#outputCity').text('city')
var id= $('#id').attr('id')
var obj=JSON.stringify({
name:name,
city:city,
id:id,
outputName:outputName,
outputCity:outputCity
})
$.ajax({
type: "POST",
url: "/posty",
data:obj,
contentType: "application/json",
beforeSend:function(){
//can put some spinner,before request
},
success: function (res) {
//respond from Backend
if(res){
...
}
},
});
});
//On server side
app.post("/posty", urlencodedParser, async (req, res) => {
try {
await db.query(...);
res.send(true);
}
} catch (err) {
console.log(err);
}
})
Sorry for Jquery,its easier to write..
You should specify the name attribute correctly of each input, so that you can send a HTTP POST request with the payload you want.
<body>
<form action="/posty" method="post">
<label for="name">Name: </label>
<input id="name" name="name" type="text">
<label for="city">City: </label>
<input id="city" name="city" type="text">
<button type="submit">submit</button>
</form>
</body>
If you want to modify the input value before sending the request, you can define a custom function, modify input value in it, and use the native fetch API to send it.
<body>
<script type="text/javascript">
function customSubmit() {
const name = document.getElementById('name').value + ' mock';
const city = document.getElementById('city').value + ' mock';
fetch('/posty', {
method: 'POST',
body: JSON.stringify({ name, city })
})
}
</script>
<form onsubmit="event.preventDefault(); customSubmit()">
<label for="name">Name: </label>
<input id="name" name="name" type="text">
<label for="city">City: </label>
<input id="city" name="city" type="text">
<button type="submit">submit</button>
</form>
</body>
I am using javascript for validating a form in django template, but it's not working,
the DOM events are not fetching the values. even if i give valid input
to form the console says empty string
HTML snippet
<form onsubmit="return validate_hotel()" action="confirm_hotel/{{hotel_name}}" method="post">
{% csrf_token %}
<div id="left">
<label>Check in date</label>
<input id="checkin" type="date" autocomplete="off" name="checkin" > <br><br>
<label>Number of guests</label><br>
<select autocomplete="off" name="guests" id="guests">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select><br><br>
<label>Username</label>
<input id="HotelUsername" type="text" name="username" autocomplete="off">
</div>
<div id="right">
<label>Check out date</label>
<input id="checkout" type="date" autocomplete="off" name="checkout"> <br><br>
<label>Number of rooms</label><br>
<select autocomplete="off">
<option value="1">1</option>
<option value="2">2</option><br>
</select><br><br>
<label> password</label>
<input id="password" type="password" autocomplete="off" name="password" >
</div>
<br><label id="hotel_error_message"> {{error_message}} </label><br>
<button type="submit">Confirm booking</button>
</form>
here is the javascript function i am using to validate things.
i am using document.getElementById() method to fetch the input values.
function validate_hotel()
{
var hotel_username = document.getElementById("HotelUsername").value;
var checkin = document.getElementById("checkin").value;
var checkout = document.getElementById("checkout").value;
var hotel_password = document.getElementById("password").value;
var date_regx = /^(19|20)\d\d([- /.])(0[1-9]|1[012])\2(0[1-9]|[12][0-9]|3[01])$/
var username_regx = /^[a-zA-Z0-9_$.#]+$/
var password_regx = /^(?=.*\d).{4,12}$/
var valid = true;
console.log(hotel_username, checkin, checkout, hotel_password);
if (! username_regx.test(hotel_username))
{
valid = false;
}
if (! password_regx.test(hotel_password))
{
valid = false;
}
if (! date_regx.test(checkin))
{
valid = false;
}
if (! date_regx.test(checkout))
{
valid = false;
}
if (!valid)
{
document.getElementById("hotel_error_message").innerHTML = "Invalid inputs";
}
return valid;
};
Javascript code is executed by the browser (client side) and It is not related to backend (django etc ...). Your code has no problem and works correctly.
To check javascript code I'm using Firefox debugger. It is possible to create break points in your javascript code and watch the variables to check if they get value or not.
In Firefox browser, open debugger.
Find the file that contains javascript code
create some break points on some lines
execute your code (submit the form)
and then by hovering the mouse on your variables check if they get value or
not. you can also add some watch to check variables.
when your code is stopped at break points, checking the value of variables is also
available in console.
Anyway, the code works correctly check if you have some elements with same name or something like this.
So I am currently working on this form validation part for this web-based app. Trying to apply some front end js code on the ejs file as shown below,
<body>
<h1>Doctor</h1>
<p>Registration</p>
<!--physician route-->
<div id="doc_reg">
<form method='POST'onsubmit="return formValidation()"action="/physician/loggedin">
<label>Username:</label>
<input type="text" id="user_name" name="user_name">
<label>Email:</label>
<input type="email" id="user_email" name="user_email">
<label>Type in First Name:</label>
<input type="text" id="first_name" name="first_name">
<label>Type in Last Name:</label>
<input type="text" id="last_name" name="last_name">
<label>Create your password:</label>
<input type="text" id='password_1' name='password_1'>
<label>Confirm your password:</label>
<input type="text" id='password_2' name='password_2'>
<button type="submit">Register</button>
</form>
</div>
<script src="../../public/doclogin.js"></script>
</body>
</html>
the js code that I am trying to implement here (made it simple just for the sake of convenience in communication)
function formValidation(){
const user_name = document.getElementById('user_name').value
const user_email = document.getElementById('user_email').value
const first_name = document.getElementById('first_name').value
const last_name = document.getElementById('last_name').value
const password_1 = document.getElementById('password_1').value
const password_2 = document.getElementById('password_2').value
//we will leave the creating password part later, because it is such a pain in the ass
if (user_name==="" || user_email==="" || first_name==="" || last_name===""|| password_1===""|| password_2===""){
alert("Information Missing for Required Entries")
return false
}
}
I don't know why the validation does not work the way it is expected.
However, when I make a form on a pure html file with the same js code, it works.
Why is that??
use && to check for all required fields
Answer to this question can be found here How to include external .js file to ejs Node template page.
I'm trying to send emails with a generated pdf, i can use uploadcare for the user to specify which file but i want this to be done automatically, i.e. the file uploaded is the pdf. At the moment the form is sending but the my_file part is missing
<form id="contactform" method="POST">
<input type="text" name="name" placeholder="Your name">
<input type="email" name="_replyto" placeholder="Your email">
<input type="hidden" name="_subject" value="Website contact" />
<textarea name="message" placeholder="Your message"></textarea>
<input type="hidden" name="my_file" data-public-key="key_here" />
<input type="text" name="_gotcha" style="display:none" />
<input type="submit" value="Send">
</form>
js
const filetostore = fetch()
console.log(filetostore)
async function fetch(){
const itemToStore = document.getElementsByClassName("itemName");
const itemQty = document.getElementsByClassName("quoteQty");
const itemPrices = document.getElementsByClassName("quotePrice");
const itemTotal = document.getElementsByClassName("quoteTotal");
const totalCost = "Total Cost" + ":" + document.getElementById("quoteTotalCost").innerText;
await fn(itemToStore, itemQty, itemPrices, itemTotal, totalCost)
}
var my_file = uploadcare.fileFrom('input', filetostore);
$('input[name="my_file"]').val(myfile)
console.log(my_file)
var contactform = document.getElementById('contactform');
contactform.setAttribute('action', '//formspree.io/' + 'yy92' + '#' + 'gmail' + '.' + 'com');
The uploadcare.fileFrom method returns a promise-based uploadcare file instance. If you want to add a file URL in the form, you need to get it first.
var my_file = uploadcare.fileFrom('input', filetostore);
my_file.done(function(fileInfo) {
$('input[name="my_file"]').val(fileInfo.cdnUrl);
});
Also, the filetostore argument should be a HTMLInputElement containing a file to upload. It's not clear from the code snippet what the fetch() function returns.
I am working on a simple ASP.NET project. I have HTML and a JS file. I am trying to send the values of the form inputs to the JS file, but it seems to be broken for some reason.
My form looks like:
<div class="set-the-clock">
<form name="settheclock">
<span>Hours: </span><input type="text" id="fhours" value=""><br>
<span>Minutes: </span><input type="text" id="fminutes" value=""><br>
<span>Seconds: </span><input type="text" id="fseconds" value=""><br>
<input type="button" id="send" value="Enter">
</form>
and my JS is:
var setHour = document.getElementById("fhours").value;
var setMinute = document.getElementById("fminutes").value;
var setSecond = document.getElementById("fseconds").value;
and the function that meant to use it:
function setTheClockByButton() {
setTheClock(setHour, setMinute, setSecond);
alert(setHour);
}
If I put a number to the value in the HTML form it works fine(like this)
<span>Hours: </span><input type="text" id="fhours" value="3"><br>
but it not accepting any data from the keyboard.
And of course I have the onclick function associated to the form:
document.getElementById("send").onclick = setTheClockByButton;
(otherwise it'd make no sense).
Move those assignment statements inside the function:
function setTheClockByButton() {
var setHour = document.getElementById("fhours").value;
var setMinute = document.getElementById("fminutes").value;
var setSecond = document.getElementById("fseconds").value;
setTheClock(setHour, setMinute, setSecond);
alert(setHour);
}
Now each time the button is clicked (and note that I'm assuming that part works, since you say it does), the values of the input fields will be fetched so that the clock update function is working with up-to-date values.
You need an onclick event:
<div class="set-the-clock">
<form name="settheclock">
<span>Hours: </span><input type="text" id="fhours" value=""><br>
<span>Minutes: </span><input type="text" id="fminutes" value=""><br>
<span>Seconds: </span><input type="text" id="fseconds" value=""><br>
<input type="button" id="send" value="Enter" onclick="setTheClockByButton()">
</form>
</div>
<script>
function setTheClockByButton() {
var setHour = document.getElementById("fhours").value;
var setMinute = document.getElementById("fminutes").value;
var setSecond = document.getElementById("fseconds").value;
alert(setHour);
}
</script>