I wrote code to display data based on month selection. Month is changing but data is not displaying according to that. See my code once and suggest what shall I do.When clicking the next its changing the month but the data in the calendar is not displaying.
<!DOCTYPE html>
<html>
<body>
<form method="post" action="display.php">
<!--<button id="prev">-->
<input type="button" id="prev" name="prev" value="prev" />
<input type="text" id="date" name="date" value=""
style="border:none;" />
<input type="button" id="next" name="next" value="next" />
<!--<button id="next">-->
<script>
//document.getElementById("date").value = new Date().toJSON().slice(0,10)
var today = new Date();
var mm=today.getMonth();
var yy=today.getFullYear();
var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
var dat=monthNames[mm]+' '+yy;
var yyy="";
document.getElementById("date").value = dat;
document.getElementById('prev').addEventListener("click", function() {
var last=document.getElementById("date").value;
var val=last.split(" ");
var month=val[0];
var year=val[1];
if(month=='January'){
var mmm=11;
yyy=year-1;
var dat=monthNames[mmm]+' '+yyy;
document.getElementById("date").value = dat ;
}
else {
var index=monthNames.indexOf(month);
var mmm=index-1;
var dat=monthNames[mmm]+' '+year;
document.getElementById("date").value = dat;
}
});
var xxx="";
document.getElementById('next').addEventListener("click", function() {
var next=document.getElementById("date").value;
var val=next.split(" ");
var month=val[0];
var year=val[1];
if(month=='December'){
var mmm=0;
xxx=++year;
var dat=monthNames[mmm]+' '+xxx;
document.getElementById("date").value = dat ;
}
else {
var index=monthNames.indexOf(month);
var mmm=index+1;
var dat=monthNames[mmm]+' '+year;
document.getElementById("date").value = dat;
}
});
</script>
</form>
</body>
</html>
display.php
<?php
include 'config.php';
if(isset($_POST['prev']) || isset($_POST['next']))
{
$monyear=$_POST['date'];
$mnh=explode(' ',$monyear);
$years=$mnh[1];
$months=strtolower(substr("$mnh[0]",0,3));
$comb=$months.'-'.$years;
$select ="SELECT * FROM `daily_report` WHERE `reg_id`='akshaypm123' and
`monyr`='$comb' ";
$res = mysqli_query($db,$select);
while($row=mysqli_fetch_array($res))
{
$abc=$row['monyr'];
$count=0;
$ab=explode('-',$abc);
$year = $ab[1];
$month = $ab[0];
$mon = date("m", strtotime($month));
$date = mktime(12, 0, 0, $mon, 1, $year);
$daysInMonth = date("t", $date);
$offset = date("w", $date); //for may->offset=1
$rows = 1;
echo "<h1 align = center> " . date("F Y", $date) . "</h1>\n";
echo "<table align = center>";
echo "<tbody style = 'font-family:monospace;background-color:beige; border-
top:2 solid black'>";
echo "\t<tr style ='height:3em;background-color:mistyrose;'><th>Sunday</th>
<th>Monday</th><th>Tuesday</th><th>Wednesday</th><th>Thursday</th>
<th>Friday</th><th>Saturday </th></tr>";
echo "\n\t<tr>";
for($i = 1; $i <= $offset; $i++)
{
echo "<td border = 2 soild black></td>";
}
for($day = 1; $day <= $daysInMonth; $day++)
{
if( ($day + $offset - 1) % 7 == 0 && $day != 1)
{
echo "<tr>\n\t</tr>";
$rows++;
}
$cba=$row['d'.$day.''];
$time=explode('-',$cba);
if ($cba=='leave') {
$count +=1;
}
if($count>1)
{
switch($time[0]) {
case 'leave':
$bg_color = "red";
break;
/* case 'absent':
$bg_color = "red";
break;*/
case 'NH':
$bg_color = "yellow";
break;
case $time[0]=='08:30 AM ' || $time[0]<='09:00 AM ':
$bg_color = "honeydew";
break;
case $time[0]>'09:00 AM ':
$bg_color = "orange";
break;
}
}
else {
switch($time[0]) {
case 'leave':
$bg_color = "green";
break;
case 'NH':
$bg_color = "yellow";
break;
case $time[0]=='08:30 AM ' || $time[0]<='09:00 AM ':
$bg_color = "honeydew";
break;
case $time[0]>'09:00 AM ':
$bg_color = "orange";
break;
}
}
if(($day + $offset - 1) % 7 == 0){
echo "<td style=' width:6em; background-
color:cornflowerblue'> <br></td>";
}
else if($time[0]!=null){
echo "<td style=' width:10em; height:5em; text-align:center;
background-color:".$bg_color."'>".$cba."</td>";
}
else {
echo "<td style='background-color:red;text-align:center;'>LOP<br>
</td>";
}
}
while( ($day + $offset) <= $rows * 7)
{
echo "<td></td>";
$day++;
}
echo "</tr>";
echo "</tbody></table>";
}
}
else{
$disp= strtolower(date("M-Y"));
$select ="SELECT * FROM `daily_report` WHERE `reg_id`='akshaypm123' and
`monyr`='$disp'";
$res = mysqli_query($db,$select);
while($row=mysqli_fetch_array($res))
{
$abc=$row['monyr'];
$count=0;
$ab=explode('-',$abc);
$year = $ab[1];
$month = $ab[0];
$mon = date("m", strtotime($month));
$date = mktime(12, 0, 0, $mon, 1, $year);
$daysInMonth = date("t", $date);
$offset = date("w", $date); //for may->offset=1
$rows = 1;
echo "<h1 align = center> " . date("F Y", $date) . "</h1>\n";
echo "<table align = center>";
echo "<tbody style = 'font-family:monospace;background-color:beige;
border-top:2 solid black'>";
echo "\t<tr style ='height:3em;background-color:mistyrose;'>
<th>Sunday</th><th>Monday</th><th>Tuesday</th><th>Wednesday</th>
<th>Thursday</th><th>Friday</th><th>Saturday </th></tr>";
echo "\n\t<tr>";
for($i = 1; $i <= $offset; $i++)
{
echo "<td border = 2 soild black></td>";
}
for($day = 1; $day <= $daysInMonth; $day++)
{
if( ($day + $offset - 1) % 7 == 0 && $day != 1)
{
echo "<tr>\n\t</tr>";
$rows++;
}
$cba=$row['d'.$day.''];
$time=explode('-',$cba);
if ($cba=='leave') {
$count +=1;
}
if($count>1)
{
switch($time[0]) {
case 'leave':
$bg_color = "red";
break;
case 'NH':
$bg_color = "yellow";
break;
case $time[0]=='08:30 AM ' || $time[0]<='09:00 AM ':
$bg_color = "honeydew";
break;
case $time[0]>'09:00 AM ':
$bg_color = "orange";
break;
}
}
else {
switch($time[0]) {
case 'leave':
$bg_color = "green";
break;
case 'NH':
$bg_color = "yellow";
break;
case $time[0]=='08:30 AM ' || $time[0]<='09:00 AM ':
$bg_color = "honeydew";
break;
case $time[0]>'09:00 AM ':
$bg_color = "orange";
break;
}
}
if(($day + $offset - 1) % 7 == 0){
echo "<td style=' width:6em; background-
color:cornflowerblue'> <br></td>";
}
else if($time[0]!=null){
echo "<td style=' width:10em; height:5em; text-align:center;
background-color:".$bg_color."'>".$cba."</td>";
}
else {
echo "<td style='background-color:red;text-align:center;'>LOP<br>
</td>";
}
}
while( ($day + $offset) <= $rows * 7)
{
echo "<td></td>";
$day++;
}
echo "</tr>";
echo "</tbody></table>";
}
}
?>
I tried in ajax by passing date value, but it is not working.enter image
description here
Related
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.
I'm constructing a survey and I have a textbox that generates dynamic dropdowns based on user input which displays the same data.
This is the script
<script>
function load_questions(){
var xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","ajax.php??main=1&subcategory="+document.getElementById("subcategorydd").value +"&cnt="+document.getElementById("q_num").value,false);
xmlhttp.send(null);
document.getElementById("question").innerHTML=xmlhttp.responseText;
}
function checkValues() {
_values = [];
$('.form-control-static').each(function() {
_values.push($(this).val());
//console.log($(this).val());
});
sameValue = false;
for ($i = 0; $i < (_values).length; $i++) {
for ($w = 0; $w < (_values).length; $w++) {
if (_values[$i] === _values[$w] && $i != $w) {
sameValue = true;
}
}
}
if (sameValue) {
alert('has the same value .');
return false;
}
alert('there is no the same value');
//do something .
}
</script>
This is the insert code when I'm creating the survey
<?php
$con = mysqli_connect("localhost","root","","imetrics");
if(isset($_POST['submit'])){
$title = $_POST['surveytitle'];
$catdd = $_POST['catdd'];
$subcatdd = $_POST['subcatdd'];
$gender = $_POST['gender'];
$age = $_POST['age'];
$occupation = $_POST['occupation'];
$occupationtwo = $_POST['occupdd'];
$relstatus = $_POST['relationshipstatus'];
$q_num = $_POST['q_num'];
$insert = mysqli_query($con, "INSERT INTO `surveyform` (`surveytitle`,`surveycategory`,`surveysubcategory`,`gender`,`age`,`occupation`,`occupation_status`,`status`) VALUES ('$title','$catdd','$subcatdd','$gender','$age','$occupation','$occupationtwo','$relstatus')");
if(!$insert){
echo mysqli_errno();
}
else{
$getMaxID = mysqli_query($con, "SELECT MAX(survey_id) as maxid FROM surveyform");
$row_2 = mysqli_fetch_array($getMaxID);
$survey_id = $row_2[0];
for( $a = 1; $a <= $q_num; $a++)
{
mysqli_query($con, "INSERT INTO surveyform_questions ( survey_id, question_id) VALUES ('$survey_id', ". $_POST['question_dropdowns'.$a] .")");
//echo "INSERT INTO surveyform_questions ( survey_id, question_id) VALUES ('$survey_id', ". $_POST['question_dropdowns'.$a] .")";
}
echo '<script language="javascript">';
echo 'alert("Survey Created!")';
echo '</script>';
}
}
?>
And this is my dropdown code
if($question !="" && $cnt!="" && $addQues!="yes" && $main != 1){
$i = 0;
for ($i = 1; $i <= $cnt; $i++)
{
$query=mysqli_query($con, "SELECT * FROM question WHERE question_subcat = $question ");
echo "<b>Question #". $i."</b>";
echo "<select id='question_dropdown".$i."' class='form-control-static' name='question_dropdowns".$i."'>";
echo "<option selected>"; echo "Select"; echo "</option>";
while($row=mysqli_fetch_array($query))
{
echo "<option value='$row[question_id]'>";
echo $row["questiontitle"];
echo "</option>";
}
echo "</select>";
echo "<br />";
}
echo "<div id='insertQuesHere".$i."'></div>";
echo "<a href='#add_question' onclick='return addQues();'>Add Question</a>";
}
here's my submit button
<input type="submit" name="" id="btnSaveSurvey" class="form-control-static" onclick="checkValues();" value="check" />
What's the validation code that will prevent me from inserting if the data chosen from the dropdown is the same? For example I generated 2 dropdowns and I chose the same datas from the dropdown, what's the validation code for it?
Please call checkValues method your submit button click
<input type="submit" name="" id="btnSaveSurvey" class="form-control-static" onclick="checkValues();" value="check" />
checkValues method below :
function checkValues() {
_values = [];
$('.form-control-static').each(function() {
_values.push($(this).val());
//console.log($(this).val());
});
sameValue = false;
for ($i = 0; $i < (_values).length; $i++) {
for ($w = 0; $w < (_values).length; $w++) {
if (_values[$i] === _values[$w] && $i != $w) {
sameValue = true;
}
}
}
if (sameValue) {
alert('has the same value .');
return false;
}
alert('there is no the same value');
//do something .
}
Also , you can see an example Example
I need a little help here I have a breadcrumbs in php. My directory is like this:
folder/name.php
and using this code I get on output like this:
Home » folder » name
What I want to do is to put name that I want instead of the code gets the name of folder and file.
Here's my code:
<?php
$path = $_SERVER["PHP_SELF"];
$parts = explode('/',$path);
if (count($parts) < 2)
{
echo("home");
}
else
{
echo ("Home » ");
for ($i = 1; $i < count($parts); $i++)
{
if (!strstr($parts[$i],"."))
{
echo("<a href=\"");
for ($j = 0; $j <= $i; $j++) {echo $parts[$j]."/";};
echo("\">". str_replace('-', ' ', $parts[$i])."</a> » ");
}
else
{
$str = $parts[$i];
$pos = strrpos($str,".");
$parts[$i] = substr($str, 0, $pos);
echo str_replace('-', ' ', $parts[$i]);
};
};
};
?>
Second code
<?php
$Pages = array(
'/NewTgoTv' => 'Clothes',
'/NewTgoTv/33.php' => 'Something'
);
$path = $_SERVER["PHP_SELF"];
$parts = explode('/',$path);
if (count($parts) < 2)
{
echo("home");
}
else
{
echo ("Home » ");
for ($i = 1; $i < count($parts); $i++)
{
if (!strstr($parts[$i],"."))
{
echo("<a href=\"");
for ($j = 0; $j <= $i; $j++) {echo $parts[$j]."/";};
echo("\">". str_replace('-', ' ', $Pages[$parts[$i]])."</a> » ");
}
else
{
$str = $parts[$i];
$pos = strrpos($str,".");
$parts[$i] = substr($str, 0, $pos);
echo str_replace('-', ' ', $Pages[$parts[$i]]);
};
};
};
?>
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 having that making a function to add a favorite item, have a heart icon when you click on that it should change the color from gray to red and save the status.
Before I had a selection box that could save status but with image unable to adapt a function.
SelectBox where I could save and change status:
<select id="priority-select-<?php echo $id ?>" class="form-control" name="priority[<?php echo $id ?>]" title="<?php echo $this->__('Priority') ?>">
<?php foreach($_hlp->getPriorities() as $k=>$v):?>
<option value="<?php echo $k ?>" <?php if ($k == $item->getPriority()){ echo "selected"; } ?>><?php echo $this->htmlEscape($v) ?></option>
<?php endforeach; ?>
</select>
I'm trying to do using images for icons:
<img id="heart-l-<?php echo $id ?>"
src="<?php if ($item->getPriority() < 1) {echo $this->getSkinUrl('images/heart-m-disabled.png');} else {echo $this->getSkinUrl('images/heart-m.png');} ?>"
alt="" onclick='adicionaFav(this.id)'/>
My javascript code:
<script type="text/javascript">
var $jq = jQuery.noConflict();
var heart_m = "<?php echo $this->getSkinUrl('images/heart-m.png') ?>";
var heart_m_disabled = "<?php echo $this->getSkinUrl('images/heart-m-disabled.png') ?>";
var valor;
function adicionaFav(id) {
if(document.getElementById(id).src == "<?php echo $this->getSkinUrl('images/heart-m-disabled.png');?>"){
document.getElementById(id).src = "<?php echo $this->getSkinUrl('images/heart-m.png');?>";
priorityChange(1, id);
$jq('#priority-select-' + id).val('0');
}
else{
document.getElementById(id).src = "<?php echo $this->getSkinUrl('images/heart-m-disabled.png');?>";
priorityChange(0, id);
$jq('#priority-select-' + id).val('1');
}
}
function priorityChange(size,id) {
if(size==1){
$jq("#heart-m-" + id).attr("src", heart_m);
}else{
$jq("#heart-m-" + id).attr("src", heart_m_disabled);
}/*
switch (size) {
case 0: {
$jq("#heart-m-" + id).attr("src", heart_m_disabled);
$jq("#heart-l-" + id).attr("src", heart_l_disabled);
break;
}
case 1: {
$jq("#heart-m-" + id).attr("src", heart_m);
$jq("#heart-l-" + id).attr("src", heart_l_disabled);
break;
}
case 2: {
$jq("#heart-m-" + id).attr("src", heart_m);
$jq("#heart-l-" + id).attr("src", heart_l);
break;
}
}*/
}
/*
function prioritySelect(size, id) {
switch (size) {
case 0: {
priorityChange(size, id);
$jq('#priority-select-' + id).val('0');
break;
}
case 1: {
priorityChange(size, id);
$jq('#priority-select-' + id).val('1');
break;
}
case 2: {
priorityChange(size, id);
$jq('#priority-select-' + id).val('2');
break;
}
}
}*/
</script>
note: I could change the color of the heart, however was unable to save the status when upgrading.
can someone tell me what must I do to save the favorite status?
want to have prioridad = 0 to gray heart and priority = 1 for the red heart
can solve, following the codes below:
icon:
<img id="heart-m-<?php echo $id ?>"
src="<?php if ($item->getPriority() < 1) {
echo $this->getSkinUrl('images/heart-m-disabled.png');
} else {
echo $this->getSkinUrl('images/heart-m.png');
} ?>"
alt="" onclick='adicionaFav(<?php echo $id ?>)'/>
</div>
Javascript code:
<script type="text/javascript">
var $jq = jQuery.noConflict();
var heart_m = "<?php echo $this->getSkinUrl('images/heart-m.png') ?>";
var heart_m_disabled = "<?php echo $this->getSkinUrl('images/heart-m-disabled.png') ?>";
var valor;
function adicionaFav(id) {
if (document.getElementById("heart-m-" + id).src == "<?php echo $this->getSkinUrl('images/heart-m-disabled.png');?>") {
$jq("#heart-m-" + id).attr("src", heart_m);
$jq('#priority-select-' + id).val('1');
}
else {
$jq("#heart-m-" + id).attr("src", heart_m_disabled);
$jq('#priority-select-' + id).val('0');
}
}
function priorityChange(size, id) {
if (size == 1) {
$jq("#heart-m-" + id).attr("src", heart_m);
} else {
$jq("#heart-m-" + id).attr("src", heart_m_disabled);
}
}
</script>
hope I can to help someone!! =)