How to get response from server without refreshing and using JQuery/AJAX? - javascript

Is there any "right" way to get response from server without using JQuery/AJAX and of course without refreshing page?
server.js:
var http = require('http');
var url = require('url');
var qs = require('querystring');
var static = require('node-static');
var file = new static.Server('.');
http.createServer(function(req, res) {
if (req.method == 'POST' && req.url == "/reglog.html") {
var body = '';
req.on('data', function (data) {
body += data;
// Destroy connection if data is too large for it
if (body.length > 1e6) {
req.connection.destroy();
}
});
req.on('end', function () {
//it's time to parse body
var post = qs.parse(body);
//send response everything is ok
if (post.email.length > 0 && post.pswrd.length > 0 && post.login.length > 0) {
//also console.log to see what was sent from client
console.log(post);
res.end('Everything is good!');
} else {
// ...or not ok
res.end('Everything is bad!');
}
});
} else if (method = 'GET') {
file.serve(req, res);
}
}).listen(8080);
So, there's reglog.js:
var xhr = new XMLHttpRequest();
var uemail = document.getElementById("email"); //HTML element for user's email
var ulogin = document.getElementById("login"); //HTML element for user's login
var upswrd = document.getElementById("pswrd"); //HTML element for user's password
var message = document.getElementById("message"); //HTML element for response from server
function hide(tout) {
if (tout === undefined) tout = 2500;
return setTimeout(function() {
message.innerHTML = "";
}, tout);
}
document.getElementById("btn").onclick = (function createUser(){
var email = uemail.value;
var login = ulogin.value;
var pswrd = upswrd.value;
//XHR part starts//
var body = "email="+email+"&login="+login+"&pswrd="+pswrd;
//I know that email, login and pswrd should be with encodeURIComponent, but in my case it's not a problem and using it won't solve my main problem
xhr.open("POST","/reglog.html",true);
xhr.send(body);
message.style.color = "black";
xhr.onload = function() {
message.innerHTML = xhr.responseText;
}
//XHR part ends//
});
document.getElementById("lbtn").onclick = (function logMenu(){
document.getElementById('logform').style.display = "block";
document.getElementById('regform').style.display = "none";
});
document.getElementById("rbtn").onclick = (function regMenu(){
document.getElementById('regform').style.display = "block";
document.getElementById('logform').style.display = "none";
});
And reglog.html:
<HTML>
<HEAD>
<meta charset="utf-8">
<style>
.button{
position: absolute;
top: 45%;
bottom: 55%;
left: 15%;
}
</style>
</HEAD>
<BODY>
<form id="regform" action="/reglog.html" style="display:block;">
<center><p>Register</p>
E-mail: <input type="email" id="email" name="email" autocomplete="off"><br>
Login: <input type="text" id="login" name="login" required autocomplete="off"><br>
Password: <input type="password" id="pswrd" name="password" required autocomplete="off"><br>
<span id="message"></span><br>
<div class="button">
<input type="submit" id="btn" value="Register"/><br><br>
<input type="button" id="lbtn" value="Back to log in"/></div>
</center>
</form>
<form id="logform" style="display:none;">
<center><p>Log in</p>
Login: <input type="text" id="login2" autocomplete="off"/><br>
Password: <input type="password" id="pswrd2" autocomplete="off"/><br>
<span id="message2"></span><br>
<div class="button">
<input type="button" id="btn2" value="Log in"/><br><br>
<input type="button" id="rbtn" value="Registration"/></div>
</center>
</form>
<script async src="/reglog.js"></script>
</BODY>
</HTML>
As you can see I can get response on client side in
<span id="message"></span>
But I can see it for ~0.5 sec and after that there would be page refreshing. And that is not the best way to see results. My question: is it possible to see this response in "span" for more than ~0.5 sec? I mean, maybe refresh page and then show this response? I don't get how to do it because there is always response coming (for 0.5 sec) and then page refreshing.
Also I don't know if it's possible to do that without AJAX/JQuery.
I would glad to get any help because it's the question that torments me for two days, and I didn't find any reasonable answer via google.

Your code looks fine you just need to prevent the default action of the form submitting the traditional (page reload) way when you click the submit button.
document.getElementById("btn").onclick = (function createUser(e){
e.preventDefault();
// rest of function
});

Related

405 Method Not Allowed - The method is not allowed for the requested URL

I am going to get input from a message form (HTML) in js, but it shows The method is not allowed for the requested URL. Can anyone help me find where is the issue? Thanks!
js code:
var socket = io.connect("http://" + document.domain + ":" + location.port);
socket.on("connect", async function () {
var usr_name = await load_name();
if (usr_name != "") {
socket.emit("event", {
message: usr_name + " just connected to the server!",
connect: true,
});
}
var form = $("form#msgForm").on("submit", async function (e) {
e.preventDefault();
// get input from message box
let msg_input = document.getElementById("msg");
let user_input = msg_input.value;
let user_name = await load_name();
// clear msg box value
msg_input.value = "";
// send message to other users
socket.emit("event", {
message: user_input,
name: user_name,
});
});
});
HTML form:
<form id="msgForm" action="" method="POST" style="bottom:0; margin: 0% 0% 0% 0%;">
<div class="input-group mb-3">
<input type="text" class="form-control" placeholder="Message" aria-label="Message" id="msg">
<div class="input-group-append">
<button class="btn btn-success" type="submit" id="sendBtn">Send</button>
</div>
</div>
</form>
Well, this is quite simple and is basic JavaScript.
Fetch the input using querySelector or get it by its ID.
Take the input and use .value
const input = document.querySelector("#msgForm");
console.log(input.value);

Google App Script setTimeout Function problem

I have a typical Google App Html form that records the data entered in a spreasheet.
Here are the files.
HTML Form:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<?!= include("css");?>
</head>
<body>
<h2>Feedback Form</h2>
<div id="message"></div>
<!--- BUTTON New registration --->
<br /><input id="button-responder" type ="button" value = "New registration"
onclick="submitResponder('button-responder'),
submitTransition('message');" style="display:none;" />
<!--- FORM --->
<form id="my-form">
<br /><input id="name" type="text" name="name" placeholder="Your Name">
<br /><input id="email" type="email" name="email" placeholder="Your Email">
<br /><textarea id="comment" rows="10" cols="40" name="comment"></textarea>
<!--- BUTTON submitForm --->
<br /><input id="btn" type="button" value="Submit"
onclick="submitForm(this.parentNode),
document.getElementById('my-form').style.display='none',
submitResponder('button-responder'),submitTransition('message');" />
</form>
<?!= include("test-js");?>
</body>
</html>
Google Script:
function doGet(request) {
return HtmlService.createTemplateFromFile('index')
.evaluate();//not all caps but it has to match the name of the file and it doesn't - Change to PAGE
}
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename)
.getContent();
}
function submitData(form) {
var subject='New Feedback';
var body=Utilities.formatString('name: %s <br />Email: %s<br />Comment: %s', form.name,form.email,form.comment);
var folderId = "my-folder-ID"; // Please set the folder ID. // Added
var blob = Utilities.newBlob(body, MimeType.HTML, form.name).getAs(MimeType.PDF); // Added
var file = DriveApp.getFolderById(folderId).createFile(blob); // Added
return Utilities.formatString('name: %s <br />Email: %s<br />Comment: %s<br />
PDF: <a target="_blank" href="%s">see your PDF file</a>',
form.name,form.email,form.comment,file.getUrl());
function userClicked(userInfo){
var url = "https://docs.google.com/spreadsheets/d/my-spreadsheet-ID";
var ss = SpreadsheetApp.openByUrl(url);
var ws = ss.getSheetByName("Data");
ws.appendRow([userInfo.name, userInfo.email, userInfo.comment]);
}
test-js
<script>
function submitForm(form) {
google.script.run
.withSuccessHandler(function(value){
document.getElementById('message').innerHTML = value;
document.getElementById('name').value = '';
document.getElementById('email').value = '';
document.getElementById('comment').value = '';
})
.submitData(form);
}
function submitResponder() {
var x = document.getElementById("button-responder");
var xx = document.getElementById("my-form");
var xxx = document.getElementById("message");
if (x.style.display === "none") {
x.style.display = "block";
xx.style.display = "none";
xxx.style.display = "block";
} else {
x.style.display = "none";
xx.style.display = "block";
xxx.style.display = "none";
}
}
function submitTransition() {
setTimeout(function() {
document.getElementById('message').style.color = 'blue';}, 2500);
}
document.getElementById("btn").addEventListener("click",doStuff);
function doStuff(){
var userInfo = {}
userInfo.name = document.getElementById("name").value;
userInfo.email = document.getElementById("email").value;
userInfo.comment = document.getElementById("comment").value;
google.script.run.userClicked(userInfo);
document.getElementById("name").value= "";
document.getElementById("email").value= "";
document.getElementById("comment").value= "";
}
</script>
css:
<style>
#message {
color: transparent;
}
</style>
QUESTION
Now in Google Script file function
function submitData (form)
and in test-js file function
function doStuff ()
they do their job well but with a latency of around 2.5s
then for Google Script to file the function
return Utilities.formatString
can show the result (name - email - comment - PDF Url)
its conclusion must be awaited, 2.5s.
Functions in variables.
In test-js file function
function submitResponder ()
makes the fields linked to the ID (message) visible with variables
name: example-name
email: example-email
comment: example-comment
PDF: see your example-PDF file
and the field linked to the ID (button-responder)
"New registration" button
Then upon loading the index.html page
the form and the "submit" button are shown,
edit the fields by clicking on submit
the form is hidden, the "New registration" button appears
and after about 2.5s the edited fields (name-email ....) also appear.
Click on the button "New registration" below
the form reappears as at the beginning, clearly not with a reload page, but simply with
display = "none"
display = "block"
Now here's the problem I can't solve:
By re-editing the fields and clicking again on submit-form
the fields edited the previous time appear again immediately
name: example-name
email: example-email
comment: example-comment
PDF: see your example-PDF file
and after about 2.5s they update with the new edited fields
name: new-name
email: new-email
comment: new-comment
PDF: see your new-PDF file
Now with the function
function submitTransition () {
setTimeout (function () {
document.getElementById ('message'). style.color = 'blue';}, 2500); }
and with style
#message { color: transparent; }
I'm trying to find a solution to delay (hide) the display of the old fields until the new ones are updated.
It is certainly not the right way.
I hope I have been clear in the explanation, your help will be very much able.
Thanks in advance.
You want to show the texts and button of "New registration" after "submit" button was clicked and the script of submitData was finished.
If my understanding is correct, how about this modification?
The reason of your issue is that google.script.run is run with the asynchronous process. By this, before the script of submitData is finished, document.getElementById('my-form').style.display='none', submitResponder('button-responder') and submitTransition('message') are run.
Modified script:
Please modify your script as follows.
From:
<br /><input id="btn" type="button" value="Submit"
onclick="submitForm(this.parentNode),
document.getElementById('my-form').style.display='none',
submitResponder('button-responder'),submitTransition('message');" />
To:
<br /><input id="btn" type="button" value="Submit" onclick="submitForm(this.parentNode)" />
And
From:
function submitForm(form) {
google.script.run
.withSuccessHandler(function(value){
document.getElementById('message').innerHTML = value;
document.getElementById('name').value = '';
document.getElementById('email').value = '';
document.getElementById('comment').value = '';
})
.submitData(form);
}
To:
function submitForm(form) {
google.script.run
.withSuccessHandler(function(value){
document.getElementById('message').innerHTML = value;
document.getElementById('name').value = '';
document.getElementById('email').value = '';
document.getElementById('comment').value = '';
document.getElementById('my-form').style.display='none'; // Added
submitResponder('button-responder'); // Added
submitTransition('message'); // Added
})
.submitData(form);
}
And, by above modification, you can also remove setTimeout as follows.
From:
function submitTransition() {
setTimeout(function() {
document.getElementById('message').style.color = 'blue';}, 2500);
}
To:
function submitTransition() {
document.getElementById('message').style.color = 'blue';
}
Reference
Class google.script.run (Client-side API)
google.script.run is an asynchronous client-side JavaScript API available in HTML-service pages that can call server-side Apps Script functions.
If I misunderstood your question and this was not the result you want, I apologize.

Uploaidng file to parse through html form

I am trying to let users fill out a form and upload a photo. I want all of this information to be stored in my parse database. I got the form to work fine, now I need to include the file upload. I am also creating this with express.js.
Here is my .ejs file with the form
<div id="result"></div>
<form action="/" id="filter-form" >
<P>
Upload your filter!
<input type="file" id="uploadfilter" required>
<img id="yourfilter" src="#" >
</P>
<p>
<input type="text" name="name" placeholder="Name" id="username" required>
</p>
<p>
<input type="email" name="email" placeholder="Email" id="email" required>
</p>
<p>
<textarea name="comments" id="comments" placeholder ="Additional comments" required></textarea>
</p>
<p>
<input type="checkbox" style="position: relative; left:0; visibility: visible;" required > I agree that this is my own work and does not contain logos or trademarks and I have read the Submission Guidelines
</p>
<p>
<input type="checkbox" style="position: relative; left:0; visibility: visible;" required > I agree to the Privacy Policy and Submission Agreement of the Smart Filters submission tool.
</p>
<p>
<input type="submit" value="Submit Filter">
</p>
</form>
Here's the javascript also in the .ejs file.
<script type="text/javascript">
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#yourfilter').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#uploadfilter").change(function(){
readURL(this);
});
jQuery(function($){
$('#filter-form').submit(function(event) {
event.preventDefault();
// Get some values from elements on the page:
var $form = $(this);
var name = $form.find("#username").val();
var email = $form.find("#email").val();
var comments = $form.find("#comments").val();
var url = $form.attr("action");
var data = {
"name": name,
"email": email,
"comments": comments,
"filterfile": parseFile,
};
var posting = $.post(url, data);
posting.done(function (data) {
//var data = JSON.parse(data);
var content = "<b>"+data.message+"</b>";
$("#result").empty().append(content);
});
posting.fail(function (data) {
//var data = JSON.parse(data);
var content = data.message;
$("#result").empty().append(content);
});
});
});
Here is the app.js code within the app.post.
app.post('/*', function (req, res) {
console.log('I AM HERE!');
console.log("PARAMS:")
console.log(req.params);
console.log("BODY:");
console.log(req.body);
var data = req.body;
if ((tryParseJSON(data) != false) || (!data.hasOwnProperty('name')) || (!data.hasOwnProperty('email')) || (!data.hasOwnProperty('comments'))) {
return res.json({"message" : "Invalid parameters!", "status" : 200});
}
var newFilter = Parse.Object.extend("FilterSubmit");
var newfilter = new newFilter();
newfilter.set("name", data.name);
newfilter.set("email", data.email);
newfilter.set("comments", data.comments);
newfilter.set("filterfile", data.parseFile);
var FilterSave = newfilter.save();
return Parse.Promise.when([FilterSave]).then(function (FilterSubmit) {
console.log("Filter Saved!");
return res.json({"status" : 400, "message" : "Filter Saved! Thank you "+data.name+"!"});
}, function (error) {
console.log("Save error!");
console.log(error);
return res.json({"message" : "Save error!", "status" : 200});
});
});
function tryParseJSON (jsonString){
try {
var o = JSON.parse(jsonString);
// Handle non-exception-throwing cases:
// Neither JSON.parse(false) or JSON.parse(1234) throw errors, hence the type-checking,
// but... JSON.parse(null) returns 'null', and typeof null === "object",
// so we must check for that, too.
if (o && typeof o === "object" && o !== null) {
return o;
}
}
catch (e) { }
return false; };
This form works perfectly when it's just the text input. It stopped submitting when I included the file input (Probably because I havn't implemented it fully yet). I now just need to get file uploading working with it as well. I'm not sure how to connect them or where to start. Any help would be much appreciated :)
Your form can not send files or images in the way you do:
Your form requires the attribute 'enctype' to be set.
<form action="/" id="filter-form" method="post" enctype="multipart/form-data">.

Functions in document.ready is not working

I think the Jquery syntax IM using isn't correct, but not sure what is wrong. Maybe someone can give me a hand. So I have a HTML Login page, where it asks for user and pw. I want to save these 2 variables as session cookie.
Here is the HTML of the login:
<FORM NAME="cf">
<span class="auto-style1">Username:</span>
<input type="hidden" id="messageType" name="messageType" value="3">
<INPUT TYPE="text" id="userName" NAME="userName" size="20" style="width: 180px">
<br><span class="auto-style1">Password:</span> <INPUT TYPE="password" id="password" NAME="password" size="20" style="width: 180px">
<span lang="en-ca"> </span>
</FORM>
<INPUT TYPE="submit" id="btnSubmit" name="btnSubmit" Value="Sign In" style="width: 109px" class="auto-style2">
Here is the Javascript I have written:
$(document).ready(function () {
$("#btnSubmit").click(function () {
//collect userName and password
var messageType = $("#messageType").val();
var userName = $("#userName").val();
var password = $("#password").val();
var YouEntered;
var YouEntered2;
var cookie_name1 = "username";
var cookie_name = "password";
putCookie();
putCookie2();
auth(messageType, userName, password);
});
});
//Set Cookies username and password
function putCookie() {
if(document.cookie != document.cookie)
{index = document.cookie.indexOf(cookie_name1);}
else
{ index = -1;}
if (index == -1)
{
YouEntered=document.cf.userName.value;
document.cookie=cookie_name1+"="+YouEntered+"; expires=0"; //Expires when Session Ends
}
}
function putCookie2() {
if(document.cookie != document.cookie)
{index = document.cookie.indexOf(cookie_name);}
else
{ index = -1;}
if (index == -1)
{
YouEntered2=document.cf.password.value;
document.cookie=cookie_name+"="+YouEntered2+"; expires=0"; //Expires when Session Ends
}
}
If I use onclick in the HTML to run the putCookie functions, I can save the cookies, but it won't send to the server.
Any help or reason why it doesn't work is appreciated.
First change your function as
function putCookie(cookie_name1) {
if(document.cookie != your_cookie){
index = document.cookie.indexOf(cookie_name1);
}
else {
var YouEntered=document.cf.userName.value;
document.cookie=cookie_name1+"="+YouEntered+"; expires=0"; //Expires when Session Ends
}
}
and should call the function like
putCookie(cookie_name1);

Form Validation in a pop up window

Hi I am displaying a pp up window based on the value stored in a localStorage.In the pop up window there is a form containing email and password.The user has to enter his email and password.Now what I need is that, the email entered by user has to be sent to a url and the url returns a status(either 1 or 0).If the url returns 1 then the user can just continue with the log in process.Otherwise an error message should be shown.The url is in the format http://www.calpinemate.com/employees/attendanceStatus/email/3".Here in the place of email highlighten should come the email entered by user in the form.In this way I have to pass the email.In this way I am doing form validation.But I don't know how to do.
Here is my userinfo.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<b>Enter your Email ID and Password</b><br><br>
<form id="userinfo">
<label for="user"> Email : </label>
<input type="text" id="user" />
<br><br>
<label for="pass">Password : </label>
<input type="password" id="pass" />
<br>
<br>
<input type="button" id="login" value="Log In" />
</form>
</body>
</html>
This is the form in the pop up window
Here is my test.js
window.addEventListener('DOMContentLoaded', function() {
var user = document.querySelector('input#user');
var pwd = document.querySelector('input#pass');
var login = document.querySelector('input#login');
login.addEventListener('click', function() {
var userStr = user.value;
login();
window.close();
chrome.runtime.getBackgroundPage(function(bgPage) {
bgPage.updateIcon();
});
});
function login(){
var urlPrefix = 'http://www.calpinemate.com/employees/attendanceStatus/';
var urlSuffix = '/3';
var req = new XMLHttpRequest();
req.addEventListener("readystatechange", function() {
if (req.readyState == 4) {
if (req.status == 200) {
var item=req.responseText;
if(item==1){
localStorage.username=userStr;
localStorage.password=pwd;
}
else{ alert('error');}
}
}
});
var url = urlPrefix + encodeURIComponent(userStr) + urlSuffix;
req.open("GET", url);
req.send(null);
}
});
This is my javascript.When the user presses the log in button,whatever the user enters in the email textbox gets stored in localStorage.username.Now what I need is that I have to check whether such an email id exists by passing the email to the above specified url.And if it exists only it should be stored in localStorage.username.Please anyone help me. I have tried using the above code.But noting happens.Please help me
Here is a resource you can edit and use Download Source Code or see live demo here http://purpledesign.in/blog/pop-out-a-form-using-jquery-and-javascript/
It is a contact form. You can change it to validation.
Add a Button or link to your page like this
<p>click to open</p>
“#inline” here should be the “id” of the that will contain the form.
<div id="inline">
<h2>Send us a Message</h2>
<form id="contact" name="contact" action="#" method="post">
<label for="email">Your E-mail</label>
<input type="email" id="email" name="email" class="txt">
<br>
<label for="msg">Enter a Message</label>
<textarea id="msg" name="msg" class="txtarea"></textarea>
<button id="send">Send E-mail</button>
</form>
</div>
Include these script to listen of the event of click. If you have an action defined in your form you can use “preventDefault()” method
<script type="text/javascript">
$(document).ready(function() {
$(".modalbox").fancybox();
$("#contact").submit(function() { return false; });
$("#send").on("click", function(){
var emailval = $("#email").val();
var msgval = $("#msg").val();
var msglen = msgval.length;
var mailvalid = validateEmail(emailval);
if(mailvalid == false) {
$("#email").addClass("error");
}
else if(mailvalid == true){
$("#email").removeClass("error");
}
if(msglen < 4) {
$("#msg").addClass("error");
}
else if(msglen >= 4){
$("#msg").removeClass("error");
}
if(mailvalid == true && msglen >= 4) {
// if both validate we attempt to send the e-mail
// first we hide the submit btn so the user doesnt click twice
$("#send").replaceWith("<em>sending...</em>");
//This will post it to the php page
$.ajax({
type: 'POST',
url: 'sendmessage.php',
data: $("#contact").serialize(),
success: function(data) {
if(data == "true") {
$("#contact").fadeOut("fast", function(){
//Display a message on successful posting for 1 sec
$(this).before("<p><strong>Success! Your feedback has been sent, thanks :)</strong></p>");
setTimeout("$.fancybox.close()", 1000);
});
}
}
});
}
});
});
</script>
You can add anything you want to do in your PHP file.

Categories

Resources