Not getting a response from php in ajax handleResponse - javascript

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;
}
?>

Related

If I click on Tab, it doesn't response. Why?

Problem is I cannot click the Tabs on the website and If i click on Tabs; it show
Uncaught Type Error: Cannot set properties of null (setting 'value').
Is there any way to fix this? Also, I am a beginner and I don't know how to fix this. Codes are written in PHP and Javascript.
<?php
// session_start();
require("checklogin.php");
$toolsname = "Matrix Setup";
$toolsnamepath = "index.php";
$userlogin = $loginname;
$usrgroup = $_SESSION["usrgrp"];
$str_tab = isset($_POST["str_tab"])? $_POST["str_tab"] : "";
$winwidth = isset($_POST["winwidth"])? $_POST["winwidth"] : "";
$ch = isset($_POST["ch"])? $_POST["ch"] : "";
$badgeno = isset($_SESSION["badgeno"])? $_SESSION["badgeno"] : "";
if($str_tab == ""){
$str_tab = isset($_GET["str_tab"])? $_GET["str_tab"] : "";
}
if($winwidth == ""){
$winwidth = isset($_GET["winwidth"])? $_GET["winwidth"] : "";
}
if($ch == ""){
$ch = isset($_GET["ch"])? $_GET["ch"] : "";
}
echo "<html>";
echo "<head><title>$toolsname</title>";
echo "<meta http-equiv=\"X-UA-Compatible\" content=\"IE=5\">";
echo "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">";
echo "<link rel=\"stylesheet\" type=\"text/css\" href=\"\web/css/lotmgt_edge.css\"/>";
echo "<script src=\"lotmgt.js\"></script>\n";
echo "<script src=\"setup/setup.js\"></script>\n";
echo "<script src=\"productmatrix/productmatrix.js\"></script>\n";
echo "<script src=\"simulator/simulator.js\"></script>\n";
echo "<script src=\"addmatrix/addmatrix.js\"></script>\n";
echo "<script src=\"addAVImatrix/addmatrix.js\"></script>\n";
echo "<script src=\"\web/js/eregister/pointer.js\" type=\"text/javascript\"></script>";
echo "</head>";
echo "<body onload=OnLoad('" . $ch . "','" . $badgeno . "')>";
//include($_SERVER['DOCUMENT_ROOT']."\library\common\apewsheader.php");
//include($_SERVER['DOCUMENT_ROOT']."\library\common\db_config.inc");
//include($_SERVER['DOCUMENT_ROOT']."\library\common\standard_defines.inc");
include("//sgewsnant21.amk.st.com/ewsweb/wwwroot/library/common7/apewsheader.php");
include("//sgewsnant21.amk.st.com/ewsweb/wwwroot/library/common7/db_config.inc");
include("//sgewsnant21.amk.st.com/ewsweb/wwwroot/library/common7/standard_defines.inc");
include("editme.php");
echo "<form name=\"lotmgt\" method=\"post\" target=\"_self\" onsubmit=\"return false;\">";
echo "<div style=\"position:relative; top:20px;\">";
echo "<table cellpadding=\"3\" cellspacing=\"0\" border=\"0\" width=\"99%\">";
echo "<tr>";
echo "<td>";
for($c=0;$c<count($ary_tab);$c++) {
$class_tab = (($ch=="ProductMatrix" && $ary_tab[$c]=="Product Matrix" && (!isset($str_tab) || $tr_tab=="")) || ($ch=="SocketSimulator" && $ary_tab[$c]=="Socket Simulator" && (!isset($str_tab) || $str_tab=="")) || ($ch=="AVIMatrixAdd" && $ary_tab[$c]=="AVI Matrix Add" && (!isset($str_tab) || $str_tab=="")) || ($ch=="SetupPostTest" && $ary_tab[$c]=="Setup PostTest" && (!isset($str_tab) || $str_tab=="")) || ($ch=="Setup" && $ary_tab[$c]=="Setup" && (!isset($str_tab) || $str_tab=="")) || (($c==0 && !isset($str_tab)) && $ch=="") || $ary_tab[$c] == $str_tab)? "link_tab_slct" : "link_tab";
echo "" . $ary_tab[$c] . "";
}
echo"</td>";
echo"</tr>";
echo"</table>";
echo "</div>";
//echo $str_tab;
if($str_tab != ""){
switch($str_tab){
case "Setup":
include("setup/setup.php");
break;
case "Setup PostTest":
include("setup/setup.php");
break;
case "Setup1":
include("setup1/setup.php");
break;
case "Product Matrix":
include("productmatrix/productmatrix.php");
break;
case "Socket Simulator":
// include("simulator/simulator.php");
include("simulator/Socket_simulator.php");
break;
// case "Matrix Add":
// include("addmatrix/addmatrix.php");
// break;
case "AVI Matrix Add":
include("addAVImatrix/addmatrix.php");
break;
}
}
else {
if ($ch=="ProductMatrix") {
include("productmatrix/productmatrix.php");
}
else if($ch=="SocketSimulator"){
// include("simulator/simulator.php");
include("simulator/Socket_simulator.php");
}
else if($ch=="AVIMatrixAdd"){
include("addAVImatrix/addmatrix.php");
}
else if($ch=="Setup"){
include("setup/setup.php");
}
else if($ch=="SetupPost6E"){
include("setup/setup.php");
}
else{
include("setup/setup.php");
}
}
//common
echo "<input type=\"hidden\" name=\"str_tab\" value=\"" . $str_tab . "\">";
echo "<input type=\"hidden\" name=\"winwidth\" value=\"" . $winwidth . "\">";
echo "<input type=\"hidden\" name=\"username\" value=\"" . $loginname . "\">";
echo "</form>";
flush();
mysqli_close($conn);
echo "</body>";
echo "</html>";
?>
Above codes are index.php codes.
var winplanproducttoentity = '';
var winupdateauto = '';
var winupdatebytester = '';
var winupdatebyproduct = '';
var winupdatestatus = '';
var wintestlot = '';
var winassignlot = '';
var winshowlot = ''
var winchecksicom = '';
var w;
var winwidth = window.screen.width;
var div = new Array('outputdiv','setupdiv');
//var div = new Array('outputdiv','setupdiv','availdiv');
var reqHttp = InitRequest();
var reqHttp1 = InitRequest();
var reqHttp2 = InitRequest();
var reqHttp3 = InitRequest();
function InitRequest() {
var request=null;
try {
request=new XMLHttpRequest();
}
catch (e) {
try {
request=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e){
request=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return request;
}
function AsynReqData(request,url,fn) {
request.open("GET", url + '&sid=' + Date() + Math.random(), true);
request.onreadystatechange = eval(fn);
request.send(null);
}
function SynReqData(request,url) {
request.open("GET", url + '&sid=' + Date() + Math.random(), false);
request.send(null);
return request.responseText;
}
function DisplayTab(tabname,tabid) {
document.getElementById(tabid).value = tabname; // this is the $str_tab
document.lotmgt.submit();
}
function OnLoad(ch,badgeno){
var tab = document.lotmgt.str_tab.value; // this is the $str_tab from DisplayTab function
w = (winwidth < 1280)? 1280 : winwidth;
if((tab=='' & ch=='') || tab=='Setup' || (ch=='Setup' & tab=='')) {
var p_1 = "checked";
var T_0 = "checked";
var zmiss = "checked";
for(var i=0; i<div.length; i++) {
document.getElementById(div[i]).className = 'hide';
}
// var wd = (128*5) - 10;
var wd = (128*7.5) - 50;
var lf = 0;
document.getElementById('filterdiv').style.width = wd + 'px';
document.getElementById('filterdiv').style.left = lf + 'px';
wd = (128*5.5) - 80;
lf = (128*5) - 10; // lf = (128*7) - 20;
document.getElementById('waferdiv').style.width = wd + 'px';
document.getElementById('waferdiv').style.left = lf + 'px';
// AsynReqData(reqHttp,'setup/content_wafer.php?site=','UpdateWafer');
AsynReqData(reqHttp1,'setup/content_filter.php?site=' + '' + '&badgeno=' + badgeno + '&p_1=' + p_1 + '&T_0=' + T_0 + '&zmiss=' + zmiss,'UpdateFilter');
}
else if (tab=='Product Matrix' || (ch=='ProductMatrix' & tab=='')){
AsynReqData(reqHttp,'productmatrix/content_filter.php?area=','UpdatePMFilter');
}
// else if (tab=='Matrix Simulator' || (ch=='MatrixSimulator' & tab=='')){
// // AsynReqData(reqHttp,'simulator/content_filter.php?area=','UpdateSIMFilter');
// }
else if (tab=='Setup PostTest' || (ch=='SetupPostTest' & tab=='')){
var p_1 = "checked";
var T_0 = "checked";
var wd = (128*9) - 50;
var lf = 0;
document.getElementById('filterdiv').style.width = wd + 'px';
document.getElementById('filterdiv').style.left = lf + 'px';
AsynReqData(reqHttp1,'setup/content_filter1.php?site=' + '' + '&badgeno=' + badgeno + '&p_1=' + p_1 + '&T_0=' + T_0,'UpdateFilter');
}
}
//shared functions
function ManagePopup(except){
var mywin = new Array('winplanproducttoentity','winupdateauto','winupdatebytester','winupdatebyproduct','winupdatestatus','wintestlot','winassignlot','winshowlot','winchecksicom');
for(var i=0; i<mywin.length; i++) {
var win = window[mywin[i]];
if (mywin[i] == except){
if(!win.closed && win.location) win.focus();
}
else{
if(!win.closed && win.location) win.close();
}
}
}
function PlanProductToEntity(product,type){
var w = 300;
var h = 600;
var winl = (screen.width - w) / 2;
var wint = (screen.height - h) / 2;
var winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,copyhistory=no';
ManagePopup('winplanproducttoentity');
winplanproducttoentity = this.open('../lotmgt/wip/pop_assignproduct.php?product=' + product + '&type=' + type, 'winplanproducttoentity', winprops);
}
Above codes are Javascript codes. Error says in Javascript and How to fix that?
The error occurs in the JS code and is due to the HTML generated in PHP which is missing an id attribute.
You seem to get the error here: document.getElementById(tabid).value = tabname; because document.getElementById(tabid) is null.
When it looks for the element with id str_tab it doesn't find it. The only element in the HTML which could be the desired one has the attribute name="str_tab" and it's your hidden field. You have to add the missing id="str_tab" attribute to this hidden field.

problems with htmlrows javascript

I'm trying to make htmlRows to work. When I select productcode I want to trigger func Choise() and fill price and name.
<script>
// get Product Code
<?php
$connect = new PDO("mysql:host=localhost;dbname=praktika", "root", "");
function fill_productCode($connect)
{
$output = '';
$query = "SELECT * FROM services";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
foreach ($result as $row) {
$output .= '<option value="' . $row["code"] . '">' . $row["code"] . '</option>';
}
return $output;
}
?>
var count = $(".itemRow").length;
$(document).on('click', '#addRows', function() {
count++;
var htmlRows = '';
htmlRows += '<tr>';
htmlRows += '<td><input class="itemRow" type="checkbox"></td>';
htmlRows += '<td><select id="selectUsers" onChange="Choice();" type="text" name="productCode[]" class="form-control" autocomplete="off"><option value="">Select</option><?php echo fill_productCode($connect); ?></select></td>';
// htmlRows += '<td><input type="text" id="serviceName" name="productName[]" class="form-control" autocomplete="off"></td>';
htmlRows += '<td><input type="text" id="productName_' + count + '" name="productName[]" class="form-control" autocomplete="off"></td>';
htmlRows += '<td><input type="number" name="quantity[]" id="quantity_' + count + '" class="form-control quantity" autocomplete="off"></td>';
htmlRows += '<td><input type="number" name="price[]" id="price_' + count + '" class="form-control price" autocomplete="off"></td>';
htmlRows += '<td><input type="number" name="total[]" id="total_' + count + '" class="form-control total" autocomplete="off"></td>';
htmlRows += '</tr>';
$('#invoiceItem').append(htmlRows);
});
var serviceName = new Array();
var price_1 = new Array();
var ful = new Array();
serviceName[0] = "";
price_1[0] = "";
ful[0] = "";
serviceName[1] = "Serverių instaliavimas";
price_1[1] = "544.99";
ful[1] = "Buddy Smith";
serviceName[2] = "Sąskaitų skaitmenizavimas";
price_1[2] = "111";
ful[2] = "Libbie Smith";
serviceName[3] = 4;
price_1[3] = "asmith";
ful[3] = "Andy Smith";
function Choice() {
//x = document.getElementById("users");
y = document.getElementById("selectUsers");
//x.value = y.options[y.selectedIndex].text;
document.getElementById("serviceName").value = serviceName[y.selectedIndex];
document.getElementById("price_1").value = price_1[y.selectedIndex];
document.getElementById("ful").value = ful[y.selectedIndex];
}
</script>
As mentioned in the comment, it is best to move PHP script to their own page.
PHP - getServices.php
<?php
$connect = new PDO("mysql:host=localhost;dbname=praktika", "root", "");
$statement = $connect->prepare("SELECT * FROM services");
$statement->execute();
$result = $statement->fetchAll();
$output = "";
foreach ($result as $row) {
$output .= '<option value="' . $row["code"] . '">' . $row["code"] . '</option>' . "\r\n";
}
echo $output;
?>
You can then GET this via AJAX when needed.
$.get("getServices.php", function(h){
$("#selectUsers").html(h);
});
This would make a GET Request and the PHP would output the HTML back to the request.
It would be better to set this more like an API. Where a GET request can get JSON data back and then manipulate as needed with jQuery.
jQuery
$(function() {
function getData(page) {
var results;
$.getJSON(page, function(data) {
results = data;
});
return results;
}
function addRow(tObj) {
var c = $("tbody tr", tObj).length;
var newRow = $("<tr>");
$("<td>").appendTo(newRow); // 0
$("<input>", {
class: "itemRow",
type: "checkbox"
}).appendTo($("td", newRow));
$("<td>").appendTo(newRow); // 1
var sUser = $("<select>", {
id: "selectUsers",
name: "productCode[]",
class: "form-control",
autocomplete: "off"
}).appendTo($("td", newRow).eq(1));
$("<option>").html("Select User").appendTo(sUser);
// Populate User Options
$.each(getData("getUsers.php"), function(i, u) {
$("<option>", {
value: u.code
}).html(u.name).appendTo(sUser);
});
$("<td>").appendTo(newRow); // 2
$("<input>", {
type: "text",
id: "productName_" + (c + 1),
name: "productName[]",
class: "form-control",
autofill: "off"
}).appendTo($("td", newRow).eq(2));
$("<td>").appendTo(newRow); // 3
$("<input>", {
type: "number",
id: "quantity_" + (c + 1),
name: "quantity[]",
class: "form-control quantity",
autofill: "off"
}).appendTo($("td", newRow).eq(3));
$("<td>").appendTo(newRow); // 4
$("<input>", {
type: "number",
id: "price_" + (c + 1),
name: "price[]",
class: "form-control price",
autofill: "off"
}).appendTo($("td", newRow).eq(4));
$("<td>").appendTo(newRow); // 5
$("<input>", {
type: "number",
id: "total_" + (c + 1),
name: "total[]",
class: "form-control total",
autofill: "off"
}).appendTo($("td", newRow).eq(5));
tObj.append(newRow);
}
$(document).on('click', '#addRows', function() {
addRow($("#invoiceItem"));
});
});
This would be potential PHP code:
PHP - getUsers.php
<?php
$connect = new PDO("mysql:host=localhost;dbname=praktika", "root", "");
$statement = $connect->prepare("SELECT * FROM users");
$statement->execute();
$result = $statement->fetchAll();
$output = array();
foreach ($result as $row) {
array_push($output, $row);
}
header('Content-Type: application/json');
echo json_encode($output);
$statement = null;
$connect = null;
?>

variables not being read in if statement in php

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.

how to handle scroll up and scroll down with ajax request?

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);

How get the textbox values in array.....to store in database

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

Categories

Resources