I'm making a dynamic website that need to show the user's name in the heading. The heading should say 'Hello, ', when the user enters their name into the text box and presses the button. And the name has to stay on the page even if I refresh the page.
What will be the javascript functions and html codes to implement this?
However, to implement this, the site need to read the query string when the page is loaded, not when the button is pressed. How can I write functions for the onload event for this?
I've tried this, but this doesn't work.
function setUserName() {
var userName = document.getElementById("userName").value;
localStorage.setItem("userName", userName);
}
function getUserName() {
var userName = localStorage.getItem("userName");
return userName;
}
function displayUserName() {
var userName = getUserName();
if (userName) {
document.write("Hello, " + userName);
} else {
document.write("Hello, world!");
}
}
<input type="text" id="userName">
<button onclick="setUserName()">Set Name</button>
<body onload="displayUserName()"></body>
Try this code, It might helpfull to you
function setUserName() {
var userName = document.getElementById("userName").value;
localStorage.setItem("userName", userName);
location.reload();
}
function getUserName() {
var userName = localStorage.getItem("userName");
return userName;
}
function displayUserName() {
var userName = getUserName();
if (userName) {
document.getElementById("helloText").textContent = "Hello, " + userName;
} else {
document.getElementById("helloText").textContent = "Hello, world";
}
}
<span id="helloText"></span>
<input type="text" id="userName" name="userName">
<button onclick="setUserName()">Set Name</button>
<body onload="displayUserName()">
</body>
Local storage wont work with the snippet by the way
Related
I am building a very simple chat application, nothing too fancy just a way for multiple users to chat at once.
The problem I am having is that whilst I can read and display messages from the database, no new messages will get inserted.
I am using JavaScript to pass a $.Get with the message and the username. I have checked the console and there is no errors showing but I have an undefined index: text and undefined index: username when I use POSTMAN to test.
Can anyone help push me in the right direction to solve this?
chat.php
<div class="wrapper">
<p id='chat-user'> </p>
<div id='chat-area'></div>
<form id='send-message-area'>
<textarea name="the-textarea" id="the-textarea" maxlength="150" placeholder="Start Typing..."autofocus></textarea>
</form>
<button id='chatSend' class="btn btn-info" type="submit">Post New Message</button>
<div id="the-count">
<span id="current">0</span>
<span id="maximum">/ 150</span>
</div>
</div>
var name = prompt("Enter your name:", "Guest");
if (!name || name === ' ') {
name = "Guest";
}
window.onload = function () {
document.getElementById("chat-user").innerHTML = "Your are: " + name;
};
$(document).ready(function () {
var chatInterval = 250;
var $chatOutput = $("#chat-area");
var $chatInput = $("#the-textarea");
var $chatSend = $("#chatSend");
function sendMessage() {
var chatInputString = $chatInput.val();
$.GET("testProcess.php", {
username: name,
text: chatInputString
});
retrieveMessages();
}
process.php
<?php
error_reporting(E_ALL);
include ("connection.php");
$username = substr($_GET["username"], 0, 32);
$text = substr($_GET["text"], 0, 150);
$nameEscaped = htmlentities(mysqli_real_escape_string($conn, $username));
$textEscaped = htmlentities(mysqli_real_escape_string($conn, $text));
$timestamp = date("Y-m-d H:i:s");
$insertMessage = "INSERT INTO message (messageID, messageBody, timeSent, nickname, sent) VALUES ('', '$textEscaped', '$timestamp', '$nameEscaped')";
$result = mysqli_query($conn, $insertMessage);
Your postman request is wrong as shown in the picture
you are passing the param GET with the value send but in your php script you have $_GET["username"] and $_GET["text"] the method GET is already set in the left side of the url in the picture so you dont need to send it what you want to send is the param username and text so the url would look like this
http://xxxxxxx/testProcess.php?username=Guest&text=test
as for your javascript code the jquery method for get is $.get and not $.GET and you are missing a way to handle the submit of the form because your submit button is outside of the form so a correct way to this would be
var name = prompt("Enter your name:", "Guest");
if (!name || name === ' ') {
name = "Guest";
}
window.onload = function() {
document.getElementById("chat-user").innerHTML = "Your are: " + name;
};
$(document).ready(function() {
var chatInterval = 250;
var $chatOutput = $("#chat-area");
var $chatInput = $("#the-textarea");
var $chatSend = $("#chatSend");
//intercepting the submit event to call the sendMessage function
$("#send-message-area").on("submit", function(e) {
e.preventDefault();
sendMessage()
})
function sendMessage() {
var chatInputString = $chatInput.val();
$.get("testProcess.php", {
username: name,
text: chatInputString
});
retrieveMessages();
}
})
I'm making a login page where if the email address already exists i want to stay on the same page and prompt the user that the email address already exists.
Here is the function which is the onClick function that will be called when the button is clicked
function login() {
var username = document.getElementById("username").value;
var pword = document.getElementById("pword").value;
var confpwd = document.getElementById("confpwd").value;
var email = document.getElementById("email").value;
var fname = document.getElementById("fname").value;
var lname = document.getElementById("lname").value;
var gender = document.getElementById("gender").value;
var t = 1;
if (t.toString() !== '0') {
var er = "Email-id already exists";
event.preventDefault();
document.getElementById("nemail").value = er;
document.getElementById("username").value = username;
document.getElementById("pword").value = "";
document.getElementById("confpwd").value = "";
document.getElementById("fname").value = fname;
document.getElementById("lname").value = lname;
document.getElementById("gender").value = gender;
}
}
You must pass a function to the <form onsubmit="return login()">. The login function must return true if you want to submit and false otherwise. See this answer for more details: JavaScript code to stop form submission
Working codepen to illustrate: http://codepen.io/DeividasK/pen/YZqwLO
Depending on how your code is setup to submit. You may just need to insert a return when the code realizes the email address is a duplicate. Something along this path might help prevent the page from moving forward.
if (ListOfExistingEmails.indexof(email) > 0 ) return false;
My website works like this:
1. User enters username and pass and press submit.
2. On submit, an ajax is sent to a page that checks the information and echos back 1, 2, or 3.
3. Based on ajax result, it sends the user to the application window.
WHAT I NEED: When the user is sent to the application window, I want the user id to be pasted in post to the new address.
<script>
$(document).on("click", "#submit", function(event)
{
var user = document.getElementById("name").value;
var pwd = document.getElementById("pwd").value;
$.post("userExistCheck.php",
{
userName: user,
userPass: pwd
},
function(result)
{
if (result == "0")
{
window.location.replace("Moment/momentApp.php");
}
else if (result == "1")
{
alert("Password is incorrect!");
}
else
{
alert("User does not exist!");
}
});
})
</script>
Hi just change this line
window.location.replace("Moment/momentApp.php?userid=" + userid);
Try something like this
I hope this is you want or else go with mamta answer :)
Html
<input type="hidden" id="userid" name="userid" value="1" />
Jquery
var userid = document.getElementById("userid").value;
$.post("userExistCheck.php",
{
userName: user,
userPass: pwd,
userid : userid //here u can pass the userid
},
<input type="hidden" name="userid" id="userid" />
<script>
$(document).on("click", "#submit", function(event)
{
var userid = document.getElementById("userid").value;
}
</script>
So, basically with this you can send the user id also. I have not written the whole code but the necessary part which should be appended
So, I have a question about Javascript and HTML. Below I have my code, and I'm not sure why but whenever I try and run it(ie: hit Submit), my website freezes. I have it set right now so that it checks if the username/password EXISTS, but it does not have to be a combination of the 2 quite yet. Can someone help me?
<!DOCTYPE html>
<html>
<title> Welcome to my website!</title>
<body>
<form action="action_page.php" method = "post">
Username: <input type="text" name="user">
Password: <input type="password" name="pass">
<input type="submit" value="Submit" onclick="myLogin()">
</form>
<script type="text/javascript">
function myLogin(){
var usernames = ["rdoucett", "hovland"];
var passwords = ["Rd200161", "hovland1"];
usernames[5] = "stop";
passwords[5] = "stop";
var a = false;
var b = false;
var i = 1;
while(a===false) {
if(usernames[i] != form.user.value) {
i++;
}else if(usernames[i] == form.user.value){
a=true;
}else if(usernames[i] == "stop"){
alert("Incorrect username or password!");
a=true;
};
};
i = 1;
while(b===false) {
if(passwords[i] != form.pass.value) {
i++;
}else if(passwords[i] == form.pass.value){
b=true;
}else if(passwords[i] == "stop"){
alert("Incorrect username or password!");
b=true;
};
};
if(b&&a===true){
alert("Welcome " + document.getElementsByName("user") + "!");
}else{
alert("I do not recognize you " + document.getElementsByName("pass") + "!");
};
};
</script>
</body>
Don't use a while loop at all, just exit the myLogin function if it was an invalid username or password.
Be aware that what you have written here is completely insecure. Anyone visiting your website with even a basic technical knowledge can see your full list of usernames and passwords.
I changed your code a lot, but I think it is what you wanted. In your scenario beside a few errors, any valid username and any valid password would match. (i.e. user = "rdoucett" and psw= "hovland1").
function myLogin(){
var usernames = ["rdoucett", "hovland"];
var passwords = ["Rd200161", "hovland1"];
var username;
for (var i = 0; i < usernames.length; i++) {
if (usernames[i] == form.user.value) {
username = usernames[i];
break;
}
}
if (!username || passwords[i] != form.pass.value) {
alert("Incorrect username or password!");
}
else {
alert("Welcome " + document.getElementsByName("user") + "!");
}
};
From the security point of view, as already been said this is very insecure. You should think the HTML and JS as information any client can see. So this kind of functionality is what you must do server side.
Also note that the alerts wont avoid the form of being submitted. If you want to avoid that, you should add return false;.
Hello guys im new on Google Script,
im making an app that read the input from the box,
and then send it to the mysql.
I have this:
-
Codigo.gs
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('getIp');
}
var connection = Jdbc.getConnection("jdbc:mysql://HOST:PORT/DB", "USER", "PW");
// perform the query
var SQLstatement = connection.createStatement();
var result = SQLstatement.executeQuery("Insert Into IPS Values(IPFromPrompt,0)");
Look at "IPFromPrompt" there is where i want IP from the following code
GetIp.html
<div>
<p>Click the button and enter your IP Addess.</p>
<button onclick="myFunction()">Try it</button>
<p id="AddIP"></p>
<script>
function myFunction() {
var IP = prompt("Please enter your IP Address", "");
if (person != null) {
document.getElementById("AddIP").innerHTML =
"Added " + IP + "to our database";
}
}
</script>
</div>
Do you know how can i do that?
I think you've got multiple problems here. You need a google.script.run call to trigger the .gs code from the HTML. Your myFunction() function needs to have google.script.run.
<script>
function myFunction() {
var IP = prompt("Please enter your IP Address", "");
var theUserInput = To Do . . .Get user input;
google.script.run
.withSuccessHandler(onSuccess)
.processInput(theUserInput)
}
function onSuccess(argIP) {
if (person != null) {
document.getElementById("AddIP").innerHTML =
"Added " + argIP + "to our database";
}
};
</script>
Codigo.gs
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('getIp');
}
function processInput(argGetInput) {
var connection = Jdbc.getConnection("jdbc:mysql://HOST:PORT/DB", "USER", "PW");
// perform the query
var SQLstatement = connection.createStatement();
var result = SQLstatement.executeQuery("Insert Into IPS Values(IPFromPrompt,0)");
return result;
};