Trying to Pass Multiple Variables from Multiple Windows through AJAX - javascript

I am trying to pass multiple variables from two different windows into the same PHP script. Is this possible? If not, what would be the best course of action?
Thanks
verifyemail.html
<script type = "text/javascript" src = "js/js_functions.js"> </script>
<form method="post" onsubmit = "return testAjax();" />
<input type="email" placeholder="email" name="email" required maxlength = "50"><br>
<input type="email" placeholder="re-enter email"name="reemail" required maxlength = "50"><br>
<input type="submit" value="Verify Email">
</form>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
signup.html:
<script type = "text/javascript" src="js/js_functions.js"></script>
<form method="post" onsubmit="return ajaxTest();"/>
<input type="text" placeholder="username" name="username" required = "required" maxlength = "15"><br>
<input type="password" placeholder="password" name="password" required = "required" pattern = "(?=.*\d)(?=.*[A-Z]).{10,}"><br>
<input type="password" placeholder="re-enter password"name="repassword" required = "required"><br>
<p class = "passwordreq">Password must:</p>
<input type="submit" value="sign up"> <input type="button" value="go back" onclick="window.location='index.html'">
</form>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
js_functions
var username, password;
function setUsrandPass(form)
{
if(form.password.value != form.repassword.value)
{
alert("Passwords do not match");
}
else {
username = form.username.value;
password = form.password.value;
window.location = 'verifyemail.html';
}
return false;
}
function ajaxTest()
{
if(form.email.value != form.reemail.value)
{
alert("Emails do not match");
}
else
$.ajax({
type: 'GET',
url: 'signup_script.php',
data: {usr: username, pass: password, em: form.email.value},
});
return false;
}
php script:
<?php
include 'profile_Functions.php';
$username = $_GET['usr'];
$password = $_GET['pass'];
$email = $_GET['em'];
echo "got here!";
createUser($username,$password,$email);
?>

This is not possible with things from separate pages. They need to be making the same request to the PHP script to provide both data.
You may be able to circumvent this by writing with PHP to some sort of datastore, i.e. a file or a database, then you wait for the other script to write as well, and then PHP can do any processing it needs.

Related

Generate password tokens

If I click the generate button I want the following passwords to appear "abcd" "1234" "!##$" in the three empty boxes but I missed my class about this lesson and when I tried to watch youtube videos about it I get confused so can anyone help me on How to put the passwords "abcd" "1234" "!##$" in the 3 empty boxes if I press the generate button? Thank you in advance
<html>
<head>
<h1><center>Hi! there, to enter to our website please generate your Three(3) password token and use it to Enter<center></h1>
</head>
<script>
var counter=3;
function validate()
{
while(counter>=1)
{
var token1="abcd";
var token2="1234";
var token3="!##$";
var checkToken=document.getElementById("getToken").value;
if(checkToken===token1 || checkToken===token2)
{
document.write("<center>password correct. Please click the link:");
document.write('<br> Check our site');
}
else
{
counter=counter-1;
alert("Incorrect password!\n\n Attempts left: "+counter);
if(counter==0)
{
document.write("please contact our security team.");
}
break;
}
}
}
</script>
<script>
function generate()
var pass1="abcd";
var pass2="1234";
var pass3="!##$";
</script>
<body>
<center>
<p>Generate password token</p>
<input type="text" placeholder="Create password" id="password1" readonly />
<input type="text" placeholder="Create password" id="password2" readonly />
<input type="text" placeholder="Create password" id="password3" readonly />
<br>
<input type="button" value="Generate Token" onclick="generate()">
<p>Enter password token below to continue:</p>
<input type="password" placeholder="Enter password" id="getToken">
<br>
<input type="button" value="Validate Token" onclick="validate()">
</center>
</body>
So I tried doing this but it did not work
function generate()
var pass1 = "abcd";
var pass2 = "1234";
var pass3 = "!##$";
getElementById(password).innerHtml = pass1;
getElementById(passwords).innerHtml = pass2;
getElementById(passwordss).innerHtml = pass3;
Oh my God I figured it out So the correct one is
<script>
function generate(){
var pass1 = "abcd";
var pass2 = "1234";
var pass3 = "!##$";
document.getElementById("password").value=pass1;
document.getElementById("passwords").value=pass2;
document.getElementById("passwordss").value=pass3;
}
</script>
I changed Innerhtml to value and I was missing {}
<html>
<head>
<h1><center>Hi! there, to enter to our website please generate your Three(3) password token and use it to Enter<center></h1>
</head>
<script>
var counter=3;
function validate()
{
while(counter>=1)
{
var token1="abcd";
var token2="1234";
var token3="!##$";
var checkToken=document.getElementById("getToken").value;
if(checkToken===token1 || checkToken===token2)
{
document.write("<center>password correct. Please click the link:");
document.write('<br> Check our site');
}
else
{
counter=counter-1;
alert("Incorrect password!\n\n Attempts left: "+counter);
if(counter==0)
{
document.write("please contact our security team.");
}
break;
}
}
}
</script>
<script>
function generate(){
var pass1 = "abcd";
var pass2 = "1234";
var pass3 = "!##$";
document.getElementById("password").value=pass1;
document.getElementById("passwords").value=pass2;
document.getElementById("passwordss").value=pass3;
}
</script>
<body>
<center>
<p>Generate password token</p>
<input type="text" placeholder="Create password" id="password" readonly />
<input type="text" placeholder="Create password" id="passwords" readonly />
<input type="text" placeholder="Create password" id="passwordss" readonly />
<br>
<input type="button" value="Generate Token" onclick="generate()">
<p>Enter password token below to continue:</p>
<input type="password" placeholder="Enter password" id="getToken">
<br>
<input type="button" value="Validate Token" onclick="validate()">
</center>
</body>

How to post data to server and capture response

I'm new to web development and stucked at sending data to server. I have registration form and i want to send this data to server. I can send data from form tag using action and method attribute but it will return response in next page. So i read somewhere i have to use ajax to send data. I tried but i cannot send and capture data using script.
This is my reponse
{"success":true}
Html code
<div class="form">
<div class="formdetail">
<h3>Individual Registration</h3>
<label for="fname"> Name</label><br>
<input type="text" size="40" id="name" name="name" placeholder="Enter your name.." required><br><br>
<label for="phonenumber">Mobile Number</label>
<br/>
<input id="mobileno" size="40" name="mobileno" type="tel" size="20" maxlength="13" placeholder="Enter your mobile number..." type="number" required><br><br>
<label for="email">Email-Id</label><br>
<input type="text" size="40" id="email" name="email" placeholder="Enter your email-id..." required><br><br>
<input type="date" id="dt" onchange="mydate1();" hidden/>
<input type="text" id="ndt" name="dob" onclick="mydate();" hidden />
<input type="button" Value="Date of Birth" onclick="mydate();" />
<script>
function mydate()
{
//alert("");
document.getElementById("dt").hidden=false;
document.getElementById("dob").hidden=true;
}
function mydate1()
{
d=new Date(document.getElementById("dt").value);
dt=d.getDate();
mn=d.getMonth();
mn++;
yy=d.getFullYear();
document.getElementById("dob").value=dt+"/"+mn+"/"+yy
document.getElementById("dob").hidden=false;
document.getElementById("dt").hidden=true;
}
</script>
<br><br>
<label for="address">Address</label><br>
<input type="text" id="address" size="40" name="address" placeholder="Enter your address..." required><br><br>
<label for="country">Country</label><br>
<input type="text" id="country" size="40" name="country" placeholder="Enter your country name....." required><br><br>
<label for="State">State</label><br>
<input type="text" id="state" size="40" name="state" placeholder="Enter your state name....." required><br><br>
<label for="city">City</label><br>
<input type="text" id="city" size="40" name="city" placeholder="Enter your city name....." required><br><br>
<input type="hidden" name="category" value="Individual">
<input type="submit" value="Submit" id="someInput" onclick="ajax_post()"><br>
<p class="small">Institute Registraion</p>
</div>
</div>
</form>
<script type="text/javascript">
function ajax_post(){
var hr = new XMLHttpRequest();
var url = "https://smilestechno.000webhostapp.com/Register.php";
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function(){
if (hr.readyState == 4 && hr.status == 200) {
var resp = console.log(response);
if (resp == "true") {
}
}
hr.send("name="+ name + "&mobileno=" + mobileno + "&email=" + email + "&dob=" + dob + "&address=" + address + "&city=" + city + "&state=" + state + "&country=" + country );
document.getElementById("status").innerhtml = "processing";
}
you can not send variable in this format.
var vars = name+mobileno+email+dob+address+city+state+country;
Params must have a format like:
hr.send("fname=Henry&lname=Ford");
Code you need:
hr.send("name=" + name + "&monbileno=" + mobileno + ... );
You can use jquery to use ajax in a simple way.
Reference:
xmlhttprequest https://www.w3schools.com/xml/ajax_xmlhttprequest_send.asp
jquery ajax https://www.w3schools.com/jquery/jquery_ref_ajax.asp
Use jquery, it makes it easier. This is how it should be using just the fname and email as an example with jquery ajax:
<form name="myForm" id="myForm" action="myActionUrl" method="POST">
<input type="text" name="fname" id="fname">
<input type="email" name="email" id="email">
<input type="submit" value="Submit">
</form>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script>
$("#myForm").on("submit", function(event){
event.preventDefault(); //this prevents the form to use default submit
$.ajax({
method: "POST",
url: $(this).attr("action"), //this will use the form's action attribute
data: {fname: $("#fname").val(), email: $("#email").val()},
success: function(responseData){
//do something here with responseData
}
});
});
</script>
Please replace the "myActionUrl" part with the url/file that processes your data.
The file can be some basic php file which stores the data into some database and returns or echoes something back so that you can use it within the "responseData" on the ajax success function.
Hope this helps!
Please call function like this
onclick="ajax_post()"
not
onclick="ajax_post"
You used getElementById but selected a name attribute
have to use
getElementById('fname').value;
not
getElementById('name').value;
hey i would recommend using jquery to accomplish this task.
this isthe client script
script type="text/javascript" src='jquery.js'></script>
<!-- download the lates version -->
<script type="text/javascript">
ajax_post(){
var url = "https://smilestechno.000webhostapp.com/Register.php";
var name = $("#name").val();
var mobileno = $("#mobileno").val();
var email = $("#email").val();
var dob = $("#dob").val();
var address = $("#address").val();
var city = $("#city").val();
var state = $("#state").val();
var country = $("#country").val();
var tmp = null;
$.ajax({
'async': false,
'type': "POST",
'global': false,
'dataType': 'json',
'url':url,
'data':{name:name,mobileno:mobileno,email:email,dob:dob,address:address,city:city,state:state,country},
'success': function (data) {
tmp = data;
}
});
return tmp; // you can access server response from this tmp variable
}
Server side
<?php
//get items as post inputs
print_r($_POST[]);
echo $_POST['name'];
?>

Adding a node to html page with javascript

This is my first time with javascript. I'm making a basic login page where there is a control for the email input. I would like to put an error message of some kind when someone gives an email address with illegal symbol. Here my code:
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
<meta charset="UTF-8">
</head>
<body>
<div>
<form action="Home.html" method="post">
<label for="id">Username</label>
<input type="text" name="id" id="id" value="" />
<br/>
<label for="pass">Password</label>
<input type="password" name="pass" id="pass" value="" />
<br/>
<label for="email">Email</label>
<input type="email" name="email" id="email" value="" />
<br/>
<script type="text/javascript">
function checkEmail ()
{
var emailObject = document.getElementById("email");
var email = emailObject.getAttribute("value").toString();
var error = document.createTextNode("Uncorrect email");
var result = email.search("/[^(a-z | A-Z | 0-9 | #)]/");
if(result !== -1)
{
emailObject.appendChild(error);
}
}
</script>
<button type="button" onclick="checkEmail()"> Confirm </button>
</form>
</div>
</body>
</html>
I have a function I use to validate email addresses, it uses regex. I would suggest jQuery just to show/hide the error message.
function validEmail(val){
if(val.length < 6 || val.length > 255) return false;
return new RegExp(/^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/).test(val);
}
$(function(){
$("#email").on("change", function(){
var email = $("#email").val();
if(!validEmail(email)){
$("#emailError").show();
} else {
$("#emailError").hide();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<!-- Some Inputs here -->
<span id='emailError' style='display: none;'>Please enter a valid email address</span><br>
<input type='email' id='email' name='email' placeholder='Email Address' />
<!-- More Inputs here -->
<button type='submit'>Submit</button>
</form>
you're trying to append something to an input element (email input, in this case). I'd suggest to append it to your main div, which in this case I have identified as "YOUR_ID".
Also, I suggest you a more efficint way to check a valid email.
follow the below example
<body>
<div id="YOUR_ID">
<form action="Home.html" method="post">
<label for="id">Username</label>
<input type="text" name="id" id="id" value="" />
<br/>
<label for="pass">Password</label>
<input type="password" name="pass" id="pass" value="" />
<br/>
<label for="email">Email</label>
<input type="email" name="email" id="email" value="" />
<br/>
<script type="text/javascript">
function checkEmail ()
{
var emailObject = document.getElementById("email");
var divObject = document.getElementById("YOUR_ID");
var email = emailObject.getAttribute("value").toString();
var error = document.createTextNode("Uncorrect email");
var check = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
var result = check.test(email);
if(result !== -1)
{
divObject.appendChild(error);
}
}
</script>
<button type="button" onclick="checkEmail()"> Confirm </button>
</form>
</div>
</body>

Why my text is printed on page and soon disappears in js

this is my code
i was trying to make a signup form and i made a script
i jst tried that the username should contain both alphabets and numbers and nothing else
if this condition is true than it continues
else it will give an error message displayed jst below it
<html>
<head>
</head>
<body>
<style>
#sign_up_details {
padding: 10px;
}
</style>
<form name="sign_up_details">
<h3>Enter your details below</h3>
<input type="textbox" id="username" placeholder="Enter your desired username" />
<p id="usrnm_check"></p><br>
<input type="password" id="password" placeholder="Enter your desired password" />
<p id="pass_check"></p><br>
<input type="textbox" id="email" placeholder="Enter your email id" />
<p id="email_check"></p><br>
<input type="submit" name="submit" value="Submit" onclick="store()" />
</form>
<script>
var usrnm = document.getElementById("username");
var pass = document.getElementById("password");
var email = document.getElementById("email");
var usrnm_check = document.getElementById("usrnm_check");
var pass_check = document.getElementById("pass_check");
var email_check = document.getElementById("email_check");
function store() {
var newReg = /^[A-Z]+[a-z]+[0-9]+$/
if (usrnm.value.match(newReg)) {
//next action here
} else {
usrnm_check.innerHTML = "Username should have alphabets and numbers";
}
}
</script>
</body>
</html>
for eg when i keep the username field empty and click on submit the error which is to be displayed comes below it but it soon disappears.
i dont know the reason for it.
you will have to set the store in onsubmit event and not on the submit button onclick event because,onclick will execute the function and submit the form as well.
here is fiddle
execute function before submit
<html>
<head>
</head>
<body>
<style>
#sign_up_details {
padding: 10px;
}
</style>
<form name="sign_up_details" onsubmit="return store()">
<h3>Enter your details below</h3>
<input type="textbox" id="username" placeholder="Enter your desired username" />
<p id="usrnm_check"></p><br>
<input type="password" id="password" placeholder="Enter your desired password" />
<p id="pass_check"></p><br>
<input type="textbox" id="email" placeholder="Enter your email id" />
<p id="email_check"></p><br>
<input type="submit" name="submit" value="Submit" />
</form>
<script>
var usrnm = document.getElementById("username");
var pass = document.getElementById("password");
var email = document.getElementById("email");
var usrnm_check = document.getElementById("usrnm_check");
var pass_check = document.getElementById("pass_check");
var email_check = document.getElementById("email_check");
function store() {
var newReg = /^[A-Z]+[a-z]+[0-9]+$/
if (usrnm.value.match(newReg)) {
//next action here
return true;
} else {
usrnm_check.innerHTML = "Username should have alphabets and numbers";
return false;
}
}
</script>
</body>
</html>
You can try something like this:
<form action="/dosomething.htm" method="GET" onsubmit="return store(this)">
[...]
<input type="submit" value="Go">
</form>
<script type="text/javascript">
function store() {
var newReg = /^[A-Z]+[a-z]+[0-9]+$/
if (usrnm.value.match(newReg)) {
//next action here
return true;
} else {
usrnm_check.innerHTML = "Username should have alphabets and numbers";
return false;
}
}
</script>
Notice return true and return false statements in store() and in form onSubmit. If the store() will return false the form will not get submitted. At present your message goes away after display because your form gets submitted even if the validation fails.
Hope this helps!!

using id="submit" twice on one page

I am creating a login/register part to a site. And the login and register forms are on page.
Like:
<form name="loginform" style="text-align:center;" method="post" onsubmit="return validateForm();" action="index.php">
<div class="row">
<input type="text" name="email" id="email" autocomplete="off" placeholder="Email Address" />
</div>
<br />
<div class="row">
<input type="password" name="password" id="password" autocomplete="off" placeholder="Password" />
</div>
<br />
<div class="row">
<button id="submit" type="submit" class="button large arrow-type-2 dark">Log Me In</button>
</div>
</form>
<form name="registerform" style="text-align:center;" method="post" onsubmit="return validatethisForm();" action="index.php">
<div class="row">
<input type="text" name="email" id="email2" autocomplete="off" placeholder="Email Address"/>
</div>
<br />
<div class="row">
<input type="password" name="password" id="password2" autocomplete="off" placeholder="Password"/>
</div>
<br />
<div class="row">
<button id="submit" type="submit" class="button large arrow-type-2 dark">Create Free Account</button>
</div>
</form>
My Js Validation is: ( needs work )
function validateForm()
{
var x=document.forms["loginform"]["email"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
var x=document.forms["loginform"]["password"].value;
if (x==null || x=="")
{
alert("Please enter a Password");
return false;
}
}
function validatethisForm()
{
var x=document.forms["registerform"]["email2"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
var x=document.forms["registerform"]["password2"].value;
if (x==null || x=="")
{
alert("Please enter a Password");
return false;
}
}
The issue I have is page validation, everything works perfect. But because I have duplicate submit id's , I need to clean this up.
Can you offer suggestions on improving my code above ?
/////////////////////////////////////////
Using: code below for cross browser placeholder
$('[placeholder]').focus(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
input.removeClass('placeholder');
}
}).blur(function() {
var input = $(this);
if (input.val() == '' || input.val() == input.attr('placeholder')) {
input.addClass('placeholder');
input.val(input.attr('placeholder'));
}
}).blur().parents('form').submit(function() {
$(this).find('[placeholder]').each(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
}
})
});
I simplified your HTML code to the following:
<form name="loginForm" method="post" onsubmit="return validateForm();" action="index.php">
<label>Email Address: <input type="email" name="email" autocomplete="off" placeholder="Email Address"/></label>
<label>Password: <input type="password" name="password" placeholder="Password"/></label>
<button type="submit" class="button large arrow-type-2 dark">Log In</button>
</form>
<form name="registerForm" method="post" onsubmit="return validatethisForm();"
action="index.php">
<label>Email Address: <input type="email" name="email" autocomplete="off" placeholder="Email Address"/></label>
<label>Password: <input type="password" name="password" placeholder="Password"/></label>
<button type="submit" class="button large arrow-type-2 dark">Create Free Account</button>
</form>
Points
Always include a label. Not all browsers support HTML5 placeholders.
All IDs here are reluctant. Forms can be accessed by
var loginForm = document.forms.loginForm; //By name
and form elements by
loginForm.email; //Also by name
No need for divs and brs to manage the line breaks. Use the labels themselves. Add display: block; as necessary.
Don't use inline style attribute. Use a CSS <style> element or an external stylesheet.
There's no AutoComplete on password fields.
Use HTML5's new form input types. type="email" will have the browser natively validate the field and notify the user if the email is not valid.
Keep it simple. No need for bloating.
Since both functions do the same thing, just make one function and bind it to both forms 'onsubmit' event.
You taggued is as jquery ,so, jquery-style, using Mike Alsup's jQuery Form Plugin.
function validate(formData, jqForm, options) {
// formData is an array of objects representing the name and value of each field
// that will be sent to the server; it takes the following form:
//
// [
// { name: username, value: valueOfUsernameInput },
// { name: password, value: valueOfPasswordInput }
// ]
//
// To validate, we can examine the contents of this array to see if the
// username and password fields have values. If either value evaluates
// to false then we return false from this method.
for (var i=0; i < formData.length; i++) {
if (!formData[i].value) {
alert('Please enter a value for both Username and Password');
return false;
}
}
alert('Both fields contain values.');
}
$('form').ajaxForm( { beforeSubmit: validate } );
This example and more info here.

Categories