I'm trying to generate a form, posting to an xml doc but the code keeps taking the else option "Please make sure you filled in the fields correctly." in the registration.php file when I've supplied the variables properly.
There's 3 sections: html, javascript and php. The output I'm getting is
<html>
<head>
<title>A Simple Example</title>
</head>
<body>
<script src="clientSideScripts.js"></script>
<h1>Registration Page </h1>
<table border="0">
<form>
<tr>
<td><strong>Firstname:</strong></td>
<td>
<input type="text" name="firstname" id="firstname" required />
</td>
</tr>
<tr>
<td><strong>Lastname:</strong></td>
<td>
<input type="text" name="lastname" id="lastname" required />
</td>
</tr>
<tr>
<td><strong>Password:</strong></td>
<td>
<input type="password" id="userPassword" name="password" required/>
</td>
</tr>
<tr>
<td><strong>Confirm Password:</strong></td>
<td>
<input type="password" id="confirmPassword" name="pwdfield" required/>
</td>
</tr>
<tr>
<td><strong>Email:</strong></td>
<td>
<input type="email" name="email" id="email" value="" required pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$" />
</td>
</tr>
<tr>
<td><strong>Contact Phone:</strong></td>
<td>
<input type="text" name="phone" id="phone" value=""/>
</td>
</tr>
<td>
<input type="button" value="Register" onclick="registerCustomer();"/>
</td>
</form>
<div id="information"/>
</body>
</html>
var xHRObject = false;
if (window.XMLHttpRequest)
xHRObject = new XMLHttpRequest();
else if (window.ActiveXObject)
xHRObject = new ActiveXObject("Microsoft.XMLHTTP");
function validatePassword()
{
var a = document.getElementById("userPassword");
var b=document.getElementById("confirmPassword");
return a.value == b.value;
}
function registerCustomer()
{
if(!validatePassword())
alert("The passwords don't match.");
else
{
var firstname = document.getElementById("firstname").value;
var lastname = document.getElementById("lastname").value;
var password = document.getElementById("userPassword").value;
var email = document.getElementById("email").value;
var phone = document.getElementById("phone").value;
var url = "registration.php?firstname=" + firstname + "&lastname" + lastname + "&password=" + password + "&email=" + email + "&phone=" + phone;
xHRObject.open("GET", url , true);
xHRObject.onreadystatechange = function()
{
if (xHRObject.readyState == 4 && xHRObject.status == 200)
document.getElementById('information').innerHTML = xHRObject.responseText + "<br><a href='buyonline.htm'>back</a>";
}
xHRObject.send(null);
}
}
function customerLogin()
{
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
var url = "login.php?email=" + email + "&password=" + password;
xHRObject.open("GET", url , true);
xHRObject.onreadystatechange = function()
{
if (xHRObject.readyState == 4 && xHRObject.status == 200)
document.getElementById('information').innerHTML = xHRObject.responseText + "<br><a href='buyonline.htm'>back</a>";
}
xHRObject.send(null);
}
<?php
if(isset($_GET["firstname"]) && isset($_GET["lastname"]) && isset($_GET["password"]) && isset($_GET["email"]))
{
if(isEmailUnique() )
insertCustomer();
else
echo "This email is already taken, please choose another one.";
}
else echo "Please make sure you filled in the fields correctly.";
function getLastId(){
$id = 0;
$xmlFile = "../../data/customer.xml";
try
{
$dom = DOMDocument::load($xmlFile);
$customers = $dom->getElementsByTagName("customer");
foreach($customers as $node)
{
$cID = $node->getElementsByTagName("id");
$cID = $cID->item(0)->nodeValue;
if (($id < $cID )) $id = $cID;
}
}
catch(Exception $e)
{
$doc = new DomDocument('1.0');
$customers = $doc->createElement('customers');
$customers = $doc->appendChild($customers);
$doc->saveXML();
return 1;
}
return $id;
}
function insertCustomer()
{
try {
$xmlFile = "../../data/customer.xml";
$doc = DOMDocument::load($xmlFile);
$doc->formatOutput = true;
$customer = $doc->createElement("customer");
$Customers = $doc->getElementsByTagName("Customers");
$customer = $Customers->item(0)->appendChild($customer);
$newID = getLastId() + 1;
$id = $doc->createElement('id');
$idValue = $doc->createTextNode($newID);
$id->appendChild($idValue);
$customer->appendChild($id);
$name1 = $doc->createElement('firstname');
$nameValue = $doc->createTextNode($_GET["firstname"]);
$value2 = $name1->appendChild($nameValue);
$name = $customer->appendChild($name1);
$name = $doc->createElement('lastname');
$nameValue = $doc->createTextNode($_GET["lastname"]);
$value2 = $name->appendChild($nameValue);
$name = $customer->appendChild($name);
$name = $doc->createElement('password');
$nameValue = $doc->createTextNode($_GET["password"]);
$value2 = $name->appendChild($nameValue);
$name = $customer->appendChild($name);
$name = $doc->createElement('email');
$nameValue = $doc->createTextNode($_GET["email"]);
$value2 = $name->appendChild($nameValue);
$name = $customer->appendChild($name);
$name = $doc->createElement('phone');
$nameValue = $doc->createTextNode($_GET["phone"]);
$value2 = $name->appendChild($nameValue);
$name = $customer->appendChild($name);
echo "<xmp>".$doc->save($xmlFile)."</xmp>";
}
catch(Exception $e) { echo $e;}
echo "customer successfully registered and your new Id = ". $newID;
}
function isEmailUnique()
{
$xmlFile = "../../data/customer.xml";
try
{
$dom = DOMDocument::load($xmlFile);
$customers = $dom->getElementsByTagName("customer");
foreach($customers as $node)
{
$email = $node->getElementsByTagName("email");
$email = $email->item(0)->nodeValue;
if (($email == $_GET["email"])) return false;
}
}
catch(Exception $e)
{
$doc = new DomDocument('1.0');
$customers = $doc->createElement('customers');
$customers = $doc->appendChild($customers);
$doc->saveXML();
return true;
}
return true;
}
?>
I think you're missing a key equals sign here (inside registerCustomer() function):
"...firstname=" + firstname + "&lastname" + lastname + "&password="
Contrast with:
"...firstname=" + firstname + "&lastname=" + lastname + "&password="
This means the GET index lastname is never being set.
Related
I am working on a student registration form such that when a student fills the necessary information using a multi step form and submits, the filled information will be submitted to the database.
However, anytime I submit the filled information, the values will be inserted into the database including another complete row of null values.
I have tried to fix this thing but don't know where the problem is.
This is StudentSignup.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%#page import="java.sql.*"%>
<html>
<head>
<script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
<script language="javascript" type="text/javascript">
var xmlHttp;
<%--JavaScript on Academic Information Dropdown Using XmlHttpRequest--%>
function showDepartment(str) {
if (typeof XMLHttpRequest !== "undefined") {
xmlHttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlHttp === null) {
alert("Browser does not support XMLHTTP Request");
return;
} else {
var url = "departmentDBConnection.jsp";
url += "?progOfStudy=" + str;
xmlHttp.onreadystatechange = stateChange;
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
}
function stateChange() {
if (xmlHttp.readyState === 4 || xmlHttp.readyState === "complete") {
document.getElementById("department").innerHTML = xmlHttp.responseText
;
}
}
function showFaculty(str) {
if (typeof XMLHttpRequest !== "undefined") {
xmlHttp = new XMLHttpRequest();//create XMLHttpRequest object
}
else if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlHttp === null) {//If the browser doesn't support Ajax, exit now
alert("Browser does not support XMLHTTP Request");
return;
} else {
var url = "facultyDBConnection.jsp";
url += "?progOfStudy=" + str;
xmlHttp.onreadystatechange = stateChange1;
xmlHttp.open("GET", url, true);//Initiate the XMLHttpRequest object
xmlHttp.send(null);//Send the Ajax request to the server with the GET data
}
function stateChange1() {
if (xmlHttp.readyState === 4 || xmlHttp.readyState === "complete") {
document.getElementById("faculty").innerHTML = xmlHttp.responseText
;
}
}
}
</script>
<link rel="stylesheet" type="text/css" href="StudentSignUp.css">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Student Login</title>
</head>
<body>
<div id="wrapper">
<div id="headwrap">
<header>
<h1>School Name</h1>
<h3>Knowledge for development and unity</h3>
</header>
<nav>
<ul>
<li>Home</li>
</ul>
</nav>
<img src="images/kasulogo.jpg" />
</div>
</div>
<aside id="logsite">
<center>
<!--form name="form1" id="regForm" action="StudentCreateAccount.jsp"-->
<!--form id="regForm" method="post" onSubmit="submitForm(this);return false;"-->
<form id="regForm" >
<table cellspacing="5" border="0">
<thead>
<tr>
<th colspan="2" ><b><center id="CreateHead">Create a New Account</center></b></th>
</tr>
<tr>
<td colspan="2"><hr/></td>
</tr>
</thead>
<!-- One "tab" for each step in the form: -->
</table>
<div class="tab"><b><center>Personal Information:</center></b>
<table>
<tr>
<td colspan="2"><hr/></td>
</tr>
</table>
<table>
<tr>
<td>Matriculation*</td>
<td><input placeholder="" oninput="this.className = ''" name="MatricNo" required=""></td>
</tr>
<tr>
<td>First Name*</td>
<td><input placeholder="" oninput="this.className = ''" name="FName" required=""></td>
</tr>
<tr>
<td>Last Name*</td>
<td><input placeholder="" oninput="this.className = ''" name="LName" required=""></td>
</tr>
<tr>
<td>Other Names</td>
<td><input placeholder="" oninput="this.className = ''" name="OName"></td>
</tr>
<tr>
<td>Email Address</td>
<td><input placeholder="" oninput="this.className = ''" name="Email"></td>
</tr>
<tr>
<td>Phone Number*</td>
<td><input placeholder="" oninput="this.className = ''" name="Phone"></td>
</tr>
</table>
</div>
<div class="tab"><b><center>Academic Information:</center></b>
<table>
<tr>
<td colspan="2"><hr/></td>
</tr>
</table>
<table>
<tr>
<td>Programme*</td>
<!-- <td><p><input placeholder="" oninput="this.className = ''" name="Department"></p></td> -->
<td><p>
<select name='ProgOfStudy' onchange="showDepartment(this.value)">
<option value="none">--Select Programme--</option>
<%
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/cmsdb", "root", "");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("Select * from programmeofstudy");
while (rs.next()) {
%>
<option value="<%=rs.getString(1)%>"><%=rs.getString(2)%></option>
<%
}
%>
</select>
<p></td>
</tr>
<tr>
<td>Department*</td>
<td><p>
<div id='department'>
<select name='Department' >
<option value='-1'>--Select Department--</option>
</select>
</div>
<p></td>
</tr>
<tr>
<td>Faculty*</td>
<td><p>
<div id='faculty'>
<select name='Faculty' >
<option value='-1'>--Select Faculty--</option>
</select>
</div>
<p></td>
</tr>
</table>
</div>
<div class="tab"><b><center>Login Info:</center></b>
<table>
<tr>
<td colspan="2"><hr/></td>
</tr>
</table>
<table>
<tr>
<td>Password*</td>
<td><input type="password" placeholder="" oninput="this.className = ''" name="Password"></td>
</tr>
<tr>
<td>Retype Password*</td>
<td><input type ="password" placeholder="" oninput="this.className = ''" name="rePassword" oninput="setCustomValidity(value != password1.value ? 'Passwords do not match.' : '')"></td>
</tr>
</table>
</div>
<div style="overflow:auto;">
<div style="float:right;">
<button type="button" id="prevBtn" onclick="nextPrev(-1)">Previous</button>
<button type="button" id="nextBtn" onclick="nextPrev(1)">Next</button>
</div>
</div>
<!-- Circles which indicates the steps of the form: -->
<div style="text-align:center;margin-top:40px;">
<span class="step"></span>
<span class="step"></span>
<span class="step"></span>
</div>
</form>
<script type="text/javascript">
var currentTab = 0; // Current tab is set to be the first tab (0)
showTab(currentTab); // Display the crurrent tab
function showTab(n) {
// This function will display the specified tab of the form...
var x = document.getElementsByClassName("tab");
x[n].style.display = "block";
//... and fix the Previous/Next buttons:
if (n === 0) {
document.getElementById("prevBtn").style.display = "none";
} else {
document.getElementById("prevBtn").style.display = "inline";
}
if (n === (x.length - 1)) {
document.getElementById("nextBtn").innerHTML = "Submit";
} else {
document.getElementById("nextBtn").innerHTML = "Next";
}
//... and run a function that will display the correct step indicator:
fixStepIndicator(n);
}
function nextPrev(n) {
// This function will figure out which tab to display
var x = document.getElementsByClassName("tab");
// Exit the function if any field in the current tab is invalid:
if (n === 1 && !validateForm())
return false;
// Hide the current tab:
x[currentTab].style.display = "none";
// Increase or decrease the current tab by 1:
currentTab = currentTab + n;
// if you have reached the end of the form...
if (currentTab >= x.length) {
var frm = document.getElementById('regForm');
//var frm = new formData;alert(frm.MatricNo.value);
var MatNo = frm.MatricNo.value;//alert("MatNo is: "+MatNo);
var FName = frm.FName.value;
var LName = frm.LName.value;
var OName = frm.OName.value;
var eMail = frm.Email.value;
var phone = frm.Phone.value;
var pwd = frm.Password.value;
var storedTextProgOfStudy = frm.ProgOfStudy.options[frm.ProgOfStudy.selectedIndex].text;
var storedTextDepartment = frm.Department.options[frm.Department.selectedIndex].text;
var storedTextFaculty = frm.Faculty.options[frm.Faculty.selectedIndex].text;
//alert(storedTextProgOfStudy +" "+ " "+ storedTextDepartment +" "+storedTextFaculty +" "+MatNo);
var url = "StudentCreateAccount.jsp";
var parameters = "ProgOfStudy=" + storedTextProgOfStudy + '&Department=' + storedTextDepartment + '&Faculty=' + storedTextFaculty +
"&MatricNo=" + MatNo + "&FName=" + FName + "&LName=" + LName + "&OName=" + OName + "&Email=" + eMail + "&Phone=" + phone + "&Password=" + pwd;
var xhr = new XMLHttpRequest();
xhr.open("GET", url + "?" + parameters, true);
xhr.send(null);
window.location = url;
}
// Otherwise, display the correct tab:
showTab(currentTab);
}
function validateForm() {
// This function deals with validation of the form fields
var x, y, i, valid = true;
x = document.getElementsByClassName("tab");
y = x[currentTab].getElementsByTagName("input");
// A loop that checks every input field in the current tab:
for (i = 0; i < y.length; i++) {
// If a field is empty...
if (y[i].value === "") {
// add an "invalid" class to the field:
y[i].className += " invalid";
// and set the current valid status to false
valid = false;
}
}
// If the valid status is true, mark the step as finished and valid:
if (valid) {
document.getElementsByClassName("step")[currentTab].className += " finish";
}
return valid; // return the valid status
}
function fixStepIndicator(n) {
// This function removes the "active" class of all steps...
var i, x = document.getElementsByClassName("step");
for (i = 0; i < x.length; i++) {
x[i].className = x[i].className.replace(" active", "");
}
//... and adds the "active" class on the current step:
x[n].className += " active";
}
</script>
</center>
</aside>
<footer>
<br />
© 2018 . All right reserved.
</footer>
</div>
</body>
</html>
This is the StudentCreateAccount.jsp
<%# page import ="java.sql.*" %>
<%
Connection conn = null;
String matNo = request.getParameter("MatricNo");
String FName = request.getParameter("FName");
String LName = request.getParameter("LName");
String OName = request.getParameter("OName");
String email = request.getParameter("Email");
String phoneNo = request.getParameter("Phone");
String programmeOfStudy = request.getParameter("ProgOfStudy");
String department = request.getParameter("Department");
String faculty = request.getParameter("Faculty");
String pwd = request.getParameter("Password");
//String retypePwd = request.getParameter("rePassword");
String dbURL = "jdbc:mysql://localhost:3306/cmsdb";
String rootUser = "root";
String rootPwd = "";
String driver = "com.mysql.jdbc.Driver";
Class.forName(driver); //This loads the driver for the database
conn = DriverManager.getConnection(dbURL, rootUser, rootPwd);
Statement st = conn.createStatement();
ResultSet rs;
//This is the SQL String for retrieving data by name from the database.
rs = st.executeQuery("SELECT * FROM kasustudent WHERE MatricNo='" + matNo +"'");
if(rs.next()){
out.println("<script type=\"text/javascript\">");
out.println("alert('Matric Number already exist in the Database!');");
out.println("location='StudentLogin.jsp';");
out.println("</script>");
}else{
String query = "INSERT INTO kasustudent(MatricNo, FName, LName, ONames, Email, Phone, CourseOfStudy, Department, Faculty, Password) "
+ "VALUES ('" + matNo + "','" + FName + "','" + LName + "','" + OName + "','" + email + "','" + phoneNo + "','"
+ programmeOfStudy + "','" + department + "','" + faculty + "','" + pwd + "')";
st.executeUpdate(query);
out.println("<script type=\"text/javascript\">");
out.println("alert('Account Successfully Created!!\\nLogin to access your Dashboard!');");
out.println("location='StudentLogin.jsp';");
out.println("</script>");
st.close();
}
%>
Please assistance is highly appreciated.
Apologies to bore you with so much codes.
Even when the StudentCreateAccount.jsp (scriptlet) file is run, the null values will be inserted into the database.
Please, critically look into the codes and tell me the problem is?
Thank you so much in advance.
I am trying to execute a search on database. My goal is to take a search form and use ajax to request PHP to return a result. Problem is, I am not getting a response in ajax handleRequest function. Also, how do I send back a xml response from php. Here is my code. Sorry for the clutter.
index.php
<!doctype>
<html lang="en">
<head>
<title>Test Form</title>
<script src="js/validate.js"></script>
</head>
<body onload="setfocus();">
<span id="error"></span>
<form id ="searchForm" method="POST" action="/php/validate.php"
onsubmit="event.preventDefault(); process();">
<input type="text" placeholder="Eg. Canada" name="country" id="country_id"
onblur="validate(this.id, this.value);" required/>
<br />
<input type="text" placeholder="Eg. Toronto" name="city" id="city_id"
onblur="validate(this.id, this.value);" required/>
<br />
<label for="featues">Features</label>
WiFi<input type="checkbox" name="wifi" value="wifi" />
TV<input type="checkbox" name="tv" value="tv" />
Breakfast<input type="checkbox" name="breakfast" value="breakfast" />
<br />
<label>Room Type</label>
<select name="roomtype">
<option name="mastersuite" value="mastersuite">Master Suite</option>
<option name="suite" value="suite">Suite</option>
<option name="largeroom" value="largeroom">Large Room</option>
<option name="smallroom" name="smallroom">Small Room</option>
</select>
<br />
<label>Price Range</label>
<input type="text" name="minrange" id="price_min_range_id"
onblur="validate(this.id, this.value);" />
<input type="text" name="maxrange" id="price_max_range_id"
onblur="validate(this.id, this.value);" />
<br />
<label>Stay date</label>
<br />
<label>Arrival Date</label>
<input type="date" name="arrival" id="arrival" placeholder="MM/DD/YYYY"
onblur="validate(this.id, this.value);" required/>
<label>departure Date</label>
<input type="date" name="departure" id="departure" placeholder="MM/DD/YYYY"
onblur="validate(this.id, this.value);" />
<br />
<input type="submit" name="search" value="search">
</form>
<div id="responseDiv"></div>
</body>
</html>
validate.js
var xmlHttp;
//var serverAddr;
//var error;
var response;
function createHttpRequestObject(){
var responseObj;
//for IE
if(window.ActiveX){
var vers = new Array("MSXML2.XML.Http.6.0",
"MSXML2.XML.Http.5.0",
"MSXML2.XML.Http.4.0",
"MSXML2.XML.Http.3.0",
"MSXML2.XML.Http.2.0",
"Microsoft.XMLHttp");
for(var i=0; i<vers.length && !responseObj; i++){
try{
responseObj = new ActiveXObject(vers[i]);
}catch(e){
responseObj = false;
}
}
}
else{ //for all other browser
try{
responseObj = new XMLHttpRequest();
}catch(e){
responseObj = false;
}
}
if(!responseObj || responseObj === false){
alert("Failed to create response object");
}
else{
return responseObj;
}
}
function process(){
xmlHttp = createHttpRequestObject();
if(xmlHttp){
var firstname = encodeURIComponent(
document.getElementById("firstname").value);
var roomtype = encodeURIComponent(
document.getElementById("roomtype").options[
document.getElementById("roomtype").selectedIndex].value);
var minrange = encodeURIComponent(
document.getElementById("price_min_range_id").firstChild.value);
var maxrange = encodeURIComponent(
document.getElementById("price_max_range_id").firstChild.value);
var city = encodeURIComponent(document.getElementById("city_id").firstChild.value);
var country = encodeURIComponent(
document.getElementById("country_id").firsChild.value);
var arrivalDate = encodeURIComponent(
document.getElementById("arrivalDate").value);
var departureDate = encodeURIComponent(
document.getElementById("departureDate").value);
var amenity_breakfast = encodeURIComponent(
document.getElementByName("Breakfast").checked);
var amenity_tv = encodeURIComponent(
document.getElementByName("TV").checked);
var amenity_wifi = encodeURIComponent(
document.getElementByName("wifi").checked);
//get other filed values
xmlHttp.open("POST", "php/validate.php", true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.onreadystatechange = handleResponse;
xmlHttp.send("firstname=" + firstname + "&roomtype="+ roomtype + "&country="+ country + "&city=" + city + "&minrange=" + minrange + "&maxrange=" + maxrange + "&arrivalDate="+arrivalDate + "&departureDate="+ departureDate + "&breakfast="+
amenity_breakfast + "&tv="+amenity_tv + "&wifi="+ amenity_wifi);
}
else{
alert("Error connecting to server");
}
}
function handleResponse(){
var docdiv = document.getElementById("responsediv");
var table = "";
if(xmlHttp.readyState==4){
if(xmlHttp.status==200){
//the search info as xml
//var response = xmlHttp.responseXML;
response = xmlHttp.responseXml;
if(!response || response.documentElement){//catching errors with IE, Opera
alert('Invalide Xml Structure:\n'+ response.responseText);
}
var rootNodeName = response.documentElement.nodeName;
if(rootNodeName=="parseerror"){//catching error with firefox
alert('Invalid Xml Structure:\n');
}
var docroot = response.documentElement;
var responseroot = docroot.getElementByTagName("response");
//extracting all hotel values from search
var hotels = new Array(responseroot.getElementByTagName("hotels"));
table = "<table border='1px solid' margin='2px' padding='5px'>";
//docdiv.appendChild(table);
for(var i=0; i<hotels.legnth; i++){
var hotelroot = hotels[i].getElementTagName("name");
var hotelname = hotelroot.firstChild.data;
var hoteladd = hotels[i].getElementByTagName("hoteladd").firstChild.data;
var reqRoomNum = hotels[i].getElementTagName("reqroom").firsChild.data;
table +="<tr>";
//row = table.append(row);
//name column
table += "<td>";
table += hotelname + "</td>";
//address column
table += "<td>";
table += hoteladd + "</td>";
//desired roomttype
table += "<td>";
table += reqRoomNum + "</td>";
//docdiv.createElement("</tr>");
table += "</tr>";
}
table += "</table>";
}
docdiv.innerHTML= table;
}
}
function validate(fieldId, value){
//var error = 0;
//var errortext = '';
switch(fieldId){
/*case 'name':
var chk_name_regex = /^[A-Za-z ]{3,30}$/;
if(value.length<4 &&!chk_name_regex.test(value)){
print_error('Name format wrong',fiedlId);
}
break;*/
case 'country_id':
var chk_country_regex = /^[A-Za-z- ]{4,50}$/;
if(value.length<4 && !chk_country_regex.test(value)){
print_error('Country name format wrong',fieldId);
}
break;
case 'city_id':
var chk_city_regex = /^[A-Za-z- ]{4,50}$/;
if(value.length<4 && !chk_city_regex.test(value)){
print_error('City name format wrong',fieldId);
}
break;
case 'price_min_range_id':
var r = value;
if(r<0){
print_error('Min range must be zero atleast',fieldId);
}
break;
case 'price_max_range_id':
r = value;
if(!(r>=0 && r>=document.getElementById('price_min_range_id').firstChild.value)){
print_error('Max index must be atleast zero or greater than min',fieldId);
}
break;
case 'arrival':
var arrival = value;
var datecomp = arrival.explode("/");
var monthOk = parseInt(datecomp[0])>=1 && parseInt(datecomp[0])<=12;
var getleapday = parseInt(datecomp[2]) % 4===0 &&
parseInt(datecomp[2])%100===0 && parseInt(datecomp[2])%400===0;
var dayOk = parseInt(datecomp[1])>=1 && parseInt(datecomp[2])<=31;
var yearOk = parseInt(datecomp[2])>2015;
if(monthOk && dayOk && yearOk){
print_error('Date format is wrong',fieldId);
}
break;
}
}
function print_error(msg, fieldId){
var errorSpan = document.getElementById('error');
errorSpan.innerHTML = "<p text-color='red'>" + msg + "</p>";
document.getElementById(fieldId).focus();
}
function setfocus(){
document.getElementById('country_id').focus();
}
validate.php
<?php
function just_check(){
print_r($_POST);
}
just_check();
//config script
require_once('config.php');
//vars for all the fileds
$country = $city = $wifi = $tv = $breakfast = $minrange = $maxrange
= $arrival = $departure = $roomtype = '';
//server side input validation
if($_SERVER['REQUEST_METHOD']=='POST'){
$country = inputValidation($_POST['country']);
$city = inputValidation($_POST['city']);
$minrange = inputValidation($_POST['minrange']);
$maxrange = inputValidation($_POST['maxrange']);
$arrival = inputValidation($_POST['arrivalDate']);
$departure = inputValidation($_POST['departureDate']);
$roomtype = $_POST['roomtype'];
if(isset($_POST['wifi'])){
$wifi = true;
}
if(isset($_POST['tv'])){
$tv = true;
}
if(isset($_POST['breakfast'])){
$breakfast = true;
}
}
//echo $country . " " . $city . '<br >';
//connect to mysql
$db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME)
or die('Could not connect to db');
//query the database matching fields;
$query = "SELECT hotel_id, hotel_name FROM allhotels WHERE ";
//echo $query . '<br />';
if(isset($country)){
$query .= "(hotel_country='$country') AND";
}
//echo $query . '<br />';
if(isset($city)){
$query .= " (hotel_city='$city') AND";
}
$query = substr($query,0, -4);
// echo $query . '<br />';
$res = $db->query($query);
//echo $query . '<br />';
if(!$res){
echo $db->errno . '->' . $db->error;
}
//setting header to XML
header('ContentType: text/xml');
//creating XML response string"
$dom = new DOMDocument();
$response = $dom->createElement("response");
$dom->appendChild($response);
while($row = $res->fetch_array(MYSQLI_ASSOC)){
//matching room field value for query
$roomfield='';
if($roomtype == 'mastersuite'){
$roomfield = 'hotel_master_suites';
}
else if($roomtype == 'suite'){
$roomfield = 'hotel_suite';
}
else if($roomtype == 'largeroom'){
$roomfield = 'hotel_large_rooms';
}
else{
$roomfield = 'hotel_small_rooms';
}
//query with the roomfield and hotel_id value
$htl_id = $row['hotel_id'];
$subquery = "SELECT hotel_add, $roomfield FROM spechotel WHERE ".
"(hotel_id = $htl_id) AND ($roomfield > 0) AND";
if(isset($wifi)){
$subquery .= " (wifi=1) AND";
}
//echo $subquery . '<br />';
if(isset($tv)){
$query .= " (tv=1) AND";
}
//echo $query . '<br />';
if(isset($breakfast)){
$query .= " (breakfast=1) AND";
}
//echo $query . '<br />';
$subquery = substr($subquery,0, -4);
// echo $query . '<br />';
//echo $subquery . '<br />';
$subrow = $db->query($subquery);
$subrow = $subrow->fetch_array(MYSQLI_ASSOC);
$hotel_header = $dom->createElement("hotels");
$hotel_name = $dom->createElement("name");
$hotel_name->appendChild($dom->createTextNode($row['hotel_name']));
$hotel_add = $dom->createElement("hoteladd");
$hotel_add->appendChild($dom->createTextNode($subrow['hotel_add']));
//$hotel_postal = $hotel_header->apppendChild("hotelpostal");
//$hotel_postal->createTextNode($subrow['']);
$hotel_req_room = $dom->createElement("reqroom");
$hotel_req_room->appendChild($dom->createTextNode($subrow[$roomfield]));
$hotel_header->appendChild($hotel_name);
$hotel_header->appendChild($hotel_add);
$hotel_header->appendChild($hotel_req_room);
}
$xmlString = $dom->saveXML();
//print table
$db->close();
//close connection
//return search
function print_search_result(){
global $xmlString;
echo $xmlString;
}
print_search_result();
function inputValidation($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
I cannot get this form to work. Everything I do it just comes up with an error and also says that the phone number isn't valid but when I look at the code I can't really see why it isn't working.
P.S. I don't really have any understanding of PHP or JS so I don't really know what I'm looking for when it comes to errors.
Thank you for any help.
Here's the HTML
<form action="contact.php" method="post" id="cform" name="cform">
<ul id="homehireus" class="hireform contactform">
<li>
<label>Name:<span class="required">*</span></label>
<input name="name" id="name" type="text" value="" tabindex="1">
</li>
<li>
<label>Phone:</label>
<input name="phone" id="phone" type="text" value="" tabindex="2">
</li>
<li>
<label>Email:<span class="required">*</span></label>
<input name="email" id="email" type="text" value="" tabindex="3">
</li>
<li>
<label>Subject:</label>
<input name="subject" id="subject" type="text" value="" tabindex="4">
</li>
<li>
<label>Message:<span class="required">*</span></label>
<textarea name="message" id="message" tabindex="5"></textarea>
</li>
<li>
<input type="button" id="send-message" value="Send Details To iPhone Repairs" tabindex="6">
<div id="output" class="contactpage-msg"></div>
</li>
</ul>
</form>
PHP
<?php
$send_email_to = "naomi.deluca#me.com";
function send_email($name,$email,$phone,$subject,$message)
{
global $send_email_to;
if($message=='message')$message='';
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= "From: ".$email. "\r\n";
$message = "<strong>Email = </strong>".$email."<br>";
$message .= "<strong>Name = </strong>".$name."<br>";
$message .= "<strong>Phone = </strong>".$phone."<br>";
$message .= "<strong>Message = </strong>".$message."<br>";
#mail($send_email_to, $subject, $message,$headers);
return true;
}
function validate($name,$email,$phone,$message,$subject)
{
$return_array = array();
$return_array['success'] = '1';
$return_array['name_msg'] = '';
$return_array['email_msg'] = '';
$return_array['phone_msg'] = '';
$return_array['message_msg'] = '';
$return_array['subject_msg'] = '';
if($email == '')
{
$return_array['success'] = '0';
$return_array['email_msg'] = 'email is required';
}
else
{
$email_exp = '/^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$email)) {
$return_array['success'] = '0';
$return_array['email_msg'] = 'Enter valid email.';
}
}
if($name == '')
{
$return_array['success'] = '0';
$return_array['name_msg'] = 'Name is required';
}
else
{
$string_exp = "/^[A-Za-z .'-]+$/";
if (!preg_match($string_exp, $name)) {
$return_array['success'] = '0';
$return_array['name_msg'] = 'Enter valid Name.';
}
}
if($phone == '')
{
$return_array['success'] = '0';
$return_array['phone_msg'] = 'Phone is required';
}
else
{
$string_exp = "/^[A-Za-z .'-]+$/";
if (!preg_match($string_exp, $phone)) {
$return_array['success'] = '0';
$return_array['phone_msg'] = 'Enter valid Phone.';
}
}
if($subject == '')
{
$return_array['success'] = '0';
$return_array['subject_msg'] = 'Subject is required';
}
if($message == '')
{
$return_array['success'] = '0';
$return_array['message_msg'] = 'Message is required';
}
else
{
if (strlen($message) < 2) {
$return_array['success'] = '0';
$return_array['message_msg'] = 'Enter valid Message.';
}
}
return $return_array;
}
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$message = $_POST['message'];
$subject = $_POST['subject'];
$return_array = validate($name,$email,$phone,$message,$subject);
if($return_array['success'] == '1')
{
send_email($fname,$email,$phone,$subject,$message);
}
header('Content-type: text/json');
echo json_encode($return_array);
die();
?>
JS
$(document).ready(function () {
$('div#output').hide();
//bind send message here
$('#send-message').click(sendMessage);
$('button.close').live('click', function () {
$(this).parent().find('p').html('');
$(this).parent().hide();
});
});
/* Contact Form */
function checkEmail(email) {
var check = /^[\w\.\+-]{1,}\#([\da-zA-Z-]{1,}\.){1,}[\da-zA-Z-]{2,6}$/;
if (!check.test(email)) {
return false;
}
return true;
}
function sendMessage() {
// receive the provided data
var name = $("input#name").val();
var email = $("input#email").val();
var subject = $("input#subject").val();
var phone = $("input#phone").val();
var message = $("textarea#message").val();
message = 'message';
// check if all the fields are filled
if (name == '' || phone == '' || email == '' || subject == '' || message == '') {
$("div#output").show().html('<button type="button" class="close" data-dismiss="alert-close">x</button><p class="alert-close">You must enter all the fields!</p>');
return false;
}
// verify the email address
if (!checkEmail(email)) {
$("div#output").show().html('<button type="button" class="close" data-dismiss="alert">x</button><p>Please enter a valid Email Address</p>');
return false;
}
// make the AJAX request
var dataString = $('#cform').serialize();
$.ajax({
type: "POST",
url: 'contact.php',
data: dataString,
dataType: 'json',
success: function (data) {
if (data.success == 0) {
var errors = '<ul><li>';
if (data.name_msg != '')
errors += data.name_msg + '</li>';
if (data.email_msg != '')
errors += '<li>' + data.email_msg + '</li>';
if (data.phone_msg != '')
errors += '<li>' + data.phone_msg + '</li>';
if (data.message_msg != '')
errors += '<li>' + data.message_msg + '</li>';
if (data.subject_msg != '')
errors += '<li>' + data.subject_msg + '</li>';
$("div#output").removeClass('alert-success').addClass('alert-error').show().html('<button type="button" class="close" data-dismiss="alert">x</button><p> Could not complete your request. See the errors below!</p>' + errors);
}
else if (data.success == 1) {
$("div#output").removeClass('alert-error').addClass('alert-success').show().html('<button type="button" class="close" data-dismiss="alert">x</button><p>You message has been sent successfully!</p>');
}
},
error: function (error) {
$("div#output").removeClass('alert-success').addClass('alert-error').show().html('<button type="button" class="close" data-dismiss="alert">x</button><p> Could not complete your request. See the error below!</p>' + error.statusText);
}
});
return false;
}
The regular expression that validate the name is the same as the one who validate the phone number, quite weird isn't it?
To validate every kind of phone number, you just have check if $phone contains only digit with ctype_digit().
How about using
/^[0-9]+$/ instead of /^[A-Za-z .'-]+$/ at $string_exp = "/^[A-Za-z .'-]+$/";?
Or
if (preg_match($string_exp, $phone)) { instead of if (!preg_match($string_exp, $phone)) {
Your regex that you use to validate phone numbers:
/^[A-Za-z .'-]+$/
Doesn't accept digits. Given that a phone number typically has digits in it, this regex is most likely invalid in this context.
Your regex for validating phone number isn't correct.
Replace the line:
$string_exp = "/^[A-Za-z .'-]+$/";
With
$string_exp = "/^(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?\d{3}[\s-]?\d{4}$/i";
The above regular expression accepts phone numbers in following formats:
555-555-5555
5555425555
555 555 5555
1(519) 555-4444
1 (519) 555-4422
1-555-555-5555
1-(555)-555-25555
Here I am uploading this link http://harvey.binghamton.edu/~rnaik1/myForm.html where you can see how my scroll up n down button is working in javascript but now I am working with Ajax request to a php script on the server to retrieve all of the data from the database table.
Here is the link for the work i have done:http://harvey.binghamton.edu/~rnaik1/myScrollform.html
Everything is working fine for me except scroll up and scroll down button.
Once you add 5 records in a list after entering 6th record it will show latest 5 records.
I want to make the scrollup and down button working for myScrollform.html in the same way as in myForm.html. Any help would be helpful to me and appreciated.
Here is my code:
<html>
<head>
<title>My Scrolling Data Form</title>
<script src="./jquery-1.11.0.min.js"></script>
</head>
<body bgcolor="silver">
<center><h1>My Scrolling Data Form</h1>
<div id="scrollbar">
<input type="button" name="up" id="scrollup" value="Scroll Up" >
<input type="button" name="up" id="scrolldown" value="Scroll Down">
</div>
<div id="mydata" style="height: 200px; overflow-y: scroll">
Currently we have no data
</div>
<hr>
<div id="addformdata">
<form name="addForm" >
To add data to the list, fill in the form below and click on "Add"
<br>
<td><input type="text" id="name" name="namei" value=""></td>
<td><input type="text" id="ssn" name="ssni" value="" ></td>
<td><input type="text" id="date" name="birthi" value="" ></td>
<td><input type="text" id="currency" name="xxxxi" value=""></td>
<input type="button" name="add" value="Add" onclick="validateForm(); return false;">
</form>
</div>
</center>
</body>
</html>
<script type="text/javascript">
// Arrays to store values
var name_Array=new Array();
var ssn_Array=new Array();
var date_Array=new Array();
var currency_Array=new Array();
var Index = 0;
var first = 0;
var last = 0;
var scrolled = 0;
var random_Array=new Array();
$(document).ready(function(){
fetchdata();
$("#scrollup").on("click" ,function(){
// alert('hi');
// scrolled=scrolled+100;
$("#mydata").animate({
scrollTop: 0
}, 800);
});
$("#scrolldown").on("click" ,function()
{
// console.log($elem.height());
$("#mydata").animate({
scrollTop: 5000
}, 800);
});
});
function deleteRecord(id)
{
if(confirm('Are you Sure you Want to delete this record')){
$.ajax({
url:"insdel.php",
type:'POST',
data: {
"action": "delete",
"id": id
},
success:function(data)
{
fetchdata()
console.log('success');
}
});
}
}
function fetchdata()
{
// var scrolled=0
$.ajax({
url:"insdel.php",
type:'POST',
data: {
"action": "fetch"
},
success:function(data)
{
$("#mydata").html('')
$("#mydata").html(data);
console.log('success');
}
});
}
function validateForm()
{
var name = document.getElementById("name");
var ssn = document.getElementById("ssn");
var date = document.getElementById("date");
var currency = document.getElementById("currency");
var error = "";
//Name validation
if(name.value=="")
{
//Check for empty field
name.focus();
error = "Please Enter Name\n";
}
else
{ //format specifier
var letters = /^[a-zA-Z_ ]+$/;
//Check for format validation
if(!name.value.match(letters))
{
name.focus();
error = error + "Name contains only characters and spaces\nPlease Renter Name\n";
}
}
//Date validation
if(date.value=="")
{
//Check for empty field
date.focus();
error = error + "Please Enter Date\n";
}
else
{ //format specifier
var date_regex = /^((((0[13578])|([13578])|(1[02]))[\/](([1-9])|([0-2][0-9])|(3[01])))|(((0[469])|([469])|(11))[\/](([1-9])|([0-2][0-9])|(30)))|((2|02)[\/](([1-9])|([0-2][0-9]))))[\/]\d{4}$|^\d{4}$/;
//check for format validation
if(!date.value.match(date_regex))
{
date.focus();
error = error + "Date must be in mm/dd/yyyy format\nPlease Renter Date\n";
}
}
//SSN validation
if(ssn.value=="")
{
//check for empty field
ssn.focus();
error = error + "Please Enter SSN\n";
}
else
{
//format specifier
var numbers = /^\d{3}((-?)|\s)\d{2}((-?)|\s)\d{4}$/g;
//check format validation
if(!ssn.value.match(numbers))
{
ssn.focus();
error = error + "SSN must be in xxx-xx-xxxx format\nPlease Renter SSN\n";
}
}
//Currency validation
if(currency.value=="")
{
//check for empty field
currency.focus();
error = error + "Please Enter Currency\n";
}
else
{
//format specifier
var pattern = /^(\$)\d+(\.\d{1,3})?$/g ;
//check for format validation
if(!currency.value.match(pattern))
{
currency.focus();
error = error + "Currency must be in $xx.xxx format\nPlease Renter Currency\n";
}
}
if(error)
{
alert(error);
return false;
}
else
{
var name = document.getElementById("name").value;
var ssn = document.getElementById("ssn").value;
var date = document.getElementById("date").value;
var currency = document.getElementById("currency").value;
console.log(name)
adduser(name,ssn,date,currency);
return true;
}
}
function insertToList()
{
// call a function to validate the fields
var valid_function = validateForm();
if(valid_function == false)
{
return false;
}
else
{
//get the entered values from fields
var name = document.getElementById("name");
var ssn = document.getElementById("ssn");
var date = document.getElementById("date");
var currency = document.getElementById("currency");
// push the values in the array
name_Array.push(name.value);
ssn_Array.push(ssn.value);
date_Array.push(date.value);
currency_Array.push(currency.value);
// generate and push random number in the array to search the record in array and then delete that record.
random_Array.push(Math.floor((Math.random()*100)+1));// http://stackoverflow.com/questions/8610635/how-do-you-use-math-random-to-generate-random-ints
//function to insert values to list
InsertValues();
// clear the fields after each add
clearFields();
alert("Record is successfully added to above list.");
// set focus back on the name field
name.focus();
}
}
function clearFields()
{
document.getElementById("name").value = "";
document.getElementById("ssn").value = "";
document.getElementById("date").value = "";
document.getElementById("currency").value = "";
}
// function to add to the list
function InsertValues()
{
var temp = 1,temp1 = 1,index = 0,i=0;
index = name_Array.length - 5;
for(i=0;i< name_Array.length;i++)
{
// when only first 5 entries are added to the list
if(name_Array.length>5)
{
// skip the first values so that only top 5 are shown in the list
if(temp>s)
{
if(temp1==5)
{
last = i;
}
else if(temp1==1)
{
first = i;
Index = i;
}
if(temp1<=5)
{
//initialise values of fields to the list
var str = "name" + temp1;
document.getElementById(str).value = name_Array[i];
str = "ssn" + temp1;
document.getElementById(str).value = ssn_Array[i];
str = "birth" + temp1;
document.getElementById(str).value = date_Array[i];
str = "xxxx" + temp1;
document.getElementById(str).value = currency_Array[i];
str = "random" + temp1;
document.getElementById(str).value = random_Array[i];
}
temp1++;
}
}
else
{
var str = "name" + temp;
document.getElementById(str).value = name_Array[i];
str = "ssn" + temp;
document.getElementById(str).value = ssn_Array[i];
str = "birth" + temp;
document.getElementById(str).value = date_Array[i];
str = "xxxx" + temp;
document.getElementById(str).value = currency_Array[i];
str = "random" + temp;
document.getElementById(str).value = random_Array[i];
}
temp++;
}
}
// Delete a record from the list
function delete_a_Record(record)
{
var remove = 0,i=0,j=1;
var name = document.getElementById("name" + record.value);
var delRecord = document.getElementById("random" + record.value);
if(name.value)
{
remove = 1;
}
// check for the existence of record
if(remove == 1)
{
if(confirm("Click on 'OK' to delete the record\n"))
{
while(i < random_Array.length)
{
if(delRecord.value==random_Array[i])
{
// if yes then remove that record from list
name_Array.splice(i, 1);
ssn_Array.splice(i, 1);
date_Array.splice(i, 1);
currency_Array.splice(i, 1);
random_Array.splice(i, 1);
}
i++;
}
// make entire list empty
while(j <= 5)
{
var str = "name" + j;
document.getElementById(str).value = "";
str = "ssn" + j;
document.getElementById(str).value = "";
str = "birth" + j;
document.getElementById(str).value = "";
str = "xxxx" + j;
document.getElementById(str).value = "";
str = "random" + j;
document.getElementById(str).value = "";
j++;
}
//call this function again to insert values in the list
InsertValues();
record.checked = false;
}
}
else
{
alert("Nothing to delete in this record.");
record.checked = false;
}
}
// function to perform scrollUp n scrollDown
function handleScrolling(type)
{
var j,k,temp2 = 1;
// perform scroll only when there are more than 5 records in the list
if(name_Array.length>5)
{ // scroll up
if(type==1)
{
first--; // decrement the pointer to see upper records
if(first>=0)
{
for (j = first; j < name_Array.length; j++) // its showing top most record from jth position
{
var str = "name" + temp2;
document.getElementById(str).value = name_Array[j];
str = "ssn" + temp2;
document.getElementById(str).value = ssn_Array[j];
str = "birth" + temp2;
document.getElementById(str).value = date_Array[j];
str = "xxxx" + temp2;
document.getElementById(str).value = currency_Array[j];
str = "random" + temp2;
document.getElementById(str).value = random_Array[j];
temp2++;
}
}
else
{
alert("Top of the list is reached\n");
first++;// increment the pointer to see lower records
}
}
else // scroll down
{
// increment the start point to see lower records if any
first++;
if(first<=Index)
{
for (k = first; k < name_Array.length; k++) //its showing bottom most record in the list from kth position
{
var str = "name" + temp2;
document.getElementById(str).value = name_Array[k];
str = "ssn" + temp2;
document.getElementById(str).value = ssn_Array[k];
str = "birth" + temp2;
document.getElementById(str).value = date_Array[k];
str = "xxxx" + temp2;
document.getElementById(str).value = currency_Array[k];
str = "random" + temp2;
document.getElementById(str).value = random_Array[k];
temp2++;
}
}
else
{
alert("Bottom most record is reached\n");
first--;//decrement the pointer to see upper records if any
}
}
}
else
{
alert("Scrolling strikes for records more than 5\n");
return false;
}
}
function adduser(name,ssn,date,currency)
{
$.ajax({
url:"insdel.php",
type:'POST',
data: {
"name": name,
"ssn": ssn,
"date": date,
"currency": currency,
"action": "add"
},
success:function(data){
console.log('success');
fetchdata();
}
});
}
</script>
//php file
<?php
extract($_POST);
$con = mysql_connect('localhost', 'root', '');
if (!$con) {
die('Could not connect: ' . mysql_error($con));
}
//mysql_select_db("ripal");
mysql_select_db("test");
//$sql = "SELECT * FROM user WHERE id = '" . $q . "'";
if ($action == 'add') {
$sql = "INSERT INTO myform(name,ssn,date,income)VALUES('" . mysql_real_escape_string($name) . "','" . mysql_real_escape_string($ssn) . "','" . mysql_real_escape_string($date) . "','" . mysql_real_escape_string($currency) . "')";
// echo $sql;
mysql_query($sql);
echo mysql_insert_id();
} else if ($action == 'fetch') {
$sql = "select * from myform";
// echo $sql;
$result = mysql_query($sql);
$str = '<form name="myForm">
<table width="page">
<tr>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td></td>
</tr>';
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$name = $row['name'];
$ssn = $row['ssn'];
$date = $row['date'];
$currency = $row['income'];
$str.='<tr>
<td><input type="radio" id="' . $id . '" name="del" onclick="deleteRecord(this.id);"></td>
<td><input readonly type="text" value="' . $name . '" id="name1" name="name"></td>
<td><input readonly type="text" value="' . $ssn . '" id="ssn1" name="ssn"></td>
<td><input readonly type="text" value="' . $date . '" id="birth1" name="birth"></td>
<td><input readonly type="text" value="' . $currency . '" id="xxxx1" name="xxxx"><input type="hidden" name="random1" id="random1"></td>
</tr>';
}
}
$str.=' <tr>
<td colspan="5" id="scrollCount" align="center" style="padding-top:10px;"> </td>
</tr>
</table>
</form>';
if (mysql_num_rows($result) == 0) {
echo 'No data in Our Database please add one or more';
} else {
echo $str;
}
} else if ($action = 'delete') {
$sql = "DELETE from myform WHERE id=$id";
// echo $sql;
$result = mysql_query($sql);
echo $result;
}
mysql_close($con);
this is my code...
How get the textbox array value to store in database...
<html>
<head>
<script type="text/javascript">
var max = 4; //highest number to go to
var currentIndex = 0;
function btnClick() {
if(currentIndex < max){
currentIndex++;
postClick();
}
}
function Previous(){
if(currentIndex>0){
currentIndex--;
postClick();
}
}
function postClick() {//whatever you want to happen goes here
var sahans = new Array();
sahans[currentIndex] == d;
var d = document.getElementById("div");
d.innerHTML = "<p><input type='text' name='name"+currentIndex+"[]'>";
d.innerHTML += "<p><input type='text' name='topic"+currentIndex+"[]'>";
document.getElementById("div").style.display = "";
}
</script>
</head>
<body>
<form id="form1">
<div>
<input type="button" value="Previous" onclick="Previous();" />
<input type="button" value="Next" onclick="btnClick();" />
<div id="div"></div>
</div>
</form>
</body>
</html>
JavaScript:
function store(form) {
var input = form.getElementsByTagName('input');
var myarray = Array();
for (var i = 0; i < input.length; i++) {
if (input[i].getAttribute('type') == 'text') {
myarray[input[i].getAttribute('name')] = input[i].value;
}
}
for (var i in myarray) {
alert(i + ': ' + myarray[i]);
}
}
HTML:
<form onsubmit="store(this); return false">
<p>
<input type="text" name="name" /><br />
<input type="text" name="topic" />
</p>
<p>
<input type="submit" value="Store in database" />
</p>
</form>
Edit:
Ok, now I made a full example with AJAX and the actual saving to the database. The AJAX call uses 'POST'. Simply fill in the number of fields that you want in the max variable.
JavaScript:
var max = 10;
var current = 0;
function goto(form, pos) {
current += pos;
form.prev.disabled = current <= 0;
form.next.disabled = current >= max - 1;
var fields = form.getElementsByTagName('fieldset');
for (var i = 0; i < fields.length; i++) fields[i].style.display = 'none';
fields[current].style.display = 'block';
form['name' + current].focus();
}
function store(form) {
var input = form.getElementsByTagName('input');
var data = '';
for (var i = 0; i < input.length; i++) {
if (input[i].getAttribute('type') == 'text')
data += '&' + input[i].getAttribute('name') + '=' + input[i].value;
}
data = encodeURI('n=' + max + data);
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
xhr.open('POST', 'store.php', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader('Content-length', data.length);
xhr.setRequestHeader('Connection', 'close');
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if (this.responseText != '')
alert(this.responseText);
else {
form.submit.value = 'Saved!';
setTimeout(function() { form.submit.value = 'Save to database' }, 500);
}
}
}
xhr.send(data);
}
window.onload = function() {
var form = document.forms[0];
var container = form.getElementsByTagName('div')[0];
container.innerHTML = '';
for (var i = 0; i < max; i++)
container.innerHTML += '<fieldset><legend>Entry ' + (i + 1) + ' / ' + max + '</legend><input type="text" name="name' + i + '" /><br /><input type="text" name="topic' + i + '" /></fieldset>';
goto(form, 0);
}
HTML:
<form action="submit.php" method="post" onsubmit="store(this); return false">
<p>
<input type="button" name="prev" onclick="goto(this.form, -1)" value="Previous" />
<input type="button" name="next" onclick="goto(this.form, +1)" value="Next" />
</p>
<div>
<noscript>Please enable JavaScript to see this form correctly.</noscript>
</div>
<p>
<input type="submit" name="submit" value="Store in database" />
</p>
</form>
Users who have JS disabled will see what's in the <noscript> tag, otherwise it's replaced with the fieldsets. Also it's good to make an alternative submit page (submit.php) for users who have JS disabled. Below is store.php, the AJAX submit script.
PHP (store.php):
<?php
if (empty($_POST['n']) || $_POST['n'] < 1) die('Invalid request!');
$fields = array('name', 'topic');
$errors = '';
for ($i = 0; $i < $_POST['n']; $i++) {
foreach ($fields as $field) {
if (empty($_POST[$field . $i]))
$errors .= '- ' . $field . ' ' . ($i + 1) . "\n";
}
}
if ($errors != '')
die("Please fill in the following fields:\n" . $errors);
$db = mysql_connect('localhost', 'root', '');
mysql_select_db('mydb', $db);
for ($i = 0; $i < $_POST['n']; $i++) {
$name = mysql_real_escape_string($_POST['name' . $i]);
$topic = mysql_real_escape_string($_POST['topic' . $i]);
mysql_query(' INSERT INTO entries (id, name, topic) VALUES (' . $i . ', "' . $name . '", "' . $topic . '")
ON DUPLICATE KEY UPDATE name = "' . $name . '", topic = "' . $topic . '"
') or die('Database error!');
}
mysql_close($db);
?>
The output text of this script (if there is an error) is displayed in the JavaScript alert.
I hope it's working for you now.
This would be help ful for you
<input type="textbox" name="Tue[]" />
<input type="textbox" name="Tue[]" />
<input type="textbox" name="Tue[]" />
<input type="textbox" name="Tue[]" />
<script type="text/javascript">
function validateText(event){
var tar_ele = $(event.target);
if(tar_ele.val() is not valid)
tar_ele.focus();
}
</script>
<input type="text" name="Tue[]" onblur="validateText(event)"/>
javascript text box array and get values and focus on particular field