Print value using GET or POST - javascript

My goal is to print the value entered in the Firstpage.html to basicform.html using GET or POST.
I need it to be done only using Html and JavaScript or Ajax.
Code for Firstpage.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
function result()
{
var x=document.forms["fom"]["name"].value;
$_GET[0]=x;
}
</script>
</head>
<body>
<form method="get" action="basicform.html" name="fom">
Your name: <input type="text" id="name" name="name" size="25" /> <br />
<input type="submit" value="submit" onclick="result()" />
</form>
</body>
</html>
This is the code in basicform.html
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<script>
function loaad()
{
var name = $_GET[x];
if(isset($_get(submit)))
{
document.write(name);
}
}
</script>
<body onload="loaad();">
</body>
</html>

You can only get the GET parameters using JavaScript. If JavaScript was able to access post variables, it would create security risks.
This is how you would get the GET parameters using JS.
var $_GET = {}, args = location.search.substr(1).split(/&/);
for (var i=0; i<args.length; ++i) {
var tmp = args[i].split(/=/);
if (tmp[0] != "") {
$_GET[decodeURIComponent(tmp[0])] = decodeURIComponent(tmp.slice(1).join("").replace("+", " "));
}
}

I Completed the Task Successfully using localStorage.
Code for Firstpage.html
<script>
function store()
{
if(localStorage)
{
document.getElementById("contactForm").addEventListener("submit",
function()
{
var name = document.getElementById("name").value;
localStorage.setItem('name',name);
var age = document.getElementById("age").value;
localStorage.setItem('age',age);
})
}
}
</script>
</head>
<body>
<form id="contactForm" action="result.html" method="POST" >
<label for="name">Name</label>
<input type="text" name="name" id="name">
<label for="Age">Age</label>
<input type="text" name="age" id="age">
<input type="submit" value="send" onclick="store()">
</form>
</body>
and the result.html is
<script>
window.onload= function()
{
var x =localStorage.getItem('name');
var y=localStorage.getItem('age');
if((x !="undefined") || (x!="NULL"))
{
document.getElementById("ret").innerHTML="hello "+x+" your are "+y+" years old";
}
}
</script>
</head>
<body>
<div id="ret" style="position:absolute; left:400px; top:200px; height:400px; width:400px; text-align:center">
Result
</div>
</body>

If you want to get GET parameter from Javascript use this function :
function getUrlParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}
Reference:
Get url parameter jquery Or How to Get Query String Values In js
Then simply use this:
var name = getUrlParameter('x');
//assuming url: http://yoursite.copm/?x=test
document.write(name);

Your form is sending the data using get (different than PHP's $_GET). This means that the values sent will appear in the address of the web page the form is sent to - no need for JS on this page. For example, on submitting your firstpage.html form you may get to:
basicform.html?name=Bob
This works well since JavaScript can get those parameters (not very cleanly, but it can). Put this on basicform.html:
function getQueryParams(qs) {
qs = qs.split("+").join(" ");
var params = {}, tokens,
re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(qs)) {
params[decodeURIComponent(tokens[1])]
= decodeURIComponent(tokens[2]);
}
return params;
}
var query = getQueryParams(document.location.search);
Then, you'll use the query variable to print out the name value.
document.write(query.name);
getQueryParams function from here on SO.
Also, the reason using $_GET didn't cause errors is that it's formed like any other valid JavaScript variable name. However, it's just that - the same as any JS variable - and has no relation to PHP's $_GET variable.

Related

How to use the onsumit function to call the output inside login function?

I am new to javascript. I am working on a login form with CryptoJS. I have three functions in total. They are onsubmit function, checkLogin function and encrytion function. I have to use the onsubmit function to call the checkLogin function to validate user input but I don't know how to do so. Besides, I have to use the encrytion function to turn user input to another string, then use the checkLogin function to call the encryption function and get the string. The checkLogin function and encryption function should not directly access DOM. Finally both functions will be used for Jasmine testing but I don't need to do it right now. I just want to make my form works normally. I don't know how to exactly modify my onsubmit function and checkLogin function to make it works.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>Login Page</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<script src="script.js"></script>
<script src="Jasmine/lib/md5.js"></script>
</head>
<body>
<header>
<h1>Login Page</h1>
</header>
<section id="form" class="form">
<form name="submitForm" action="#" method="POST">
<fieldset class="form__field">
<legend>User Authentication</legend>
<p><label for="in_username" class="form__username" >Username:</label>
<input type="text" name="username" id="in_username"/></p>
<p><label for="in_password" class="form__password">Password:</label>
<input type="password" name="password" id="in_password"/></p>
<input type="submit" value="Log in" class="form__submit" />
</fieldset>
</form>
</section>
<!-- output message -->
<section id="output" class="output">
</section>
</body>
</html>
Encryption function is confirmed to be ok.
function md5Encrypt(stringIn) {
"use strict";
var md5string = new CryptoJS.MD5(stringIn);
return md5string.toString();
}
What I want to do is to output the result in the same page and this is my current code.
How to use checkLogin function to call encryption function and return true when username is abc and password is 123123? After I output a variable, how do I use the onsubmit function to take the variable? Thank you!
window.onload = function () {
"use strict";
var myLogin = document.forms.submitForm;
var myMessage = document.getElementById("output");
myMessage.classList.add("displaynone");
myLogin.onsubmit = processForm;
function processForm() {
var inName = document.getElementById("in_username");
var inPassword = document.getElementById("in_password");
checkLogin(inName, inPassword);
myMessage.classList.add("displayblock");
myMessage.innerHTML = output;
return false;
}
function checkLogin(inName, inPassword){
var myName = "abc";
var myPassword = "123123";
var output = "";
var noName = "No username entered";
var noPassword = "No password entered"
var valid = "Welcome back!";
var invalid = "Invalid Username or Password";
if(inName.value(myName) && inPassword.value(myPassword)){
output = valid;
} else if (inName.value("")){
output = noName;
} else if(inPassword.value("")){
output = noPassword;
} else {
output = invalid;
}
return output;
}
};

How to get the value of a checkbox using getelementbyID inside a form

I have a code which worked fine while I was testing it now I decided it to include it inside a form and it just does not want to work. If I remove the form tag it works and with the form tag it does not.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
<script>
function action() {
var checkBox = document.getElementById("UPCheck");
if (checkBox.checked == true){
window.localStorage['username'] = document.getElementById('username').value;
window.localStorage['password'] = document.getElementById('password').value;
window.localStorage['unpwchecked'] = "yes";
alert("Saved!");
}
else
{
window.localStorage['username'] = "";
window.localStorage['password'] = "";
window.localStorage['unpwchecked'] = "";
}
}
function action2() {
document.getElementById('username').value = window.localStorage['username'];
document.getElementById('password').value = window.localStorage['password'];
}
</script>
</head>
<body>
<form>
<input type="text" id="username" name="username" value="">
<input type="text" id="password" name="password" value="">
Save username / password in cookies: <input type="checkbox" id="UPCheck" name="savelocalunpw">
<p><button onclick="action()" type="button">Save values!</button></p>
<p><button onclick="action2()" type="button">Load values!</button></p>
</form>
<script>
var alerted = localStorage.getItem('unpwchecked');
if (alerted == 'yes') {
document.getElementById('username').value = window.localStorage['username'];
document.getElementById('password').value = window.localStorage['password'];
document.getElementById("UPCheck").checked = true;
}
</script>
</body>
</html>
Remove the form tag and values are properly saved in localstorage.
The problem comes from the function name. If you rename
function action()
to
function action1()
and also modify
<button onclick="action1()" type="button">Save values!</button>
then your code will work.
I notices that without the form tag, the code works ok. If you add the form element, then you will get a console error, stating that action() is not a function. I'm just guessing that there is a conflict between the function name action() and the form attribute action
Try:
var isChecked = document.getElementById("UPCheck").checked;
Probably better practice to add an event handler for the buttons, that works with the form tags. Kind of interesting that it works with renaming the function.
JS
document.getElementById("save").addEventListener("click", function(){
var checkBox = document.getElementById("UPCheck");
if (checkBox.checked == true){
window.localStorage.username = document.getElementById('username').value;
window.localStorage.password = document.getElementById('password').value;
window.localStorage.unpwchecked = "yes";
alert("Saved!");
}
else
{
window.localStorage.username = "";
window.localStorage.password = "";
window.localStorage.unpwchecked = "";
}
});
document.getElementById("load").addEventListener("click", function(){
document.getElementById('username').value = window.localStorage.username;
document.getElementById('password').value = window.localStorage.password;
});
var alerted = localStorage.getItem('unpwchecked');
if (alerted == 'yes') {
document.getElementById('username').value = window.localStorage.username;
document.getElementById('password').value = window.localStorage.password;
document.getElementById("UPCheck").checked = true;
}
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>
<body>
<form>
<input type="text" id="username" name="username" value="">
<input type="text" id="password" name="password" value="">
Save username / password in cookies: <input type="checkbox" id="UPCheck" name="savelocalunpw">
<p><button id = "save" type="button">Save values!</button></p>
<p><button id = "load" type="button">Load values!</button></p>
</form>
</body>
</html>
You can use "dot" notation for localStorage.

Javascript can't get form to validate

I'm having problems getting my form to validate with Javascript. I've tried a bunch of different things, but I just can't get it to work. It's possible I'm missing something completely basic, I am pretty new at this. Please let me know what I could possibly change.
<!DOCTYPE html>
<html lang = "en">
<head>
<title> </title>
<meta charset = "utf-8" />
</head>
<body>
<script lang = "text/javascript">
document.getElementById("myForm").onsubmit = validateForm();
function zipcheck(sZip)
{
var postalRegex = /^d{5}(-\d{4})?$/;
return postalRegex.test(sZip);
}
function validateForm()
{
if (zipcheck(document.getElementById("zip"))
return true;
else
{
alert(document.getElementById("zip") + " is not a valid zip code");
return false;
}
}
</script>
<form id = "myForm" action = "" >
<p>
<label> Zip Code
<input type = "text" id = "zip" />
</label>
<input type = "submit" name = "submit" />
</p>
</form>
</body>
</html>
The Problem your are, checking the HTML Element not the Value. It should be document.getElementById("zip").value
document.getElementById("myForm").onsubmit = validateForm;
function zipcheck(sZip)
{
var postalRegex = /^d{5}(-\d{4})?$/;
return postalRegex.test(sZip);
}
function validateForm()
{
if (zipcheck(document.getElementById("zip").value)){
return true;
}else
{
alert(document.getElementById("zip").value + " is not a valid zip code");
return false;
}
}
<!DOCTYPE html>
<html lang = "en">
<head>
<title> </title>
<meta charset = "utf-8" />
</head>
<body>
<form id = "myForm" action="/test" method="get" >
<p>
<label> Zip Code
<input type = "text" id = "zip" />
</label>
<input type = "submit" name = "submit" />
</p>
</form>
</body>
</html>
here is a working sample on jsfiddler https://jsfiddle.net/u9suy516/
Optional Information: when using addEventListener you would also have to use the preventDefault() function on the passed event Parameter, but not need the return statments.
function validateForm(event)
{
if (!zipcheck(document.getElementById("zip").value)) {
alert(document.getElementById("zip").value + " is not a valid zip code");
event.preventDefault();
}
}

AJAX not working when pressing submit button

I am practicing the basics of AJAX.
When I click Submit nothing happens.
Here’s my code.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>FIRST AJAX!</title>
<script>
function alertMe(){
var field1 = document.getElementById("Field1").value;
var parser = "parse.php";
var values = "name="+filed1;
var xml = new XMLHttpRequest();
xml.open("POST", parser, true);
xml.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xml.onreadystatechange = function(){
if(xml.readyState == 4 && xml.status == 200){
document.getElementById('output').innerHTML = xml.responseText;
}
}
xml.send(values);
document.getElementById('output').innerHTML = " Loading ... ";
}
</script>
</head>
<body>
<input type="text" name="Field1" id="Field1"/>
<input type="submit" name="Fsend" onClick="alertMe();"/>
<p id="output"></p>
</body>
</html>
Thank you.
The problem is you are declaring a variable called field1, and then calling it as fiLEd1.
Try checking the console for errors, it's always useful
var values = "name="+filed1;
has a typo, should be...
var values = "name="+field1;
Also, input elements should be within a form and you probably want to use type="button" since you are not submitting the form. Finally, all standard attributes should be in lowercase, should be onclick, not onClick.
<!doctype html> <html> <head> <meta charset="utf-8"> <title>FIRST AJAX!</title> <script>
function alertMe(){
var field1 = document.getElementById("Field1").value;
var parser = "parse.php";
var values = "name="+field1;
var xml = new XMLHttpRequest();
xml.open("POST", parser, true);
xml.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xml.onreadystatechange = function(){
if ( xml.readyState == 4 && xml.status == 200){
document.getElementById('output').innerHTML = xml.responseText;
}
}
xml.send(values);
document.getElementById('output').innerHTML = " Loading ... ";
}
</script>
</head>
<body><form>
<input type="text" name="Field1" id="Field1"/>
<input type="button" value="Submit" name="Fsend" onclick="alertMe();"/>
</form> <p id="output"></p>
</body> </html>

JavaScript Replace Method for multiple textboxes

Can anyone please tell me how I can use the replace method to replace a character if it occures in more than one textbox without having to write separate function for each textbox.
The code below is the basic way to use the replace method but it only allows for one textbox.
I'm sure I need a loop in there but I'm not sure how to use that without affecting the replace method.
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script language="javascript">
function stringReplace(form) {
var replaceStr = form.textfield1.value
var pattern = /\'/g;
form.textfield1.value = replaceStr.replace(pattern, "''");
}
</script>
</head>
<body>
<form name="form1" method="post" action="JStest_redirect.asp">
<p>fname:
<input type="text" name="textfield1" size="20">
</p>
<p>lname:
<input type="text" name="textfield2" size="20">
</p>
<p>
<input onclick="return stringReplace(form)" type="submit" name="Submit" value="Submit">
</p>
</form>
</body>
</html>
You can do this:
function stringReplace(form) {
var $inputs = $(form).find('input:text');
var pattern = /\'/g;
$inputs.each(function () {
this.value = this.value.replace(pattern, "''");
});
return false; // Prevent the form from being submitted
}
This would find all the input type text within the form and replace their values.
If you wish to do it without jquery, you can use the getElementsByTagName() method.
function stringReplace(form) {
var pattern = /\'/g;
var inputs = form.getElementsByTagName("input");
var input;
for (var i = 0; i < inputs.length; i++) {
input = inputs[i];
if (input.type = 'text') {
var replaceStr = input.value;
input.value = replaceStr.replace(pattern, "''");
}
}
return false;
}
You seem to want
function stringReplace(form) {
$('input[type=text]').val(function(_, v) {
return v.replace(/\'/g, "''");
});
return false;
}
I added a return false at the end to prevent the form to be submitted on click. You probably want to have a separate button in your case.
I believe that fisrt you have to take all the values
function GetValue(){
var Contain = "";
$("#form1 :text").each(function(){
//add replace code here
});
}
You can add onchange function to all of you text input
function stringReplace(textField) {
var replaceStr = this.value
var pattern = /\'/g;
this.value = replaceStr.replace(pattern, "''");
}
and than you add
<input type="text" name="textfield1" size="20" onchange="stringReplace(this);">

Categories

Resources