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
Related
I am attempting to build a website to assist with recording times of events during ems calls. I have replicated our protocols and am using localstorage to record when and what event happens. When the incident is over, all the events that have been clicked are displayed on a report page where the information can be sent via email.
Everything seems to work, however, if another page is opened, the localstorage seem to clear and only the buttons clicked on the most recent page appear. I need every button clicked recorded for the report.
This is my JS:
//GO BACK BUTTON
function goBack() {
window.history.back();
}
// DATE FORMATER
function convertDate() {
var d = new Date();
var a = [(d.getMonth() + 1),
(d.getDate()),
(d.getFullYear()),
].join('-');
var b = [(d.getHours()),
(d.getMinutes()),
(d.getSeconds()),
].join(':');
return (b + ' ' + a);
}
///////////////////button////////////////////////
$(document).ready(function () {
var report = {};
var myItem = [];
$('button').click(function () {
var itemTime = convertDate() + " ___ " ;
var clickedBtnID = $(this).text() + " # " ;
item = {
ITEM: clickedBtnID,
TIME: itemTime ,
};
myItem.push(item);
localStorage.report = JSON.stringify(myItem);
});
});
And this is part of the report page:
<script>
window.onload = function () {
var areport = JSON.stringify(localStorage.report);
console.log(areport);
areport = areport.replace(/\\"/g, "");
areport = areport.replace(/{/g, "");
areport = areport.replace(/}/g, "");
areport = areport.replace(/[\[\]']+/g, "");
areport = areport.replace(/,/g, "");
areport = areport.replace(/"/g, "");
console.log(areport);
document.getElementById('result').innerHTML = areport;
};
</script>
<body>
<div class="container-fluid">
<h1>Report</h1>
<?php
if (isset($_POST["send"])) {
$incident = $_POST['incident'];
$name = $_POST['name'];
$address = $_POST['address'];
$dob = $_POST['dob'];
$gender = $_POST['gender'];
$reportData = $_POST['reportData'];
if ($incident == '') {
echo $incident = 'No incident number entered.';
echo '<br>';
} else {
echo $incident . '<br>';
}
if ($name == '') {
echo $name = 'No name entered.';
echo '<br>';
} else {
echo $name . '<br>';
}
if ($address == '') {
echo $address = 'No address entered.';
echo '<br>';
} else {
echo $address . '<br>';
}
if ($dob == '') {
echo $dob = 'No birthdate entered.';
echo '<br>';
} else {
echo $dob . '<br>';
}
if ($gender == '') {
echo $gender = 'No gender entered.';
echo '<br>';
} else {
echo $gender . '<br>';
}
if ($reportData == null) {
echo $reportData = 'No report entered.';
echo '<br>';
} else {
echo $reportData . '<br>';
}
//mail
$headers = "From: CCEMP.info <ccemlbaw#server237.web-hosting.com> \r\n";
$reEmail = $_POST['reEmail'];
$reEmail1 = $_POST['reEmail1'];
//$areport = json_decode($_POST['localStorage.report']);
$msg = "Incident: " . $incident . "\n" . "Name: " . $name . "\n" . "Address:
". $address . "\n" . "DOB: " . $dob . "\n" . "Gender: " . $gender . "\n" .
$reportData;
mail($reEmail, 'Incident:' . $incident, $msg, $headers);
mail($reEmail1, 'Incident:' . $incident, $msg, $headers);
}//end of submit
?>
Here is a sample button:
<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">General Truama</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
<a class="dropdown-item" >Continue Assessment</a>
<a class="dropdown-item" href="GATA.php">Go to Truama</a>
</div>
</div>
Thanks.
You are not using localStorage, just setting .report on global localStorage variable. You would see this issue if you used strict mode ("use strict"; at top of the js file).
instead use:
localStorage.setItem("report", JSON.stringify(myItem));
and to get the item
localStorage.getItem("report");
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
This does not set the item to localStorage. In fact, localStorage.report is undefined.
localStorage.report = JSON.stringify(myItem);
This does.
localStorage.setItem('report', JSON.stringify(myItem));
I wasn't adding the localStorage from the previous page to the new one.
var myItem = [];
$(document).ready(function () {
$('button').click(function () {
var itemTime = convertDate() + " ___ " ;
var clickedBtnID = $(this).text() + " # " ;
var item = {
ITEM: clickedBtnID,
TIME: itemTime ,
};
myItem.push(item);
localStorage.setItem('report', JSON.stringify(myItem));
console.log(myItem);
});
var areport = localStorage.getItem("report");
myItem.push(areport);
});
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.
I have a form with a submit button and would like to remove the button and replace it with a loading gif image. I don't want this to happen just on click, since the form is verified I want the button to disappear only when all input fields are correctly filled so that the gif image shows progress. How can I do this?
Note: This is not a event to fire on success either, I want it to be a progress indicator. On success the form fade and display a message: "Thanks for contacting us! We will get back to you very soon..." and the jQuery below already handles this.
Here is the php code:
<?php
// Email address verification
function isEmail($email) {
return preg_match('|^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]{2,})+$|i', $email);
};
if($_POST) {
// Enter the email where you want to receive the message
$emailTo = 'example#gmail.com';
$clientName = addslashes(trim($_POST['name']));
$clientEmail = addslashes(trim($_POST['email']));
$number = addslashes(trim($_POST['number']));
$message = addslashes(trim($_POST['message']));
$subject = 'Query from My Domain';
$sendMessage = 'Hi' . "\n\n";
$sendMessage .= $message . "\n\n";
$sendMessage .= 'From: ' . $clientName . "\n";
$sendMessage .= 'Email: ' . $clientEmail . "\n";
$sendMessage .= 'Contact number: ' . $number . "\n";
$array = array();
$array['nameMessage'] = '';
$array['emailMessage'] = '';
$array['numberMessage'] = '';
$array['messageMessage'] = '';
if($clientName == '') {
$array['nameMessage'] = 'Please enter your full name.';
}
if(!isEmail($clientEmail)) {
$array['emailMessage'] = 'Please insert a valid email address.';
}
if($number == '') {
$array['numberMessage'] = 'Please enter a valid contact number.';
}
if($message == '') {
$array['messageMessage'] = 'Please enter your message.';
}
if($clientName != '' && isEmail($clientEmail) && $message != '') {
// Send email
$headers = "From: " . $clientName . ' <' . $clientEmail . '>' . "\r\n";
$headers .= PHP_EOL;
$headers .= "MIME-Version: 1.0".PHP_EOL;
$headers .= "Content-Type: multipart/mixed;".PHP_EOL;
$headers .= " boundary=\"boundary_sdfsfsdfs345345sfsgs\"";
mail($emailTo, $subject, $sendMessage, $headers);
}
echo json_encode($array);
} else {
header ('location: index.html#contact');
}
?>
and here is the jQuery:
// Contact form
$('.contact-form form').submit(function(e) {
e.preventDefault();
var form = $(this);
var nameLabel = form.find('label[for="contact-name"]');
var emailLabel = form.find('label[for="contact-email"]');
var numberLabel = form.find('label[for="contact-number"]');
var messageLabel = form.find('label[for="contact-message"]');
nameLabel.html('Full name');
emailLabel.html('Email');
numberLabel.html('Contact number');
messageLabel.html('Message');
var postdata = form.serialize();
$.ajax({
type: 'POST',
url: 'sendmail.php',
data: postdata,
dataType: 'json',
success: function(json) {
if(json.nameMessage !== '') {
nameLabel.append(' - <span class="red error-label"> ' + json.nameMessage + '</span>');
}
if(json.emailMessage !== '') {
emailLabel.append(' - <span class="red error-label"> ' + json.emailMessage + '</span>');
}
if(json.numberMessage !== '') {
numberLabel.append(' - <span class="red error-label"> ' + json.numberMessage + '</span>');
}
if(json.messageMessage !== '') {
messageLabel.append(' - <span class="red error-label"> ' + json.messageMessage + '</span>');
}
if(json.nameMessage === '' && json.emailMessage === '' && json.numberMessage === '' && json.messageMessage === '') {
form.fadeOut('fast', function() {
form.parent('.contact-form').append('<h2 class="text-center"><span class="orange">Thanks for contacting us!</span> We will get back to you very soon.</h2>');
});
}
}
});
});
do an ajax .done() after your ajax call to replace the button back
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;
}
?>
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);