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

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>

Related

How to stop user for using same username which already exist in my local storage?

var labelsarray = document.getElementsByTagName("label");
var inputsarray = document.getElementsByTagName("input");
var array = [];
function agecal() {
var Bdate = inputsarray[4].value;
var Bday = +new Date(Bdate).getFullYear();
var age = (new Date().getFullYear() - Bday);
inputsarray[5].value = age;
}
function subm() {
var users = {
FirstName: inputsarray[0].value,
LastName: inputsarray[1].value,
UserName: inputsarray[2].value,
Password: inputsarray[3].value,
DateofBirth: inputsarray[4].value,
Age: inputsarray[5].value,
Purpose: ""
};
if (inputsarray[6].checked === true) {
users.Gender = "Male";
} else if (inputsarray[7].checked === true) {
users.Gender = "Female";
}
if (inputsarray[8].checked === true) users.Purpose += " Storing Apps";
if (inputsarray[9].checked === true) users.Purpose += " Storing Sites";
if (inputsarray[10].checked === true) users.Purpose += " Fun";
array.push(users);
localStorage.setItem("Users Data: ", JSON.stringify(array));
var item = localStorage.getItem("Users Data: ");
var arrayobjfromls = JSON.parse(item);
for (var i = 0; i < arrayobjfromls.length; i++) {
if (inputsarray[2].value === arrayobjfromls[i].UserName) {
alert("This username is already in use. Please try another.");
localStorage.removeItem(arrayobjfromls[i]);
}
}
}
<div>
<center>
<form action="javascript:void(0);" method="post" onsubmit="subm();">
<label for="fname">First Name:</label> 
<input type="text" id="fname" />
<br/>
<label for="lname">Last Name:</label> 
<input type="text" id="lname" />
<br/>
<label for="uname">User Name:</label> 
<input type="text" id="uname" />
<br/>
<label for="pass">Password:</label>  
<input type="password" id="pass" />
<br/>
<label for="dob">Date of Birth:</label>  
<input type="date" id="dob" onchange="agecal();" />
<br/>
<label>Age:</label>     
<input type="text" id="age" disabled="disabled" />
<br/>
<span>Gender:</span>     
<input type="radio" name="gender" id="male" />
<label for="male">Male</label>
<input type="radio" name="gender" id="female" />
<label for="female">Female</label>
<br/>
<p>For what purpose(s) you are making account?</p>
<input type="checkbox" id="app" name="purpose" value="storingapps" />
<label for="app">Storing Apps</label>
<input type="checkbox" id="site" name="purpose" value="storingsites" />
<label for="site">Storing Sites</label>
<input type="checkbox" id="fun" name="purpose" value="fun" />
<label for="fun">Fun</label>
<br/>
<input type="submit" value="Submit" class="button" />
</form>
</center>
</div>
Please help me I want to stop user for using username which already present in my local storage by showing an alert and also I don't want to send data to local storage in which username is same of that data which is already present in my local storage...so that my local storage contain only those objects which have different usernames.
You're already checking for this; you're just doing it after you've already added the new user. Do the check first:
var item = localStorage.getItem("Users Data: ");
var arrayobjfromls = JSON.parse(item);
var found = false;
for (var i = 0; i < arrayobjfromls.length; i++) {
if(users.UserName === arrayobjfromls[i].UserName) {
found = true;
break;
}
}
if ( found ) {
alert("This username is already in use. Please try another.");
} else {
array.push( users );
localStorage.setItem("Users Data: ", JSON.stringify(array));
}

Using a checkbox to show entered values in a field to another field when a check box is clicked

Html - Delivery address has to give the entered value to billing address. The javascript and html are in separate files
Other js features are working fine, but its just this one that doesn't seem to work
<div class="textinput">
<label for="deladdress">Delivery Address: </label>
<input id="deladdress" type="text" name="Delivery Address" />
</div>
<div id="buttoncheckarea">
<input id="CheckDelivery" type="checkbox" name="CheckDelivery">
<label id="diff" for="CheckDelivery">Same as delivery address?</label>
</div>
<div class="textinput">
<label for="postcode">Postcode: </label>
<input id="postcode" type="text" name="postcode" />
</div>
<div class="textinput">
<label for="billaddress">Billing Address: </label>
<input id="billaddress" type="text" name="Billing Address" />
</div>
javascript
function deliveryfunc() {
var delivery = document.getElementById("deladdress").value;
var billing = document.getElementById("billaddress").value;
//var checkbox = document.getElementById("CheckDelivery").checked;
if (document.getElementsByName("CheckDelivery").checked == true) {
billing = delivery;
}
}
function init () {
var order = document.getElementById("ordForm");
order.onsubmit = ordervalidation;
order.onclick = radiobuttoncheck;
var checkbutton = document.getElementsByName("CheckDelivery");
checkbutton.onclick = deliveryfunc;
}
window.onload = init;
Try updating your deliveryfunc as below:
function deliveryfunc() {
var delivery = document.getElementById("deladdress");
var billing = document.getElementById("billaddress");
if (document.getElementById("CheckDelivery").checked == true) {
billing.value = delivery.value;
}
}
function init () {
var order = document.getElementById("ordForm");
order.onsubmit = ordervalidation;
order.onclick = radiobuttoncheck;
var checkbutton = document.getElementById("CheckDelivery");
checkbutton.onclick = deliveryfunc;
}
window.onload = init;

onfocus and onblur events on input

I'm trying to make a contact form, which should apply a class for css transitions when the input is onfocus/clicked by the user. If the user has typed name, the class from onfocus should stay there. If nothing is typed, an onblur event should remove the class and the effect.
I'm trying something like this, but I can't even make the onfocus event tricker an alert for testing my steps...
HTML:
<div>
<form class="footer-contact-form" action="">
<fieldset class="footer-form-field">
<input id="name" class="input-value" name="name" type="text" autocomplete="off" required>
<label for="name">Navn*</label>
</fieldset>
<fieldset class="footer-form-field">
<input id="company" class="input-value" name="company" type="text" autocomplete="off">
<label for="company">Firma</label>
</fieldset>
<fieldset class="footer-form-field">
<input id="email" class="input-value" name="email" type="email" autocomplete="off" required>
<label for="email">E-mail*</label>
</fieldset>
<fieldset class="footer-form-field-txt">
<textarea id="message" class="input-value" name="message" required></textarea>
<label for="message">Besked*</label>
</fieldset>
<input class="footer-msg-send" value="Send Besked" type="submit">
</form>
<button class="fetch-deal">Send</button>
</div>
CSS:
.input-expand {
transition: .7s;
width: 90px;
}
JS:
var inputValue = document.getElementsByClassName("input-value");
inputValue.onfocus = function() {
if (!inputValue.classList.hasClass("input-expand")) {
inputValue.addClass("input-expand");
}
// If no value is added and user does onblurr event, it should remove class .input-expand, otherwise leave class there.
}
var inputValue = document.getElementsByClassName("input-value");
var onFocus = function() { this.classList.add("input-expand");};
var onBlur = function() {if (!this.value) this.classList.remove("input-expand");};
for (var i = 0; i < inputValue.length; i++) {
inputValue[i].addEventListener('focus', onFocus, false);
inputValue[i].addEventListener('blur', onBlur, false);
}
.input-value {
transition: .7s;
width: 45px;
}
.input-expand {
transition: .7s;
width: 90px;
}
<div>
<form class="footer-contact-form" action="">
<fieldset class="footer-form-field">
<input id="name" class="input-value" name="name" type="text" autocomplete="off" required>
<label for="name">Navn*</label>
</fieldset>
<fieldset class="footer-form-field">
<input id="company" class="input-value" name="company" type="text" autocomplete="off">
<label for="company">Firma</label>
</fieldset>
<fieldset class="footer-form-field">
<input id="email" class="input-value" name="email" type="email" autocomplete="off" required>
<label for="email">E-mail*</label>
</fieldset>
<fieldset class="footer-form-field-txt">
<textarea id="message" class="input-value" name="message" required></textarea>
<label for="message">Besked*</label>
</fieldset>
<input class="footer-msg-send" value="Send Besked" type="submit">
</form>
<button class="fetch-deal">Send</button>
</div>
Without jQuery you could try:
var inputValue = document.getElementsByClassName("input-value");
[].forEach.call(inputValue,function(el){
el.onfocus=function() {
if (!el.classList.contains("input-expand")) {
el.className +="input-expand";
}
// If no value is added and user does onblurr event, it should remove class .input-expand, otherwise leave class there.
};
})
or as a fiddle:
https://jsfiddle.net/5v7n4je3/2/
mainly i think you problem lies in the ElementsByClassName array you have to iterate over the elements and use onFocus for every single one.
Notice the new Class is added once for every click at the moment.
I guess better solution for you to use css pseudo-classes. Use css style like below:
.input-value {
transition: .7s;
}
.input-value:focus {
width: 90px;
}
In this case you don't need to handle focus event through js and dynamically change classes of elements.
try this:
$(document).ready(function(){
$(".input-value").focus(function(){
//you focus code here
});
});
more reference: https://api.jquery.com/focus/
Using jQuery, try this :
https://api.jquery.com/focus/
$("input").focus(function() { $(this).addClass("input-expand"); });
$("input").blur(function() { $(this).val?null:$(this).removeClass("input-expand"); });
Here is the fix,
var inputValue = document.getElementsByClassName("input-value");
var onFocus = function() {
if (!this.classList.contains("input-expand")) {
this.classList.add("input-expand");
}
};
var onBlur = function() {
if (this.classList.contains("input-expand")) {
this.classList.remove("input-expand");
}
};
for (var i = 0; i < inputValue.length; i++) {
inputValue[i].addEventListener('focus', onFocus, false);
inputValue[i].addEventListener('blur', onBlur, false);
}
.input-expand {
transition: .7s;
width: 90px;
}
<div>
<form class="footer-contact-form" action="">
<fieldset class="footer-form-field">
<input id="name" class="input-value" name="name" type="text" autocomplete="off" required>
<label for="name">Navn*</label>
</fieldset>
<fieldset class="footer-form-field">
<input id="company" class="input-value" name="company" type="text" autocomplete="off">
<label for="company">Firma</label>
</fieldset>
<fieldset class="footer-form-field">
<input id="email" class="input-value" name="email" type="email" autocomplete="off" required>
<label for="email">E-mail*</label>
</fieldset>
<fieldset class="footer-form-field-txt">
<textarea id="message" class="input-value" name="message" required></textarea>
<label for="message">Besked*</label>
</fieldset>
<input class="footer-msg-send" value="Send Besked" type="submit">
</form>
<button class="fetch-deal">Send</button>
</div>
Try adding the script tag in the end of your body code.
Or else try and implement the solution provided below.
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
.my-focus-input{
border-color: red;
border-style: solid;
border-width: 1px;
height: 60px;
width: 300px;
}
.my-blur-input{
}
</style>
</head>
<body>
<input onfocus="myFocusFunction(this)" onblur="myBlurFunction(this)">
<script type="text/javascript">
function myFocusFunction(x) {
x.className = "my-focus-input";
}
function myBlurFunction(x) {
x.className = "my-blur-input";
}
</script>
</body>
</html>
Hi you just have to change yours css and js like this:
window.addEventListener("load",function(){
var inputValue = document.getElementsByClassName("input-value");
for(var i=0; i<inputValue.length; i++){
var f = inputValue[i];
f.className = "input-value input-expand";
f.addEventListener("focus", function(){this.style.maxWidth="90px";}, false);
f.addEventListener("blur", function(){if(this.value==""){this.style.maxWidth="30px";}}, false);
}
}, false);
.input-expand {
max-width:30px;
transition:max-width 0.7s ease 0s;
}
<div>
<form class="footer-contact-form" action="">
<fieldset class="footer-form-field">
<input id="name" class="input-value" name="name" type="text" autocomplete="off" required>
<label for="name">Navn*</label>
</fieldset>
<fieldset class="footer-form-field">
<input id="company" class="input-value" name="company" type="text" autocomplete="off">
<label for="company">Firma</label>
</fieldset>
<fieldset class="footer-form-field">
<input id="email" class="input-value" name="email" type="email" autocomplete="off" required>
<label for="email">E-mail*</label>
</fieldset>
<fieldset class="footer-form-field-txt">
<textarea id="message" class="input-value" name="message" required></textarea>
<label for="message">Besked*</label>
</fieldset>
<input class="footer-msg-send" value="Send Besked" type="submit">
</form>
<button class="fetch-deal">Send</button>
</div>
You can try something like this:
window.onload = function() {
var span1 = document.createElement("span");
span1.innerHTML = "test";
span1.className = "info";
span1.style.display = "none";
var span2 = document.createElement("span");
span2.innerHTML = "test";
span2.className = "info";
span2.style.display = "none";
var span3 = document.createElement("span");
span3.innerHTML = "test";
span3.className = "info";
span3.style.display = "none";
var username = document.getElementById("username");
username.parentNode.appendChild(span1);
var password = document.getElementById("password");
password.parentNode.appendChild(span2);
var email = document.getElementById("email");
email.parentNode.appendChild(span3);
username.onfocus = function() {
span1.className = "info";
span1.innerHTML = "infoMsg";
span1.style.display = "inline";
};
username.onblur = function() {
var alphanums = /^[a-z0-9A-Z]+$/;
if (username.value.match(alphanums)) {
span1.className = "ok";
span1.innerHTML = "Accepted";
} else {
span1.className = "error";
span1.innerHTML = "error";
}
if (username.value.length == 0) {
span1.className = "info";
span1.innerHTML = "infoMsg";
span1.style.display = "none";
}
};
password.onfocus = function() {
span2.innerHTML = "infoMsg";
span2.className = "info";
span2.style.display = "inline";
};
password.onblur = function() {
if (password.value.length < 6 && password.value.length > 0) {
span2.className = "error";
span2.innerHTML = "error";
}
if (password.value.length > 6) {
span2.className = "ok";
span2.innerHTML = "Accepted";
}
if (password.value.length == 0) {
span2.className = "info";
span2.innerHTML = "infoMsg";
span2.style.display = "none";
}
};
email.onfocus = function() {
span3.innerHTML = "infoMsg";
span3.className = "info";
span3.style.display = "inline";
};
email.onblur = function() {
var res = /^[^\s#]+#[^\s#]+\.[^\s#]+$/;
if (res.test(email.value)) {
span3.className = "ok";
span3.innerHTML = "Accepted";
} else {
span3.className = "error";
span3.innerHTML = "error";
}
if (email.value.length == 0) {
span3.className = "info";
span3.innerHTML = "infoMsg";
span3.style.display = "none";
}
};
};
All this is for this Html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Form Validation</title>
<link rel="stylesheet" href="validate.css" />
<script src="validate.js"></script>
</head>
<body>
<h1>Form Validation</h1>
<form class="signup">
<table>
<tr>
<td><label for="username">Username:</label></td>
<td><input type="text" name="username" id="username" /></td>
</tr>
<tr>
<td><label for="password">Password:</label></td>
<td><input type="password" name="password" id="password" /></td>
</tr>
<tr>
<td><label for="email">Email:</label></td>
<td><input type="text" name="email" id="email" /></td>
</tr>
</table>
</form>
</body>
</html>

Add a day with javascript

can you please help me to correct this :
function ajout()
{
var date_init = document.getElementById("actual").value;
var date_nmbr = document.getElementById("nombre").value;
var date_resu = addDaysToDate(date_init, date_nmbr);
document.getElementById("result").value = date_resu;
return(true);
}
<input type="text" name="actual" id="actual"><br>
<input type="text" name="result" id="result"><br>
<input type="text" name="nombre" id="nombre" onChange="javascript:ajout();">
Cordialy

Sending a JSON object to a server using AJAX

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>

Categories

Resources