I couldn't find any deep guide to ajax, especially for a php server side.
I currently try only to post the data to the PHP and test it before trying my luck with dumping to SQL.
Worked on it for 2 days, still not working. Guess it's a good time to head to stock overflow:
html+js:
<script>//send data scripts
var formNode = document.querySelector("#customerRegiForm");
var formData = new FormData(formNode);
var request = new XMLHttpRequest();
request.open("POST", "php/formSubmission.php", true);
request.onreadystatechange = function () {
if(request.readyState == 4 && request.status == 200){
document.getElementById("testing").innerHTML = request.responseTexts;
}
};
request.send(formData);
</script>
<form class="regiForm" id="customerRegiForm" onsubmit="return formValidation()">
<div>
Name: <input type="text" id="firstName" name="firstname" class="" required />
Family Name: <input type="text" id="lastName" name="lastname" class="" required />
</div>
<div>
Email: <input type="email" class="" id="email" name="email "required />
</div>
<div>
Phone Number: <input type="text" id="phone" name="phone" class="" required />
</div>
<div>
Country: <select name="country" class="countries" id="countryId" style="width: 100px">
<option value="">Select Country</option>
</select>
State: <select name="state" class="states" id="stateId">
<option value="">Select State</option>
</select>
City: <select name="city" class="cities" id="cityId">
<option value="">Select City</option>
</select>
</div>
<div>
Address: <input type="text" name="address" /><br />
</div>
<button type="submit">Submit</button>
</form>
<p id="testing"></p>
<?php
/**
* Created by PhpStorm.
* User: user
* Date: 17-Sep-16
* Time: 14:50
*/
echo $_POST['email'];
?>
also, any recommendations for videos and books in the subject?
I don't know if it's just a typo from your real code, but
request.responseTexts
should be
request.responseText
(the final "s" is not ok)
There are few things you need to change in your code, such as:
Look at the following <input> element,
<input type="email" class="" id="email" name="email "required />
^^^^^^^^^^^^^
Can you see that extra space after email? That's why on the PHP side, echo $_POST['email']; won't work. This <input> element should be like this:
<input type="email" class="" id="email" name="email" required />
Look at this JavaScript statement here,
document.getElementById("testing").innerHTML = request.responseTexts;
^^^^^^^^^^^^^^^^^^^^^
It should be,
document.getElementById("testing").innerHTML = request.responseText;
Look the the top <form> element,
<form class="regiForm" id="customerRegiForm" onsubmit="return formValidation()">
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
But I see no formValidation() function in your code. Create a function named formValidation() and make sure you return false from that function, otherwise the form will get submitted each time you hit the submit button. So, your script should be like this:
<script>
function formValidation(){
var formNode = document.querySelector("#customerRegiForm");
var formData = new FormData(formNode);
var request = new XMLHttpRequest();
request.open("POST", "post.php", true);
request.onreadystatechange = function () {
if(request.readyState == 4 && request.status == 200){
document.getElementById("testing").innerHTML = request.responseText;
}
};
request.send(formData);
return false;
}
</script>
Related
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'];
?>
I'm a dabbler when it comes to coding so I have a basic to intermediate understanding of various languages. I have a HTML form with a number of fields, one of which I'm trying to grab when a button is pressed but I'm getting Uncaught TypeError: Cannot read property 'value' of null
Here's my code in total:
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="testForm.css">
<title>Create Incident Form</title>
</head>
<body>
<header>Whittle ERP Ecosystem</header>
<p style="font-family:GE Inspira Sans;font-size:18px">This form is for
raising Incidents against the pillar applications in the Whittle ERP
Ecosystem</p>
<p style="font-family:GE Inspira Sans;font-size:18px;color:red;font-
weight:bold">ALL FIELDS ARE MANDATORY</p>
<form id="frm1" action="" method="post" name="incForm">
<fieldset>
<legend>User Detail</legend>
<label for="user-SSO">*SSO</label>
<input type="text" name="usrSSO" id="usrSSO" value="108013590" required>
<input type="Button" onclick="validateSSO()" value="Post">
<label for="user-tel"> *Contact Number:</label>
<input type="text" name="user-tel" id="user-tel" required>
</fieldset>
<fieldset>
<legend>System</legend>
<label for="*Choose System">Choose System:</label>
<select name="system" id="system" required>
<option value="R12">R12</option>
<option value="Proficy">Proficy</option>
<option value="TipQA">TipQA</option>
</select>
</fieldset>
<fieldset>
<legend>*Brief Description</legend>
<textarea rows="1" cols="60" name="bDesc" required></textarea>
</fieldset>
<fieldset>
<legend>*Detailed Description</legend>
<textarea rows="8" cols="60" name="dDesc" required></textarea>
</fieldset>
<fieldset>
<legend>Action</legend>
<input type="submit" name="Submit" value="Submit">
<input type="reset" value="Reset">
</fieldset>
</form>
<script>
function validateSSO(){
document.write("Starting function.....!<br />")
var fname = document.getElementById("usrSSO");
document.write(fname.value)
var strOutput
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
strOutput = xmlhttp.responseText
document.write("Function value: " + strOutput + "<br />")
}
};
xmlhttp.open("GET", "url", true)
xmlhttp.send();
if (strOutput == "A" ) {
window.alert("Condition met - SSO is valid")
}else{
document.write("Nope - invalid");
}
}
</script>
I've seen a few articles dealing with this but none seem to help me! I'm just trying to grab the contents of the usrSSO text field to use in a validation function. What have I missed/screwed up?
Thanks in advance
So as was said before using console.log will fix your first problem. I see a second problem and that is how you are handling the strOutput var. The way you have it written will cause you to handle an undefined variable since the request is asynchronous. You should only use it in the callback function for onreadystatechange like below to ensure you use it when the request is finished.
function validateSSO() {
console.log("Starting function.....!")
var fname = document.getElementById("usrSSO");
console.log(fname.value)
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200){
var strOutput = xmlhttp.responseText
console.log("Function value: " + strOutput);
if (strOutput == "A") {
alert("Condition met - SSO is valid")
}
else {
alert("Nope - invalid");
}
}
else {
alert('There was a problem with the request. status code: ' + this.status);
}
}
};
xmlhttp.open("GET", "url", true)
xmlhttp.send();
}
<header>Whittle ERP Ecosystem</header>
<p style="font-family:GE Inspira Sans;font-size:18px">This form is for raising Incidents against the pillar applications in the Whittle ERP Ecosystem
</p>
<p style="font-family:GE Inspira Sans;font-size:18px;color:red;font-
weight:bold">ALL FIELDS ARE MANDATORY</p>
<form id="frm1" action="" method="post" name="incForm">
<fieldset>
<legend>User Detail</legend>
<label for="user-SSO">*SSO</label>
<input type="text" name="usrSSO" id="usrSSO" value="108013590" required>
<input type="Button" onclick="validateSSO()" value="Post">
<label for="user-tel"> *Contact Number:</label>
<input type="text" name="user-tel" id="user-tel" required>
</fieldset>
<fieldset>
<legend>System</legend>
<label for="*Choose System">Choose System:</label>
<select name="system" id="system" required>
<option value="R12">R12</option>
<option value="Proficy">Proficy</option>
<option value="TipQA">TipQA</option>
</select>
</fieldset>
<fieldset>
<legend>*Brief Description</legend>
<textarea rows="1" cols="60" name="bDesc" required></textarea>
</fieldset>
<fieldset>
<legend>*Detailed Description</legend>
<textarea rows="8" cols="60" name="dDesc" required></textarea>
</fieldset>
<fieldset>
<legend>Action</legend>
<input type="submit" name="Submit" value="Submit">
<input type="reset" value="Reset">
</fieldset>
</form>
Ok, so what's happening is that your document.write function is replacing the entire document with that one line of text, if you change document.write to console.log your problem should go away.
I am having a problem with a script i am programming. I am very new to AJAX, and can't figure out what i am doing wrong that makes it not to work. Any help would be highly appreciated. I have multiple forms on the page and when i separate the forms the communication between the Ajax and php works just fine. But when i put everything together, it stops working. I do believe its either a communication problem or maybe some conflicting scripts or just some bad coding.
Here is the php code:
#session_start();
if(isset($_SESSION["username"])){
header("location: home.php");
exit();
}else{
$usertitle = $_POST['ut'];
$userfname = $_POST['uf'];
$userlname = $_POST['ul'];
$useremail = $_POST['ue'];
$userloc = $_POST['uloc'];
$user_est_typ = $_POST['utp'];
$userfname = preg_replace("/[^A-Za-z0-9?![:space:]]/","",$userfname);
$userlname = preg_replace("/[^A-Za-z0-9?![:space:]]/","",$userlname);
if($usertitle == "Title...."){
echo '<font color="red">Error: Please select a title.';
exit();
}else if($userfname == NULL){
exit('<font color="red">Error: You need a first name to proceed. </font>');
}else if( strlen($userfname) <= 2){
exit('<font color="red">Error: First name should be three (3) or more letters.</font>');
} else if($userlname == ""){
exit('<font color="red">Error: Giving a Surname would be nice.</font>');
}else if( strlen($userlname) <= 2){
exit('<font color="red">Error: Surname should be three (3) or more Letters.</font>');
}else if(!strpos($useremail, "#") || !strpos($useremail, "." || !filter_var($useremail, FILTER_VALIDATE_EMAIL) === true)){
exit('<font color="red">Email Address not valid</font>');
}else if($user_est_typ == "Select..."){
exit('<font color="red">Error: You must select an estimate type to proceed.</font>');
}else if($userloc == ""){
exit('<font color="red">Error: A location would be required so as to get the radiation data for the estimates</font>');
}else {
include("../../scripts/dbconect.php");
$queryuseremail = mysql_query("SELECT id FROM userdata WHERE userEmail='$useremail' LIMIT 1");
$useremail_check = mysql_num_rows($queryuseremail);
if ($useremail_check > 0){
echo "The email address ".$useremail." is already registered in ur database";
exit();
}
// More Validation and mysql insert
exit('<font color="red">signup_success</font>');
}
}
Here is my AJAX codes:
function _(x){
return document.getElementById(x);
}
function show(id){
var divelement = _(id);
if(divelement.style.display == 'none')
divelement.style.display = 'block';
else
divelement.style.display == 'none';
}
function hide(id){
var divelement = _(id);
if(divelement.style.display == 'block')
divelement.style.display = 'none';
else
divelement.style.display == 'block';
}
function emptyElement(id){
_(id).innerHTML = "";
}
function estimatetypeimg(){
var estType = _('estimatetype').value;
if (estType == 'solarpv'){
show('estimate_pv');
hide('estimate_thermal');
}
else if(estType == 'solarthermal'){
hide('estimate_pv');
show('estimate_thermal');
}
else{
hide('estimate_pv');
hide('estimate_thermal');
}
}
function newUsers() {
var title = _("salutation").value;
var fname = _("fname").value;
var lname = _("lname").value;
var email = _("email").value;
var loc = _("location").value;
var tp = _("estimatetype").value;
var url = "ajax.php";
var vars = "ut="+title+"uf="+fname+"&ul="+lname+"&ue="+email+"&uloc="+loc+"&utp="+tp;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
_("statuscheck").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", url, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(vars);
}
And here is my html code:
<div id="startbuts" style="display:none">
<form class="pure-form" name="startbutsform" id="startbutsform" onsubmit="return false;">
<button type="submit" id="newusersbtn" onclick="show('newusers'); hide('existingusers'); hide('existingusersbtn');"class="pure-button pure-button-primary">New Estimate</button>
<button type="submit" id="existingusersbtn" onclick="show('existingusers'); hide('newusers'); hide('newusersbtn');" class="button-secondary pure-button">Load Previous Estimate</button>
</form>
<div id="existingusers" style="display:none">
<form class="pure-form" name="signupex" id="signupex" onsubmit="return false;">
<fieldset>
<legend>Existing users: login with your email and Data ID.</legend>
<input type="email" id="dataemail" placeholder="Email" >
<input type="text" id="dataid" placeholder="DataId"><br/>
<button id="signupexbtn" type="submit" onclick="signinold()" class="pure-button pure-button-primary">Sign in</button>
</fieldset>
</form>
</div>
<div id="newusers" style="display:none">
<form class="pure-form" name="signupnew" id="signupnew" onsubmit="return false;">
<fieldset>
<legend>New users start here.</legend>
<div class="pure-control-group">
<label for="salutation">Title: </label>
<select id="salutation" name="salutation">
<option>Title....</option>
<option>Prof. Dr.</option>
<option>Prof.</option>
<option>Dr.</option>
<option>Mr.</option>
<option>Mrs.</option>
<option>Miss.</option>
</select>
</div>
<div class="pure-control-group">
<label for="fname">First name:</label>
<input id="fname" name="fname" type="text" placeholder="First Name">
</div>
<div class="pure-control-group">
<label for="lname">Last name:</label>
<input id="lname" name="lname" onfocus="emptyElement('errorcheck')" type="text" placeholder="Last Name">
</div>
<div class="pure-control-group">
<label for="email">Email Address:</label>
<input id="email" name="email" type="email" onfocus="emptyElement('errorcheck')" placeholder="Email Address">
</div>
<div class="pure-control-group">
<label for="location">Project Location: </label>
<input id="location" name="location" type="text" onfocus="emptyElement('errorcheck')" placeholder="Enter City ex Buea...">
</div>
<div class="pure-control-group">
<label for="estimatetype">Type of Estimate: </label>
<select id="estimatetype" name="estimatetype" onchange="estimatetypeimg()">
<option value="Select">Select...</option>
<option value="solarpv">Solar PV</option>
<option value="solarthermal">Solar Thermal</option>
</select>
</div>
<div id="estimate_pv" style="display:none" >
<img id="solarpvimg" src="images/solarpv.png" width="250" height="109" alt="Solar PV" />
</div>
<div id="estimate_thermal" style="display:none">
<img id="solarthermalimg" src="images/solarthermal.png" width="250" height="109" alt="Solar PV" />
</div>
<hr/>
<button id="signupnewbtn" type="button" class="pure-button pure-button-primary" onclick="newUsers()" >Start Calculator</button>
<button onclick="emptyElement('errorcheck'); hide('estimate_pv'); hide(estimate_thermal);" class="pure-button pure-button-primary" type="reset">Reset </button>
</fieldset>
</form>
</div>
</div>
Thank you David Lavieri and especially Sher Kahn. Your responses got me thinking and i finally figured out why I was not getting any response from my PhP script. As Khan also mention, I am just a hobby coder and you are absolutely right my code is not very clean. I cleaned the code on JSLint and realised i had too many bad coding habits. :). Thanks also for giving me a heads up with malsup query plugins. they are very handy and will help a lot.
So finally to the problem I had. The actual problem was the link to the php file. The url was poorly defined which made it impossible for the communication between the ajax and the php file. I use Dreamweaver and when i used the browse tool it gave me a link to the file, but because my javascript was external, the link was only relative to the Javascript file, and not the main html file. Also when i double checked my data vars, i missed and "&" for my second variable in the string before "uf"
var url = "ajax.php";// i changed the path file to scripts/ajax.php and it worked like magic.
var vars = "ut="+title+"uf="+fname+"&ul="+lname+"&ue="+email+"&uloc="+loc+"&utp="+tp;// before
var vars = "ut="+title+"&uf="+fname+"&ul="+lname+"&ue="+email+"&uloc="+loc+"&utp="+tp;// After
Hope this can be of help to someone else.
regards and thanks David and Khan.
Sorry if questions like this get really annoying; I've tried to figure this out without bothering anyone, but I'm a beginner and I'm totally stumped. Here's what I have so far. I want to pull data from the form called "paymentform" and generate a JSON list that I can post in a REST call. My boss wants me to do this specifically with JavaScript rather than jQuery. How would I do that?
function toggleVisibility(id) {
var e = document.getElementById(id);
if (id == "creditCard") {
document.getElementById("creditCard").checked = true;
document.getElementById("eCheck").checked = false;
if (document.getElementById("cardinfo").style.display == "none") {
document.getElementById("cardinfo").style.display = "block";
document.getElementById("bankinfo").style.display = "none";
document.getElementById("cardnumberid").setAttribute("required", true);
document.getElementById("expdateid").setAttribute("required", true);
document.getElementById("cvvnumberid").setAttribute("required", true);
document.getElementById("accountnameid").removeAttribute("required");
document.getElementById("routingnumberid").removeAttribute("required");
document.getElementById("banknameid").removeAttribute("required");
document.getElementById("accountnumberid").removeAttribute("required");
}
}
if (id == "eCheck") {
document.getElementById("creditCard").checked = false;
document.getElementById("eCheck").checked = true;
if (document.getElementById("bankinfo").style.display == "none") {
document.getElementById("cardinfo").style.display = "none";
document.getElementById("bankinfo").style.display = "block";
document.getElementById("cardnumberid").removeAttribute("required");
document.getElementById("expdateid").removeAttribute("required");
document.getElementById("cvvnumberid").removeAttribute("required");
document.getElementById("accountnameid").setAttribute("required", true);
document.getElementById("routingnumberid").setAttribute("required", true);
document.getElementById("banknameid").setAttribute("required", true);
document.getElementById("accountnumberid").setAttribute("required", true);
}
}
}
function setValue() {
document.getElementById("creditCard").checked = true;
document.getElementById("eCheck").checked = false;
document.getElementById("cardinfo").style.display = "block";
document.getElementById("bankinfo").style.display = "none";
document.getElementById("cardnumberid").setAttribute("required", true);
document.getElementById("expdateid").setAttribute("required", true);
document.getElementById("cvvnumberid").setAttribute("required", true);
document.getElementById("accountnameid").removeAttribute("required");
document.getElementById("routingnumberid").removeAttribute("required");
document.getElementById("banknameid").removeAttribute("required");
document.getElementById("accountnumberid").removeAttribute("required");
}
function submitForm() {
var myForm = document.getElementsByName("paymentform")[0];
}
body {
margin-top: 100px;
margin-left: 200px;
margin-right: 350px;
font-family: Helvetica;
font-size: 90%;
}
h1 {
font-family: Helvetica;
font-size: 150%;
}
h2 {
font-family: Helvetica;
font-size: 110%;
}
p {
font-family: Helvetica;
}
<!DOCTYPE html>
<html>
<head>
<title>Payment Information</title>
<link rel="stylesheet" type="text/css" href="CreditCardAndECheckTest.css">
<script src="CreditCardAndECheckTest.js"></script>
</head>
<body onload="setValue()">
<h1>Payment Profile</h1>
<hr>
<p>Enter the information for each field listed below.</p>
<h2>Billing Information</h2>
<form name="paymentform" onsubmit="return window.submitForm()" method="post">
First Name:
<input type="text" name="firstname" required> Last Name:
<input type="text" name="lastname" required>
<br>
<br>Company Name:
<input size="83px" type="text" name="companyname" required>
<br>
<br>Address 1:
<input size=T "30px" type="text" name="address1" required>
<br>
<br>Address 2:
<input size="30px" type="text" name="address2" required>
<br>
<br>City:
<input type="text" name="cityname" required> State/Province:
<input type="text" name="statename" required>
<br>
<br>Zip/Postal Code:
<input size="5px" type="text" name="zippostalcode" required> Country:
<input type="text" name="country" required>
<br>
<br>Email:
<input type="text" name="email" required> Phone:
<input type="text" name="phonenumber" required> Fax:
<input type="text" name="faxnumber">
<br>
<h2>Payment Information</h2>
Payment Type
<input id="creditCard" onclick="toggleVisibility('creditCard')" checked type="radio" />Credit Card
<input id="eCheck" onclick="toggleVisibility('eCheck')" type="radio" />Bank Account
<br>
<br>
<div id="cardinfo" style="display:block">
Accepted Methods: American Express, Discover, JCB, Mastercard, Visa
<br>
<br>Card Number:
<input id="cardnumberid" type="text" name="cardnumber" required>
<br>
<br>Expiration Date:
<input id="expdateid" type="text" name="expdate" required>(mmyy)
<br>
<br>CVV (3-digit number on the back of the card, if applicable):
<input id="cvvnumberid" type="text" name="cvvnumber" required>
</div>
<div id="bankinfo" style="display:none">
Name on Account:
<input id="accountnameid" size="30px" type="text" name="accountname" required> Account Type:
<select>
<option value="checking">Checking</option>
<option value="savings">Savings</option>
<option value="businesschecking">Business Checking</option>
</select>
<br>
<br>9-digit Routing Number:
<input id="routingnumberid" type="text" name="routingnumber" required> Account Number:
<input id="accountnumberid" type="text" name="accountnumber" required>
<br>
<br>Bank Name:
<input id="banknameid" size="30px" type="text" name="bankname" required>
</div>
<br>
<center>
<input type="submit" value="Submit">
</center>
</form>
</body>
</html>
tl;dr: I've provided a jsBin with a working example of your code
So, first off, jQuery exists to normalize odd browser behavior (mostly combatting IE problems) and to provide shorthand ways of doing common things. Writing out document.getElementById() a bunch of times is both tiring and unreadable. I added this simple function to make that particular bit easier:
function byId(element) {
return document.getElementById(element);
}
byId('firstname') // <input type="text" id="firstname" required>
I also changed all your name attributes to IDs. Calling getElementsByNames() is a bit wonky behavior so I personally would avoid it.
Finally, here is how to set the data to pass in a POST request (or whatever).
function submitForm() {
var cardId = byId("cardinfo");
var payment = {};
var data = {};
if (getCSS(cardId, 'display') == "block") {
payment = {
num: byId("cardnumberid").value,
exp: byId("expdateid").value,
cvv: byId("cvvnumberid").value
};
} else {
payment = {
accountName: byId("accountnameid").value,
routingNum: byId("routingnumberid").value,
bankName: byId("banknameid").value,
accountNum: byId("accountnumberid").value
};
}
data = {
first: byId('firstname').value,
last: byId('lastname').value,
company: byId('companyname').value,
addr1: byId('address1').value,
addr2: byId('address1').value,
city: byId('cityname').value,
state: byId('statename').value,
zip: byId('zippostalcode').value,
country: byId('country').value,
email: byId('email').value,
phone: byId('phonenumber').value,
fax: byId('faxnumber').value,
payment: payment
};
data = JSON.stringify(data);
console.log(data);
// Prevent the form from submitting and refreshing the page
return false;
}
You need to create the object you want to send one way or another and then you need to call JSON.stringify(objectName) on it. That will turn the object into a simple string. When you get data back from a request you'll often have to call JSON.parse(objectName) in order to manipulate the data.
Oh, extra credit:
Calling this doesnt work:
if (document.getElementById("bankinfo").style.display == "none") {...
document.getElementById().style only sets style. I created the following wee function to help:
function getCSS(element, attr) {
return window.getComputedStyle(element).getPropertyValue(attr);
}
Take a look at MDN's documentation on getPropertyValue() for more info
I have a form that i built using bootstrap, on enter it submits data via ajax, sometimes this works and other times the input box just goes empty and nothing happens.
<form class="form-inline" onsubmit="return Track_User()">
<div class="form-group">
<input type="text" class="form-control input-md" placeholder="Summoner Name" id="Summoner_Name">
<select class="form-control" id="Server_Name">
<option value="oce">OCE</option>
<option value="na">NA</option>
<option value="eue">EUE</option>
<option value="EUW">EUW</option>
</select>
</div>
<button type="submit" class="btn btn-default btn-md">Track</button>
<div id="Helpful_Output"></div>
</form>
Track_User function
function Track_User(){
// XML request for check summoner name
Summoner_Name = document.getElementById('Summoner_Name').value;
Server_Name = document.getElementById('Server_Name').value;
// Retrieves data about members in the group using ajax
var xmlhttp = new XMLHttpRequest();
var url = "check_summoner_name.php?Summoner_Name=" + Summoner_Name + "&Server_Name=" + Server_Name;
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
Update_Helpful_Output(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
// Run php script to confirm a few things
// 1. Do we already know this summoner name + server?
// 2. If we don't know the summoner, look it up, if false, return error message that summoner name is invalid
// 3. If summoner name is valid, check if we already know this summoner id + server_name combination
// 4. If we don't, create a new user
// 5. -- Finally we redirect to the graph page
}
If needed url of development page: http://crew-cut.com.au/bootstrap/loltimeplayed/index.php
Sorry for long url
Changes:
<form class="form-inline" onsubmit="Track_User()">
<div class="form-group">
<input type="text" class="form-control input-md" placeholder="Summoner Name" id="Summoner_Name">
<select class="form-control" id="Server_Name">
<option value="oce">OCE</option>
<option value="na">NA</option>
<option value="eue">EUE</option>
<option value="EUW">EUW</option>
</select>
</div>
<button type="submit" class="btn btn-default btn-md">Track</button>
<div id="Helpful_Output"></div>
</form>
function Track_User(e){
e.preventDefault();
// XML request for check summoner name
Summoner_Name = document.getElementById('Summoner_Name').value;
Server_Name = document.getElementById('Server_Name').value;
// Retrieves data about members in the group using ajax
var xmlhttp = new XMLHttpRequest();
var url = "check_summoner_name.php?Summoner_Name=" + Summoner_Name + "&Server_Name=" + Server_Name;
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
Update_Helpful_Output(xmlhttp.responseText);
}
else if (xmlhttp.readyState == 4 && xmlhttp.status == 404)
{
alert("Yeah I'm working, but I returned a 404.")
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
document.querySelector(".form-inline").querySelector(".btn").addEventListener("click", Track_User, false);
<form class="form-inline" >
<div class="form-group">
<input type="text" class="form-control input-md" placeholder="Summoner Name" id="Summoner_Name">
<select class="form-control" id="Server_Name">
<option value="oce">OCE</option>
<option value="na">NA</option>
<option value="eue">EUE</option>
<option value="EUW">EUW</option>
</select>
</div>
<button type="submit" class="btn btn-default btn-md">Track</button>
<div id="Helpful_Output"></div>
</form>
This will do it. No longer submitting via form, but using the track button to start the Ajax call. The problem lay in submitting the form. It just posted the form to nowhere without ever calling the ajax request. Now it does fire the ajax call.