Sending a JSON object to a server using AJAX - javascript

I'm working on an app that needs to serialize form data to JSON objects and send them to a server using AJAX asynchronously(as the server accepts only JSON objects). There are two forms to consider:
frontend.html
<div class="login">
<h>Login</h>
<form id="login_form_id" onsubmit="sign_in_client()">
<label>Email: </label><input id="email0" type="email" name="l_email" required>
<br>
<label>Password: </label><input id="password0" type="password" name="l_password" required>
<br><br>
<input type="submit" value="Submit">
</form>
</div>
<div class="signup">
<h>Signup</h>
<form id="signup_form_id" onsubmit="sign_up_client()">
<label>First Name: </label><input id="fname1" type="text" name="s_fname" required>
<br>
<label> Last Name: </label><input id="lname1" type="text" name="s_lname" required>
<br>
<label> City: </label><input id="city1" type="text" name="s_city" required>
<br>
<label> Country: </label><input id="country1" type="text" name="s_country" required>
<br>
<label> Male: </label><input id="gender1" type="radio" name="sex" value="male" required>
<br>
<label> Female: </label><input type="radio" name="sex" value="female" required>
<br>
<label> Email: </label><input id="email1" type="email" name="s_email" required>
<br>
<label> Password: </label><input id="password1" type="password" name="s_password" required>
<br>
<label> Repeat Pas: </label><input id="password2" type="password" name="s_rpassword" required>
<br>
<label> </label><input type="submit" value="Submit">
</form>
</div>
The code that handles form input parsing is bellow:
frontend.js
function sign_up_client()
{
var xmlhttp;
var fields = {};
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("frontEnd").innerHTML=xmlhttp.responseText;
}
}
// Open connection to server asynchronously to the sign_up route function
xmlhttp.open("POST", "sign_up", true);
// Set the content type to JSON objects
xmlhttp.setRequestHeader("Content-type","application/json");
// Send the form parameters needed for a sign-up operation
// Serialize them into a JSON object first
$("signup_form_id").find("input, textarea, select").each(function() {
var inputType = this.tagName.toUpperCase() === "INPUT" && this.type.toUpperCase();
if (inputType !== "BUTTON" && inputType !== "SUBMIT") {
}
xmlhttp.send(inputType);
});
}
The code for parsing the form data has been copied from this question. It's not very clear to me how the JSON object is being constructed. Are buttons and submit types included or not in the above example? Is the form whose inputs need to be parsed correctly picked(by id)?
At the end of the function is inputType a proper JSON object ready to be sent as is?
Edit #1:
frontend.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="client.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="client.js"></script>
<script type="text/javascript" src="serverstub.js"></script>
</head>
<body>
<div class="welcome">
<img src="wimage.png" alt="Twidder Icon;" >
<div class="login">
<h>Login</h>
<form id="signin_form_id" onsubmit="sign_in_client()">
<label>Email: </label><input type="email" name="l_email" required>
<br>
<label>Password: </label><input id="password0" type="password" name="l_password" required>
<br><br>
<input type="submit" value="Submit">
</form>
</div>
<div class="signup">
<h>Signup</h>
<form onsubmit="sign_up_client()">
<label>First Name: </label><input id="fname1" type="text" name="s_fname" required>
<br>
<label> Last Name: </label><input id="lname1" type="text" name="s_lname" required>
<br>
<label> City: </label><input id="city1" type="text" name="s_city" required>
<br>
<label> Country: </label><input id="country1" type="text" name="s_country" required>
<br>
<label> Male: </label><input id="gender1" type="radio" name="sex" value="male" required>
<br>
<label> Female: </label><input type="radio" name="sex" value="female" required>
<br>
<label> Email: </label><input id="email1" type="email" name="s_email" required>
<br>
<label> Password: </label><input id="password1" type="password" name="s_password" required>
<br>
<label> Repeat Pas: </label><input id="password2" type="password" name="s_rpassword" required>
<br>
<label> </label><input type="submit" value="Submit">
</form>
</div>
</div>
</body>
</html>
frontend.js
function sign_up_client()
{
var xmlhttp;
var jsonObject = {};
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
// Open connection to server asynchronously towards the sign_up route function
xmlhttp.open("POST", "sign_in", true);
// Set the content type to JSON objects
xmlhttp.setRequestHeader("Content-type","application/json");
// Send the form parameters needed for a sign-up operation
// Serialize them into a JSON object first
$("form").on("submit", function() {
var jsonObject = {};
$(".signup").find("input, textarea, select").map(function(index, elem) {
//Ingore types such as button, submit and radio
elem.type.match(/button|submit|radio/i) === null &&
(jsonObject[elem["name"]] = elem.value || "")
//If type = radio, grab the selected radio's value
elem.type.match(/radio/i) !== null &&
elem.checked && (jsonObject[elem["name"]] = elem.value || "")
});
alert (JSON.stringify(jsonObject, null, 4));
return false;
});
alert (JSON.stringify(jsonObject, null, 4));
// Send the JSON object
xmlhttp.send(jsonObject);
}
function sign_in_client()
{
var xmlhttp;
var jsonObject = {};
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
// Open connection to server asynchronously towards the sign_up route function
xmlhttp.open("POST", "sign_in", true);
// Set the content type to JSON objects
xmlhttp.setRequestHeader("Content-type","application/json");
// Send the form parameters needed for a sign-up operation
// Serialize them into a JSON object first
$("form").on("submit", function() {
var jsonObject = {};
$(".login").find("input, textarea, select").map(function(index, elem) {
//Ingore types such as button, submit and radio
elem.type.match(/button|submit|radio/i) === null &&
(jsonObject[elem["name"]] = elem.value || "")
//If type = radio, grab the selected radio's value
elem.type.match(/radio/i) !== null &&
elem.checked && (jsonObject[elem["name"]] = elem.value || "")
});
alert (JSON.stringify(jsonObject, null, 4));
return false;
});
alert (JSON.stringify(jsonObject, null, 4));
// Send the JSON object
xmlhttp.send(jsonObject);
}

Here is a quick way of constructing a JSON object from form fields for your specific case.
var o = {};
$(".signup").find("input, textarea, select").map(function(index, elem) {
//Ingore types such as button, submit and radio
elem.type.match(/button|submit|radio/i) === null &&
(o[elem["name"]] = elem.value || "")
//If type = radio, grab the selected radio's value
elem.type.match(/radio/i) !== null &&
elem.checked && (o[elem["name"]] = elem.value || "")
});
Now, you can send o as your JSON object.
Here is a demo for the same.

Try this example:
In below code, jQuery ajax syntax is used as it appear more simplified to me. To fetch the values from form fields, serialize method is used.
$('form').on('submit', sign_up_client);
function sign_up_client(e) {
e.preventDefault();
var formJson = [];
$(this).find(':input').each(function (index, elem) {
var inputType = this.tagName.toUpperCase() === "INPUT" &&
var formObj = {};
if (inputType === "RADIO") {
if ($(elem).is(":checked")) {
formObj[$(elem).attr('name')] = $(elem).val();
formJson.push(formObj);
}
}
else if (inputType !== "BUTTON" && inputType !== "SUBMIT")
formObj[$(elem).attr('name')] = $(elem).val();
formJson.push(formObj);
}
});
$.ajax({
type: "POST",
url: "test.php",
data: formJson,
dataType: "json",
success: function (data) {
},
error: function () {
alert('error handing here');
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="login">
<h>Login</h>
<form id="login_form_id" method="post">
<label>Email:</label>
<input id="email0" type="email" name="l_email" required>
<br>
<label>Password:</label>
<input id="password0" type="password" name="l_password" required>
<br>
<br>
<input type="submit" value="Submit">
</form>
</div>
<div class="signup">
<h>Signup</h>
<form id="signup_form_id" method="post">
<label>First Name:</label>
<input id="fname1" type="text" name="s_fname" required>
<br>
<label>Last Name:</label>
<input id="lname1" type="text" name="s_lname" required>
<br>
<label>City:</label>
<input id="city1" type="text" name="s_city" required>
<br>
<label>Country:</label>
<input id="country1" type="text" name="s_country" required>
<br>
<label>Male:</label>
<input id="gender1" type="radio" name="sex" value="male" required>
<br>
<label>Female:</label>
<input type="radio" name="sex" value="female" required>
<br>
<label>Email:</label>
<input id="email1" type="email" name="s_email" required>
<br>
<label>Password:</label>
<input id="password1" type="password" name="s_password" required>
<br>
<label>Repeat Pas:</label>
<input id="password2" type="password" name="s_rpassword" required>
<br>
<label></label>
<input type="submit" value="Submit">
</form>
</div>

Related

Contact Form Redirecting Prevent Default Not Working

I've tried this many different ways... don't know why this is redirecting still. I suppose in the past I've always used a button instead of a submit input and as such I never ran into this issue. However, I think it's time to get to the bottom of this!
HTML FORM
<form class="col-xs-12" action="mail.php" method="POST" >
<h2 class="headerFont">Contact</h2>
<p>Use the form below to send to contact me via email. I will be in touch soon after receiving your message.</p>
<div class="row">
<div class="col-xs-12 col-sm-6">
<input class="col-xs-12" placeholder="Full Name" title="Enter Full Name" type="text" name="name">
<input class="col-xs-6" placeholder="Email Address" title="Enter Email Address" type="email" name="email">
<input class="col-xs-6" placeholder="Mobile Phone Number" title="Enter Mobile Phone Number" type="tel" name="phone">
<input class="col-xs-12" placeholder="Street Address" title="Enter Street Address" type="text" name="address">
<input type="text" name="_gotcha" id="_gotcha" style="display: none !important">
<select class="col-xs-12" name="service">
<option selected disabled>Select Service</option>
<option>Group Walking</option>
<option>Private Walking</option>
<option>Pet Sitting</option>
</select>
</div>
<div class="col-xs-12 col-sm-6">
<textarea class="col-xs-12" placeholder="Message Here" rows="10" name="message"></textarea>
</div>
</div>
<input type="submit" value="Send" onclick="formSubmit(e)">
</form>
JAVASCRIPT CODE
function formSubmit(e) {
e.preventDefault();
return false;
console.log("Ajax Init");
var form = e.target,
data = new FormData(),
xhr = new XMLHttpRequest();
for (var i = 0, ii = form.length - 1; i < ii; ++i) {
var input = form[i];
data.append(input.name, input.value);
if (input.getAttribute("name") !== "_gotcha") {
if (input.value === "" || input.value === null || input.value === "undefined") {
alert("Please fill out all form fields before submitting");
break;
}
}
}
xhr.open(form.method.toUpperCase(), form.action, true);
if (document.getElementById("_gotcha").value.length == 0){
xhr.send(data);
} else {
break;
}
xhr.onloadend = function () {
// done
for (var i = 0, ii = form.length - 1; i < ii; ++i) {
var input = form[i];
input.value = "";
}
alert("Message Sent - Thank You");
};
};
It seems a better option is to use onsubmit attribute.
function formSubmit(form) {
console.log("Ajax Init");
var data = new FormData(form), // simpler
xhr = new XMLHttpRequest();
for (var i = 0, ii = form.length - 1; i < ii; ++i) {
var input = form[i];
//data.append(input.name, input.value);
if (input.getAttribute("name") !== "_gotcha") {
if (input.value === "" || input.value === null || input.value === "undefined") {
alert("Please fill out all form fields before submitting");
// something went wrong, prevent form from submitting
return false;
}
}
}
xhr.open(form.method.toUpperCase(), form.action, true);
if (document.getElementById("_gotcha").value.length == 0) {
xhr.send(data);
} else {
// something went wrong, prevent form from submitting
return false;
}
xhr.onloadend = function() {
// done
for (var i = 0, ii = form.length - 1; i < ii; ++i) {
var input = form[i];
input.value = "";
}
alert("Message Sent - Thank You");
};
// everything went ok, submit form
return true;
};
<!-- note the use of return -->
<form class="col-xs-12" action="mail.php" method="POST" onsubmit="return formSubmit(this)">
<h2 class="headerFont">Contact</h2>
<p>Use the form below to send to contact me via email. I will be in touch soon after receiving your message.</p>
<div class="row">
<div class="col-xs-12 col-sm-6">
<input class="col-xs-12" placeholder="Full Name" title="Enter Full Name" type="text" name="name">
<input class="col-xs-6" placeholder="Email Address" title="Enter Email Address" type="email" name="email">
<input class="col-xs-6" placeholder="Mobile Phone Number" title="Enter Mobile Phone Number" type="tel" name="phone">
<input class="col-xs-12" placeholder="Street Address" title="Enter Street Address" type="text" name="address">
<input type="text" name="_gotcha" id="_gotcha" style="display: none !important">
<select class="col-xs-12" name="service">
<option selected disabled>Select Service</option>
<option>Group Walking</option>
<option>Private Walking</option>
<option>Pet Sitting</option>
</select>
</div>
<div class="col-xs-12 col-sm-6">
<textarea class="col-xs-12" placeholder="Message Here" rows="10" name="message"></textarea>
</div>
</div>
<!-- upon clicking on the submit button, it will trigger the form's onsubmit handler -->
<input type="submit" value="Send">
</form>
i suggest to use jquery inside of core javascript becuase in javascript it to mush code want to write , i write for you in jquery
step 1: : give id to form tag id="myForm"
step 2: : write script like this
<script>
$('#myForm').submit(function(e){
e.preventDefualt();
data = $(this)..serialize();
});
</script>

My Jquery does not connect to my html

my jquery is not connecting and I cannot figure out why. I've been stumped on this for hours and I cannot figure it out.
this is my html code. The file name is exercise6.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Exercise 6</title>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="JS/exercise6.js"> </script>
</head>
<body>
<form id="email_form" name="email_form" action="exercise6.html" method="get">
<fieldset class="info">
<legend>Contact Information</legend>
<p>
<input type="text" name="Lname" id="name2" value="" required />
<label for="name2"> Last</label>
</p>
<p>
<input type="text" name="mailAddie" id="mail1" value="" required />
<label for="mail1"> Address</label>
</p>
<p>
<input type="text" name="City" id="city1" value="" />
<label for="city1"> City</label>
</p>
<p>
<input type="text" name="State" id="state1" value="" />
<label for="state1"> State</label>
</p>
<p>
<input type="number" name="Zip" id="zip1" value="" />
<label for="zip1"> Zip</label>
</p>
<p>
<input type="number" name="phoneNum" id="number" />
<label for="number"> Phone</label>
</p>
</fieldset>
<fieldset>
<legend>Sign up for our email list</legend>
<p>
<label for="email_address1"> Email Address</label>
<input type="text" name="email_address1" id="email_address1" value="" />
<span>*</span><br>
</p>
<p>
<label for="email_address2"> Confirm Email Address</label>
<input type="text" name="email_address2" id="email_address2" value="" />
<span>*</span><br>
</p>
<p>
<label for="first_name"> First</label>
<input type="text" name="first_name" id="first_name" value="" />
<span>*</span><br>
</p>
</fieldset>
<p>
<label> </label>
<input type="submit" value="Join Our List" id="join_list" >
</p>
</form>
</body>
</html>
and this is my javascript. The file name is exercise6.js and it is located in a file named JS. I do not know what I am doing wrong.
$(document).ready(function() {
$("#join_list").click(function() {
var emailAddress1 = $("#email_address1").val();
var emailAddress2 = $("#email_address2").val();
var isValid = true;
if (emailAddress1 == "") {
$("#email_address1").next().text("This field is required.");
isValid = false;
} else {
$("#email_address1").next().text("");
}
if (emailAddress2 == "") {
$("#email_address2").next().text("This field is required.");
isValid = false;
} else {
$("#email_address2").next().text("");
}
if ($("#first_name").val() == "") {
$("#first_name").next().text("This field is required.");
isValid = false
} else {
$("#first_name").next().text("");
}
if (isValid) {
$("#email_form").submit();
}
)};
)};
Can anyone help me?
The last two lines of exercise6.js both have a syntax error.
Change:
)};
)};
To:
});
});
To find this yourself next time, try using web development IDE like NetBeans with the help of right click with mouse to inspect in browser debug console, which would have even shown you where is this kind of error.
Your js code has some errors for close the function "});" try this
$(document).ready(function() {
$("#join_list").click(function() {
var emailAddress1 = $("#email_address1").val();
var emailAddress2 = $("#email_address2").val();
var isValid = true;
if (emailAddress1 == "") {
$("#email_address1").next().text("This field is required.");
isValid = false;
} else {
$("#email_address1").next().text("");
}
if (emailAddress2 == "") {
$("#email_address2").next().text("This field is required.");
isValid = false;
} else {
$("#email_address2").next().text("");
}
if ($("#first_name").val() == "") {
$("#first_name").next().text("This field is required.");
isValid = false
} else {
$("#first_name").next().text("");
}
if (isValid) {
$("#email_form").submit();
}
});
});

Why wont my radio button response respond to my Google Spreadsheet?

I've used the following code as a method to send user input data on my html site to a Google Spreadsheet:
Javascript:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
function postContactToGoogle() {
var firstname=$('#firstname').val();
var surname=$('#surname').val();
var dob=$('#dob').val();
var email=$('#email').val();
var option=$('#option').val();
$.ajax({
url:"https://docs.google.com/forms/d/e/1FAIpQLSfe760bJi_65cvSGfu4HckMdmAs1ahBkO7oE6njBTYZh4A/formResponse",
data: {"entry.1012452068":firstname, "entry.1038894874":surname, "entry.1352091133":dob, "entry.1048111489":email, "entry.1786559101":option}, type: "POST", datatype: "xml", statusCode: {0:function() {window.location.replace("thankyou.html");}, 200:function(){window.location.replace("thankyou.html");}}
});
}
</script>
HTML:
<form>
First Name:<br>
<input id="firstname" name="firstname" type="text" placeholder="First Name"/><br>
Surname:<br>
<input id="surname" name="surname" type="text" placeholder="Surname"/><br>
DoB:<br>
<input id="dob" name="dob" type="text" placeholder="DoB"/><br>
Email:<br>
<input id="email" name="email" type="text" placeholder="Email"/><br>
Option Pledge:<br>
<input id="option" name="option" type="radio"/> £49 <br>
<input id="option" name="option" type="radio"/> £69 <br>
<input id="ButtonSubmit" name="" type="button" value="Send" onclick="postContactToGoogle()"/>
</form>
It all works perfectly well except for the last 2 radio button options don't appear on the spreadsheet (shown on the image below). Does anyone have an insight into what I'm doing wrong?
You have 2 issues:
Your radio inputs have the same id="option" and id's should be unique .
Your radio inputs haven't value attribute to send like value="your value".
So this example should work
function postContactToGoogle() {
var firstname = $('#firstname').val();
var surname = $('#surname').val();
var dob = $('#dob').val();
var email = $('#email').val();
var option = $("[name='option']").val();
console.log({
"entry.1012452068": firstname,
"entry.1038894874": surname,
"entry.1352091133": dob,
"entry.1048111489": email,
"entry.1786559101": option
});
alert("your radio button value: " + option);
//it's working..
//then validate your data before sending
$.ajax({
url: "https://docs.google.com/forms/d/e/1FAIpQLSfe760bJi_65cvSGfu4HckMdmAs1ahBkO7oE6njBTYZh4A/formResponse",
data: {
"entry.1012452068": firstname,
"entry.1038894874": surname,
"entry.1352091133": dob,
"entry.1048111489": email,
"entry.1786559101": option
},
type: "POST",
datatype: "xml",
statusCode: {
0: function() {
alert("status:0, thank you");
window.location.replace("thankyou.html");
},
200: function() {
alert("status:200, thank you");
window.location.replace("thankyou.html");
}
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<form>
First Name:
<br>
<input id="firstname" name="firstname" type="text" placeholder="First Name" />
<br>Surname:
<br>
<input id="surname" name="surname" type="text" placeholder="Surname" />
<br>DoB:
<br>
<input id="dob" name="dob" type="text" placeholder="DoB" />
<br>Email:
<br>
<input id="email" name="email" type="text" placeholder="Email" />
<br>Option Pledge:
<br>
<input id="option1" value="Black Ballad Membership - £49" name="option" type="radio" />£49
<br>
<input id="option2" value="Premium Black Ballad Membership - £69" name="option" type="radio" />£69
<br>
<input id="ButtonSubmit" name="" type="button" value="Send" onclick="postContactToGoogle()" />
</form>
Do following change in your code,
var option = $('input[name=option]:checked').val()
Note: There should not be the same id for two different element, you have used id "option" for both radio.

javascript validation - Javascript not running

I'm trying to validate the inputs, so far I've created only two rules. One to test the phone number and another to test if the passwords entered at the same.
My problem is that for some reason my javascript isn't validating input. I have it referenced in <script>, I call it in the form onsubmit="return validate()". For some reason even with using an alert test to check that its run, that fails. So, I'm not really sure what's wrong, I could do with some extra eyes.
function validate() {
var errMsg = ""; /* stores the error message */
var result = true; /* assumes no errors */
var phonetest1 = true;
var phonetest2 = true;
/*get values from the form*/
var FirstName = document.getElementById("FirstName").value;
var Lastname = document.getElementById("Lastname").value;
var Email = document.getElementById("Email").value;
var Password = document.getElementById("Password").value;
var ConPassword = document.getElementById("ConPassword").value;
var Phone = document.getElementById("Phone").value;
var phonepatt1 = (/\(|0|\d|\)|\d|\d|\d|\d|\d|\d|\d|\d/);
var phonepatt2 = (/0|\d|\s|\d|\d|\d|\d|\d|\d|\d|\d/);
/* Rule one */
if (!phonepatt1.test(Phoneno)) {
phonetest1 = false;
}
if (!phonepatt2.test(Phoneno)) {
phonetest2 = false;
}
if (phonetest1 == false && phonetest2 == false) {
errMsg += "Your Phone number is incorrect .\n";
result = false;
}
alert("I'm running"); /* This isn't working */
/* Rule two */
if (ConPassword != Password) {
errMsg += "Please confirm your password .\n";
result = false;
}
if (errMsg != "") { //only display message box if there is something to show
alert(errMsg);
}
return result;
}
<H1>store Home Page</H1>
<p>Customer Registration: Register
<p>Customer Login: Login
<p>Manager Login Administrators
<form id="UserDetails" method="post" onsubmit="return validate()" action="index.htm">
<fieldset id="Details">
<legend>Your details:</legend>
<p>
<label for="FirstName">First Name</label>
<input type="text" name="FirstName" id="FirstName" pattern="[a-zA-Z]+" size="20" maxlength="20" required="required" />
</p>
<p>
<label for="Lastname">Last Name</label>
<input type="text" name="LastName" id="Lastname" pattern="[a-zA-Z]+" size="20" maxlength="20" required="required" />
</p>
<p>
<label for="Email">Email</label>
<input type="text" name="Email" id="Email" size="20" maxlength="20" required="required" />
</p>
<p>
<label for="Password">Password</label>
<input type="text" name="Password" id="Password" size="20" maxlength="20" required="required" />
</p>
<p>
<label for="ConPassword">Confirm Password</label>
<input type="text" name="ConPassword" id="ConPassword" size="20" maxlength="20" required="required" />
</p>
<p>
<label for="Phone">Phone Number</label>
<input type="text" name="Phone" id="Phone" maxlength="12" size="12" placeholder="(03)92251515" />
</p>
<input type="submit" value="Register Now!" />
<input type="reset" value="Reset" />
</fieldset>
</form>
You have wrog name in your JavaScript (should be Phone instead of Phoneno):
if (!phonepatt1.test(Phone)) {
phonetest1 = false;
}
if (!phonepatt2.test(Phone)) {
phonetest2 = false;
}

Getting Javascript to insert values into my textboxes (AJAX!)

So I have this code, which I am trying to use to make it update my form text boxes when I select a different drop down user.
Here's the code:
<script type="text/javascript">
document.getElementById("useruname").onchange = function() {
var selecteduname = this.value;
}
var xmlhttp;
function loadXMLDoc()
{
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
function updateAdduser()
{loadXMLDoc();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var json = xmlhttp.responseText;
var fields = JSON.parse(json);
Object.keys(fields).forEach(function (name) {
var input = document.getElementsByName(name);
input.value = fields[name];
});
}
}
xmlhttp.open("GET", "ajaxuseradd.psp?=", true);
xmlhttp.send();
}
</script>
<form action="adduser.psp" method="get">
<fieldset>
<label for="uname">Username:</label>
<select name="uname" id="useruname" onChange="updateAdduser();">
<%
import MySQLdb
db = MySQLdb.connect("localhost", "login", "password", "somethingelse")
c = db.cursor()
c.execute("""SELECT user from employees;""")
tup = c.fetchall()
tupstr = str(tup)
tupstr = tupstr.replace("(", "").replace("'", "").replace(")", "").replace(",,", ",").replace("'", "").replace("' ", "'").replace(", ", ",")
tupstr = tupstr.rstrip(",")
numlist = tupstr.split(",")
optionlist = ['<option value="%s">%s</option>' % (x, x) for x in numlist]
options = "\n".join(optionlist)
%>
<%= options %>
</select>
</fieldset>
<fieldset>
<label for="fname">First Name:</label>
<input type="text" name="fname" />
</fieldset>
<fieldset>
<label for="lname">Last Name:</label>
<input type="text" name="lname" />
</fieldset>
<fieldset>
<label for="email">Email:</label>
<input type="text" name="email">
</fieldset>
I would seriously consider moving to using a client javascript library like jQuery.
Your code would be simplified to something like this:
<script type="text/javascript">
$("#useruname").change = function() {
var selecteduname = this.value;
}
function updateAdduser()
{
var fields = null;
$.ajax(url: "ajaxuseradd.psp?=",
dataType = 'json',
success: function(data){
fields = data;
Object.keys(fields).forEach(function (name) {
var input = $(name);
input.value = fields[name];
});
}
});
}
</script>
<form action="adduser.psp" method="get">
<fieldset>
<label for="uname">Username:</label>
<select name="uname" id="useruname" onChange="updateAdduser();">
<%
import MySQLdb
db =
c = db.cursor()
c.execute("""SELECT user from employees;""")
tup = c.fetchall()
tupstr = str(tup)
tupstr = tupstr.replace("(", "").replace("'", "").replace(")", "").replace(",,", ",").replace("'", "").replace("' ", "'").replace(", ", ",")
tupstr = tupstr.rstrip(",")
numlist = tupstr.split(",")
optionlist = ['<option value="%s">%s</option>' % (x, x) for x in numlist]
options = "\n".join(optionlist)
%>
<%= options %>
</select>
</fieldset>
<fieldset>
<label for="fname">First Name:</label>
<input type="text" name="fname" />
</fieldset>
<fieldset>
<label for="lname">Last Name:</label>
<input type="text" name="lname" />
</fieldset>
<fieldset>
<label for="email">Email:</label>
<input type="text" name="email">
</fieldset>

Categories

Resources