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);
Related
<script> //script loading the csv and reading the files to out into an array of variables which are used in dropdown
var $csvData = [],
$colNames = [];
function _ReadCSV($a) {
var $f = $a.files[0];
if($f) {
var reader = new FileReader();
reader.onerror = function($e) {
div.innerHTML = 'The file can\'t be read! Error ' + $e.target.error.code;
}
reader.onload = function($e) {
var $data = $e.target.result.split("\n");
$colNames = $data[0].split(","); //split to separate the column inside the csv
$data.splice(0, 1);
for(var $b = 0; $b < $data.length; $b++) {
var $tmpJSON = {},
$colData = $data[$b].split(",");
for(var $c = 0; $c < $colData.length; $c++) $tmpJSON[$colNames[$c]] = $colData[$c];
$csvData.push($tmpJSON);
document.getElementById("try").innerHTML = "Value: "+ $colData; //just to check the value
}
_CreateDropdown();
}
reader.readAsText($f);
}
}
function _CreateDropdown() {
var $tmpHTML = '<select onchange="_UpdateFields(this.value)">';
for(var $a = 0; $a < $csvData.length; $a++) $tmpHTML += '<option value="' + $a + '">' + $csvData[$a][$colNames[0]] + '</option>';
$tmpHTML += '</select>';
document.getElementById("dropdown").innerHTML = $tmpHTML;
_UpdateFields(0);
}
function _UpdateFields($a) {
var $values = '';
for(var $b = 0; $b < $colNames.length; $b++) {
console.log($colNames[$b], $csvData[$a][$colNames[$b]]);
if($csvData[$a][$colNames[$b]] != "") $values += $colNames[$b] + ': <input id="' + $colNames[$b] + '" name="' + $colNames[$b] + '" type="text" value="' + $csvData[$a][$colNames[$b]] + '" /><br />';
}
document.getElementById("fields").innerHTML = $values;
}
window.onload = function() {
document.getElementById('fileBox').onchange = function(){ _ReadCSV(this); }
}
</script>
Currently I have two columns in csv and need to pick the value of one of the column item. Which is selected upon the dropdown selected by the user and then need to modify the value. The $values variable stores both the columns values.
I'm trying to make node counter by id, node name, and attribute name&value!
Here I would like to check if every is empty then show "HERE IS NO VALUE OF YOU ENTERED".
here in the end of I try to use <&&> but it doesn't work!
also is that impossible to use just tag instead of in the end of the code? when i tried, it show eror :(
** I have no idea of how to count attribute name&value number..**
I'm realy begginer of javascript ! thank you in advance guys!!
this is my form html.
function javascript_click() {
/* 자바스크립트 id값 찾기 */
if (document.getElementById("value1").value) {
var val = document.getElementById("value1").value;
if (document.getElementById(val)) {
//var myNodelist = document.getElementById("val").value;
document.getElementById("cnt").innerHTML += "선택하신아이디는 " + val + " 이며 id갯수는 1개입니다.By javascript <br>";
} else {
document.getElementById("cnt").innerHTML += "wrong value of ID <br>";
}
}
/* 자바스크립트 노드명 찾기 */
else if (document.getElementById("value2").value) {
var val2 = document.getElementById("value2").value;
if (document.querySelector(val2)) {
// alert(val2);
var myNodelist = document.querySelectorAll(val2);
document.getElementById("cnt").innerHTML += "선택하신 노드는 " + val2 + " 이며 노드갯수는 " + myNodelist.length + "개 입니다. By javascript<br>";
} else {
document.getElementById("cnt").innerHTML += "wrong value of ID <br>";
}
}
/* 자바스크립트 attribute 찾기 */
/* 자바스크립트 속성명&값 찾기 */
else if (
document.getElementById("value3").value &&
document.getElementById("value4").value
) {
var val2 = document.getElementById("value2").value;
if (document.querySelector(val2)) {
// alert(val2);
var myNodelist = document.querySelectorAll(val2);
document.getElementById("cnt").innerHTML += "선택하신 노드는 " + val2 + " 이며 노드갯수는 " + myNodelist.length + "개 입니다. By javascript<br>";
} else {
document.getElementById("cnt").innerHTML += "wrong value of ID <br>";
}
} else if (
(document.getElementById("value1").value &&
document.getElementById("value2").value &&
document.getElementById("value3").value &&
document.getElementById("value4").value) == 0
) {
document.getElementById("cnt").innerHTML += "THERE IS NO VALUE OF YOU ENTERED<br>";
}
}
<form action="">
<table class="tg" id="tg">
<tr>
<td>id</td>
<td><input type="text" id="value1"></td>
</tr>
<tr>
<td>node name</td>
<td><input type="text" id="value2"></td>
</tr>
<tr>
<td>attribute</td>
<td><input type="text" id="value3"></td>
</tr>
<tr>
<td>attribute</td>
<td><input type="text" id="value3"></td>
</tr>
</table>
<div id="cnt"></div>
</form>
<div class="button">
<button id='btn_javascript' onclick="javascript_click();">자바스크립트</button>
</div>
You may do validation like this:
if (document.getElementById("value1").value!=='') {
let val1 = document.getElementById("value1").value;
document.getElementById("cnt").innerHTML += "선택하신아이디는 " + val1 + " 이며 id갯수는 1개입니다.By javascript <br>";
} else {
document.getElementById("cnt").innerHTML += "wrong value of ID <br>";
}
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'm working on an old project that wasn't developed by me at first. I need to make an Ajax request so that the values contained in the fields (more on that later) be sent to a php script which will then return their values into the correct td.
Here is the JavaScript/jQuery code.
$(function ()
{
$('form').on('submit', function (e)
{
e.preventDefault();
$.ajax
({
type: 'post',
url: 'envoi_dispo_semaine.php',
data: $('form').serialize(),
success: function ()
{
alert('Le planning a été mis à jour.');
}
});
});
jQuery(document).ready(function date()
{
Date.prototype.getWeek = function() {
var onejan = new Date(this.getFullYear(),0,1);
var today = new Date(this.getFullYear(),this.getMonth(),this.getDate());
var dayOfYear = ((today - onejan +1)/86400000);
return Math.ceil(dayOfYear/7)
};
var today = new Date();
var t = today.getWeek();
})
jQuery(document).ready(function()
{
jDispo = {};
jCharge = {};
jSolde = {};
var d = 0;
var c = 0;
var s = 0;
jQuery('.DISPO').each(function()
{
jDispo[d] = jQuery(this).val();
d++;
});
jQuery(".CHARGE").change(function()
{
var totalCharge = 0;
if(jQuery(".CHARGE").length > 0)
{
jQuery(".CHARGE").each(function()
{
jCharge[c] = jQuery(this).val();
c++;
totalCharge = totalCharge + jQuery(this).val();
});
}
jQuery('.SOLDE').each(function()
{
jSolde[s] = jQuery(this).val();
$.ajax(
{
type:'post',
url:'check_charge.php',
data:{charge : jCharge[s],solde : jSolde[s],dispo : jDispo[s],action:"update_site"},
success: function()
{
$('jSolde[s]').empty();
$('jSolde[s]').append();
$('.ajax').html($('.ajax input').val());
$('.ajax').removeClass('ajax');
}
});
s++;
});
});
});
$(document).ready(function()
{
if ($("#tab_projets table tbody tr:eq(2) td:contains('-')").length)
{
$("#tab_projets table tbody tr:eq(2) td:contains('-')").css('background', '#CCFF00');
$("#tab_projets table tbody tr:eq(2) td:contains('-')").css('font-color', 'black');
}
if ($("#tab_projets table tbody tr:eq(5) td:contains('-')").length)
{
$("#tab_projets table tbody tr:eq(5) td:contains('-')").css('background', '#CCFF00');
$("#tab_projets table tbody tr:eq(5) td:contains('-')").css('font-color', 'black');
}
if ($("#tab_projets table tbody tr:eq(8) td:contains('-')").length)
{
$("#tab_projets table tbody tr:eq(8) td:contains('-')").css('background', '#CCFF00');
$("#tab_projets table tbody tr:eq(8) td:contains('-')").css('font-color', 'black');
}
});
});
And here is check_charges.php:
<?php
include('connexion_db.php');
$charge = $_POST['charge'];
$dispo = $_POST['dispo'];
$solde = $_POST['solde']; //I'll need this one later on.
$res = $dispo - $charge;
echo $res;
?>
I also have some php code that allows me to generate a table (it's in the same file as the javascript):
<thead>
<?php
echo " <td colspan=2>Semaine n°</td>
<td>Retard</td>";
for ($i=$numerosemaine; $i <= $numerosemaine + $longueurAff; $i++)
{
echo "<form action=\"envoi_dispo_semaine.php\" method=\"post\">
<td>
<input type=\"hidden\" name=\"semaine_id\" value=\"".$i."\" />".$i."</td>";
}
?>
</thead>
<tbody>
<?php
foreach($users as &$myUser)
{
echo " <tr class=".$myUser.">
<td width=66% rowspan=3><input type=\"hidden\" name=\"login\" value=\"".$myUser."\" onblur=\"updateCharge\"/>".$myUser."</td>
<td width=34%>Disponibilité</td>
<td rowspan=3></td>
";
for ($i=$numerosemaine; $i <= $numerosemaine + $longueurAff; $i++)
{
$req = "
SELECT Nb_max_jours FROM Dispo_par_semaine WHERE login = '".$myUser."' AND semaine_id = ".$i;
$query = requete_is_plancharges($req);
$row = mysql_fetch_row($query);
$affichageDispo = $row[0];
if ($affichageDispo == "")
{
$affichageDispo = 3;
}
echo "
<td>
<input class=\"DISPO\" type=\"number\" name=\"disponibilite[]\" value=".$affichageDispo." min=\"0\" max=\"5\" step=\"0.5\" class=\"input\"/>
</td>
";
}
echo"
</tr>
<tr class=".$myUser.">
<td width=34%>Charge</td>";
for ($i=$numerosemaine; $i <= $numerosemaine + $longueurAff; $i++)
{
$reqTache = "
SELECT tache_id
FROM Tache
WHERE ebi_id = ".$ebi."
AND demande_id = ".$demande."
AND action_id = ".$action;
$resultatTache_id = requete_is_plancharges($reqTache);
$maTache = mysql_fetch_object($resultatTache_id);
$req_Charge = "
SELECT COUNT(charge) as charge_tache
FROM Charge_par_tache
WHERE tache_id =".$maTache->tache_id.
" AND semaine_id =".$i.
" AND login = '".$myUser."'";
$resultat_requete_Charge = mysql_fetch_object(requete_is_plancharges($req_Charge));
if ($resultat_requete_Charge->charge_tache > 0)
{
$req = "
SELECT Charge_par_tache.charge
FROM Charge_par_tache, Tache
WHERE Charge_par_tache.tache_id = Tache.tache_id
AND Tache.ebi_id = ".$ebi."
AND Tache.demande_id = ".$demande."
AND Tache.action_id = ".$action."
AND Charge_par_tache.login = '".$myUser."'
AND Charge_par_tache.semaine_id = ".$i;
$Charge = mysql_fetch_object(requete_is_plancharges($req));
} else
{
$Charge->charge = "";
}
echo " <input type = \"hidden\" name = \"tache_id\" value=".$maTache->tache_id.">
<td class=\"CHARGE\">";
$query = requete_is_plancharges($req);
$row = mysql_fetch_array($query);
$affichageCharge = $row[0];
echo " <input class=\"CHARGE\" type=\"number\" name=\"charge[]\" value=".$Charge->charge." min=\"0\" step=\"0.5\"/>
</td>";
}
echo"
</tr>
<tr class=".$myUser.">
<td width=34%>Solde</td>";
for ($i=$numerosemaine; $i <= $numerosemaine + $longueurAff; $i++)
{
$req1 = "
SELECT charge FROM Charge_par_tache WHERE login = '".$myUser."' AND semaine_id = ".$i;
$req2 = "
SELECT Nb_max_jours FROM Dispo_par_semaine WHERE login = '".$myUser."' AND semaine_id = ".$i;
$query1 = requete_is_plancharges($req1);
$row1 = mysql_fetch_row($query1);
$query2 = requete_is_plancharges($req2);
$row2 = mysql_fetch_row($query2);
$solde=$row2[0]-$row1[0];
echo "<td class=\"SOLDE\"><input type=\"hidden\" class=\"SOLDE\" value=".$solde."/> ".$solde."</td>";
}
?>
</tr>
<?php
}
?>
</tbody>
</table>
<p><input type="submit" name="submit" value="Mise à jour"></p>
</form>
The problem is that I can't seem to retrieve $res. I'm just starting Ajax so I really don't know what to do, and couldn't find the answer on the Internet as I use a js array to store my values.
If I understand your problem you want to get the response value of "check_charges.php", that it is the $res value, isn't it? The value will be returned in the first parameter of success function of your ajax.
Your code:
jQuery('.SOLDE').each(function()
{
jSolde[s] = jQuery(this).val();
$.ajax(
{
type:'post',
url:'check_charge.php',
data:{charge : jCharge[s],solde : jSolde[s],dispo : jDispo[s],action:"update_site"},
success: function(data)
{
// Store where you want the data value
alert('res value: ' + data);
$('jSolde[s]').empty();
$('jSolde[s]').append();
$('.ajax').html($('.ajax input').val());
$('.ajax').removeClass('ajax');
}
});
s++;
});
I hope I have helped you.
Been pulling my hair out since the past 4 hours. I have two Javascript file, both works completely fine by itself. One is use as a login verification, the other takes my registration page and writes the form to an XML file.
When I took some code from my login JS and place it in my registration JS, my registration JS doesn't even function properly. I'm thinking my issue is probably the placement of my codes.
If I post the complete codes here, the post would be like 10ft long, so here's all my files:
http://www.mediafire.com/?wt9bchq35pdqxgf
By the way, this is not a real world application, it's just something I'm doing.
Here's my original Javascript file for the registration page:
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
var fso = new ActiveXObject("Scripting.FileSystemObject");
var FILENAME = 'C:\\Users\\Wilson Wong\\Desktop\\Copy of Take Home Exam - Copy\\PersonXML2.xml';
function SaveXML(UserData)
{
var file = fso.CreateTextFile(FILENAME, true);
file.WriteLine('<?xml version="1.0" encoding="utf-8"?>\n');
file.WriteLine('<PersonInfo>\n');
for (countr = 0; countr < UserData.length; countr++)
{
file.Write(' <Person ');
file.Write('Usrname="' + UserData[countr][0] + '" ');
file.Write('Pswd="' + UserData[countr][1] + '" ');
file.Write('PersonID="' + UserData[countr][2] + '" ');
file.Write('FirstName="' + UserData[countr][3] + '" ');
file.Write('LastName="' + UserData[countr][4] + '" ');
file.Write('Gender="' + UserData[countr][5] + '" ');
file.Write('DOB="' + UserData[countr][6] + '" ');
file.Write('Title="' + UserData[countr][7] + '" ');
file.WriteLine('></Person>\n');
} // end for countr
//file.WriteLine('></Person>\n');
var usrn = document.getElementById("Usrn").value;
var pswd = document.getElementById("Pswd").value;
var pid = document.getElementById("PersonID").value;
var fname = document.getElementById("FirstName").value;
var lname = document.getElementById("LastName").value;
var gender = document.getElementById("Gender").value;
var dob = document.getElementById("DOB").value;
var title = document.getElementById("Title").value;
file.Write(' <Person ');
file.Write('Usrname="' + usrn + '" ');
file.Write('Pswd="' + pswd + '" ');
file.Write('PersonID="' + pid + '" ');
file.Write('FirstName="' + fname + '" ');
file.Write('LastName="' + lname + '" ');
file.Write('Gender="' + gender + '" ');
file.Write('DOB="' + dob + '" ');
file.Write('Title="' + title + '" ');
file.WriteLine('></Person>\n');
file.WriteLine('</PersonInfo>\n');
file.Close();
} // end SaveXML function --------------------
function LoadXML(xmlFile)
{
xmlDoc.load(xmlFile);
return xmlDoc.documentElement;
} //end function LoadXML()
function initialize_array()
{
var person = new Array();
var noFile = true;
var xmlObj;
if (fso.FileExists(FILENAME))
{
xmlObj = LoadXML(FILENAME);
noFile = false;
} // if
else
{
xmlObj = LoadXML("PersonXML.xml");
//alert("local" + xmlObj);
} // end if
var usrCount = 0;
while (usrCount < xmlObj.childNodes.length)
{
var tmpUsrs = new Array(xmlObj.childNodes(usrCount).getAttribute("Usrname"),
xmlObj.childNodes(usrCount).getAttribute("Pswd"),
xmlObj.childNodes(usrCount).getAttribute("PersonID"),
xmlObj.childNodes(usrCount).getAttribute("FirstName"),
xmlObj.childNodes(usrCount).getAttribute("LastName"),
xmlObj.childNodes(usrCount).getAttribute("Gender"),
xmlObj.childNodes(usrCount).getAttribute("DOB"),
xmlObj.childNodes(usrCount).getAttribute("Title"));
person.push(tmpUsrs);
usrCount++;
} //end while
if (noFile == false)
fso.DeleteFile(FILENAME);
SaveXML(person);
} // end function initialize_array()
This code here will write to my XML file after I hit the submit button. And this is how the XML looks like:
<?xml version="1.0" encoding="utf-8"?>
<PersonInfo>
<Person Usrname="Bob111" Pswd="Smith111" PersonID="111" FirstName="Bob" LastName="Smith" Gender="M" DOB="01/01/1960" Title="Hello1" ></Person>
<Person Usrname="Joe222" Pswd="Johnson222" PersonID="222" FirstName="Joe" LastName="Johnson" Gender="M" DOB="12/01/1980" Title="Hello2" ></Person>
<Person Usrname="Tracey333" Pswd="Wilson333" PersonID="333" FirstName="Tracey" LastName="Wilson" Gender="F" DOB="12/01/1985" Title="Hello3" ></Person>
<Person Usrname="Connie444" Pswd="Yuiy444" PersonID="444" FirstName="Connie" LastName="Yuiy" Gender="F" DOB="12/01/1985" Title="Hello4" ></Person>
<Person Usrname="Brian555" Pswd="Dame555" PersonID="555" FirstName="Brian" LastName="Dame" Gender="M" DOB="12/01/1985" Title="Hello5" ></Person>
<Person Usrname="Scott666" Pswd="Bikes666" PersonID="666" FirstName="Scott" LastName="Bikes" Gender="MF" DOB="12/01/1985" Title="Hello6" ></Person>
<Person Usrname="sadsa" Pswd="s" PersonID="s" FirstName="s" LastName="s" Gender="s" DOB="s" Title="s" ></Person>
If I modify my code to what is shown below, the XML file won't even create. Nor will the authentication run properly. As in the the box won't turn red and no alert message pops up. But the codes I add in does work on my other JS file for my log in page.
Here's the edited registration JS:
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
var fso = new ActiveXObject("Scripting.FileSystemObject");
var FILENAME = 'C:\\Users\\Wilson Wong\\Desktop\\Copy of Take Home Exam - Copy\\PersonXML2.xml';
function SaveXML(UserData)
{
var file = fso.CreateTextFile(FILENAME, true);
file.WriteLine('<?xml version="1.0" encoding="utf-8"?>\n');
file.WriteLine('<PersonInfo>\n');
for (countr = 0; countr < UserData.length; countr++)
{
file.Write(' <Person ');
file.Write('Usrname="' + UserData[countr][0] + '" ');
file.Write('Pswd="' + UserData[countr][1] + '" ');
file.Write('PersonID="' + UserData[countr][2] + '" ');
file.Write('FirstName="' + UserData[countr][3] + '" ');
file.Write('LastName="' + UserData[countr][4] + '" ');
file.Write('Gender="' + UserData[countr][5] + '" ');
file.Write('DOB="' + UserData[countr][6] + '" ');
file.Write('Title="' + UserData[countr][7] + '" ');
file.WriteLine('></Person>\n');
} // end for countr
var usrn = document.getElementById("Usrn").value;
var pswd = document.getElementById("Pswd").value;
var pid = document.getElementById("PersonID").value;
var fname = document.getElementById("FirstName").value;
var lname = document.getElementById("LastName").value;
var gender = document.getElementById("Gender").value;
var dob = document.getElementById("DOB").value;
var title = document.getElementById("Title").value;
var errmsg = "empty field";
var errmsg2 = "You have register successfully";
var msg = "This user name is already in use"; //this is what I added
var errCount = 0;
errCount += LogInVal(usrn);
errCount += LogInVal(pswd);
errCount += LogInVal(pid);
errCount += LogInVal(fname);
errCount += LogInVal(lname); //this is what I added
errCount += LogInVal(gender);
errCount += LogInVal(dob);
errCount += LogInVal(title);
if (errCount != 0) //the if/else statements are what I added
{
file.WriteLine('</PersonInfo>\n'); //checks to see if textbox is empty, if yes, alert
file.Close();
alert(errmsg);
return false;
}
else if(authentication(usrn) == true)
{
file.WriteLine('</PersonInfo>\n'); //checks to see if user name entered is already in use
file.Close();
alert(msg);
return false;
}
else
{
file.Write(' <Person ');
file.Write('Usrname="' + usrn + '" ');
file.Write('Pswd="' + pswd + '" ');
file.Write('PersonID="' + pid + '" ');
file.Write('FirstName="' + fname + '" ');
file.Write('LastName="' + lname + '" '); //this block of code here was there originally
file.Write('Gender="' + gender + '" ');
file.Write('DOB="' + dob + '" '); //previous two condition is false, registration successful, writes to XML.
file.Write('Title="' + title + '" ');
file.WriteLine('></Person>\n');
file.WriteLine('</PersonInfo>\n');
file.Close();
alert(errmsg2);
return true;
}
} // end SaveXML function --------------------
function authentication(usrname1) //function was added
{
for (var x = 0; x < arrPerson.length; x++)
{
if (arrPerson[x][0] == usrn)
{
return true;
}
}
return false;
}
function LogInVal(objtxt) //function was added
{
if(objtxt.value.length == 0)
{
objtxt.style.background = "red";
return 1;
}
else
{
objtxt.style.background = "white";
return 0;
}
}
function LoadXML(xmlFile)
{
xmlDoc.load(xmlFile);
return xmlDoc.documentElement;
} //end function LoadXML()
function initialize_array()
{
var person = new Array();
var noFile = true;
var xmlObj;
if (fso.FileExists(FILENAME))
{
xmlObj = LoadXML(FILENAME);
noFile = false;
} // if
else
{
xmlObj = LoadXML("PersonXML.xml");
//alert("local" + xmlObj);
} // end if
var usrCount = 0;
while (usrCount < xmlObj.childNodes.length)
{
var tmpUsrs = new Array(xmlObj.childNodes(usrCount).getAttribute("Usrname"),
xmlObj.childNodes(usrCount).getAttribute("Pswd"),
xmlObj.childNodes(usrCount).getAttribute("PersonID"),
xmlObj.childNodes(usrCount).getAttribute("FirstName"),
xmlObj.childNodes(usrCount).getAttribute("LastName"),
xmlObj.childNodes(usrCount).getAttribute("Gender"),
xmlObj.childNodes(usrCount).getAttribute("DOB"),
xmlObj.childNodes(usrCount).getAttribute("Title"));
person.push(tmpUsrs);
usrCount++;
} //end while
if (noFile == false)
fso.DeleteFile(FILENAME);
SaveXML(person);
} // end function initialize_array()
Here's the login page JS, which contains the code(it works fine in this file) that was added to the registration JS:
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
//DEFINE LOAD METHOD
function LoadXML(xmlFile)
{
xmlDoc.load(xmlFile);
xmlObj = xmlDoc.documentElement;
}
//declare & initialize array
var arrPerson = new Array();
//initialize array w/ xml
function initialize_array()
{
LoadXML("PersonXML.xml");
var x = 0;
while (x < xmlObj.childNodes.length)
{
var tmpArr = new Array(xmlObj.childNodes(x).getAttribute("Usrname"),
xmlObj.childNodes(x).getAttribute("Pswd"),
xmlObj.childNodes(x).getAttribute("FirstName"),
xmlObj.childNodes(x).getAttribute("LastName"),
xmlObj.childNodes(x).getAttribute("DOB"),
xmlObj.childNodes(x).getAttribute("Gender"),
xmlObj.childNodes(x).getAttribute("Title"));
arrPerson.push(tmpArr);
x++;
}
}
//Validation
function LogInVal(objtxt)
{
if(objtxt.value.length == 0)
{
objtxt.style.background = "red";
return 1;
}
else
{
objtxt.style.background = "white";
return 0;
}
}
//main validation
function MainVal(objForm)
{
var errmsg = "empty field";
var errmsg2 = "Incorrect Username and Password";
var msg = "You have logged in successfully";
var errCount = 0;
var usrn = document.getElementById("usrname1").value;
var pswd = document.getElementById("pswd1").value;
errCount += LogInVal(objForm.usrname);
errCount/*1*/ += LogInVal(objForm.pswd);
initialize_array();
if (errCount != 0)
{
alert(errmsg);
return false;
}
else if(authentication(usrn, pswd) == true)
{
alert(msg);
return true;
setCookie('invalidUsr',' ttttt');
}
else
{
alert(errmsg2);
return false;
}
}
function authentication(usrname1, pswd1)
{
for (var x = 0; x < arrPerson.length; x++)
{
if (arrPerson[x][0] == usrname1 && pswd1 == arrPerson[x][1])
{
return true;
}
}
return false;
}
function setCookie(Cookiename,CookieValue)
{
alert('executing setCookie');
document.cookie = Cookiename + '=' + CookieValue;
}
Here's my registration HTML page:
<html>
<!--onSubmit="SaveXML(person);"-->
<head>
<title>Registration</title>
<link rel="stylesheet" type="text/css" href="CSS_LABs.css" />
</head>
<body>
<script type="text/javaScript" src="writeXML.js"> </script>
<div class="form">
<form id="Registration" name="reg" action="" method="get" onSubmit="return initialize_array()">
Username:<input type="text" name="Usrn" id="Usrn" maxlength="10"/> <br/>
Password:<input type="password" name="Pswd" id="Pswd" maxlength="20"/> <br/>
<hr>
PersonID:<input type="text" name="PersonID" id="PersonID"/> <br>
<hr>
First Name:<input type="text" name="FirstName" id="FirstName"/> <br>
Last Name:<input type="text" name="LastName" id="LastName"/>
<hr>
DOB:<input type="text" name="DOB" id="DOB"/> <br>
<hr>
Gender:<input type="text" name="Gender" id="Gender"/> <br>
<hr>
Title:<input type="text" name="Title" id="Title"/> <br>
<hr>
<!--Secret Question:<br>
<select name="secret?">
</select> <br>
Answer:<input type="text" name="answer" /> <br> <br>-->
<input type="submit" value="submit" />
</form>
</div>
</body>
</html>
Hope I'm not being too confusing.
What I see in the code is this:
create XML file, start with <personInfo>
if error, skip </personInfo>
now add something else.
so you're not closing the XML element. Of course it won't create the file. It won't write invalid XML, and that's "expected" behavior.
You can also debug your jvascript code to enable javascript debugging. go to : tools > intenet options > advanced > browsing and uncheck (disable script debugging). in Internet Explorer Browser . then you can attach debugger by writing debugger; # any location in javascript function egs:
function SaveXML(UserData)
{
debugger;
var file = fso.CreateTextFile(FILENAME, true); file.WriteLine('\n');
file.WriteLine('\n');
.........................
}