Toggle hide/show table td in .hta - javascript

I've seen several of posts regarding this subject, but I have not managed to solve my own problem despite of having tried different methods.
I am programming in a .hta file, where I have all my notes titles listed above each other. Whenever you click a note title the description should appear (toggle/expand) under the title. All the notes should start hidden.
sub searchdata
SQL_query = "SELECT * FROM dvd WHERE Title LIKE '%"& txtsrch.value &"%' OR Notes LIKE '%"& txtsrch.value &"%' ORDER BY Title"
Set rsData = conn.Execute(SQL_query)
strHTML2 = strHTML2 & ""
Do Until rsData.EOF = True
strHTML2 = strHTML2 & "<table width='97%' border='0' id='bodytext' style='border-bottom: solid #000000 1px;'><tr><span class'togglelink'><td width='70%' style='cursor: pointer'><b>" & rsData("Title") & "</b></td></span><td align='right' style='color: #000'>" & rsData("Cat") & " <a href='#' onclick='editUser("& rsData("ID") &")' language='vbscript'><img src='images/arrow-blue.png' border='0' title='Rediger notatet' /></a> <a href='#' onclick='deleteUser("& rsData("ID") &")' language='vbscript'><img src='images/slet.png' border='0' title='Slet notatet' /></a></td><tr><span class='toggle' style='display: block'><td colspan='2'>" & rsData("Notes") & "</td></span></tr></table>"
rsData.moveNext ' go to next record
Loop
strHTML2 = strHTML2 & ""
searchIT.innerHTML = strHTML2
end sub
I am using this JS script to run it:
<script type="text/javascript">
$(document).ready(function () {
$('.toggle').hide();
$('span.togglelink').on('click', function (e) {
e.preventDefault();
var elem = $(this).next('.toggle')
$('.toggle').not(elem).hide('fast');
elem.toggle('fast');
});
});
</script>
I can easily get the script to work when testing with just plain text.
JSFiddle
Side question: Is programming in a HTA really so different from HTML? I'm running in to a lot of problems trying to convert my whole site (MySQL, PHP, HTML) to working in HTA.
Thanks in advance!
Update: Listed my whole .hta script:
<html>
<HTA:APPLICATION ID="oHTA"
APPLICATIONNAME="myApp"
BORDER="thick"
CAPTION="yes"
ICON=./images/Icon.ico
MAXIMIZEBUTTON="yes"
MINIMIZEBUTTON="yes"
SHOWINTASKBAR="yes"
SINGLEINSTANCE="no"
SYSMENU="yes"
RESIZE="yes"
VERSION=7.2
WINDOWSTATE="normal"
contextMenu=no
>
<head>
<style>
#vis1{
display:none;
}
</style>
<script type="text/javascript"> // Width and height in pixel to the window
window.resizeTo(683,725);
</script>
<script type="text/javascript">
var enablepersist="on" //Enable saving state of content structure using session cookies? (on/off)
var collapseprevious="Yes" //Collapse previously open content when opening present? (yes/no)
if (document.getElementById){
document.write('<style type="text/css">')
document.write('.switchcontent{display:none;}')
document.write('</style>')
}
function getElementbyClass(classname){
ccollect=new Array()
var inc=0
var alltags=document.all? document.all : document.getElementsByTagName("*")
for (i=0; i<alltags.length; i++){
if (alltags[i].className==classname)
ccollect[inc++]=alltags[i]
}
}
function contractcontent(omit){
var inc=0
while (ccollect[inc]){
if (ccollect[inc].id!=omit)
ccollect[inc].style.display="none"
inc++
}
}
function expandcontent(cid){
if (typeof ccollect!="undefined"){
if (collapseprevious=="yes")
contractcontent(cid)
document.getElementById(cid).style.display=(document.getElementById(cid).style.display!="block")? "block" : "none"
}
}
function revivecontent(){
contractcontent("omitnothing")
selectedItem=getselectedItem()
selectedComponents=selectedItem.split("|")
for (i=0; i<selectedComponents.length-1; i++)
document.getElementById(selectedComponents[i]).style.display="block"
}
function get_cookie(Name) {
var search = Name + "="
var returnvalue = "";
if (document.cookie.length > 0) {
offset = document.cookie.indexOf(search)
if (offset != -1) {
offset += search.length
end = document.cookie.indexOf(";", offset);
if (end == -1) end = document.cookie.length;
returnvalue=unescape(document.cookie.substring(offset, end))
}
}
return returnvalue;
}
function getselectedItem(){
if (get_cookie(window.location.pathname) != ""){
selectedItem=get_cookie(window.location.pathname)
return selectedItem
}
else
return ""
}
function saveswitchstate(){
var inc=0, selectedItem=""
while (ccollect[inc]){
if (ccollect[inc].style.display=="block")
selectedItem+=ccollect[inc].id+"|"
inc++
}
document.cookie=window.location.pathname+"="+selectedItem
}
function do_onload(){
uniqueidn=window.location.pathname+"firsttimeload"
getElementbyClass("switchcontent")
if (enablepersist=="on" && typeof ccollect!="undefined"){
document.cookie=(get_cookie(uniqueidn)=="")? uniqueidn+"=1" : uniqueidn+"=0"
firsttimeload=(get_cookie(uniqueidn)==1)? 1 : 0 //check if this is 1st page load
if (!firsttimeload)
revivecontent()
}
}
if (window.addEventListener)
window.addEventListener("load", do_onload, false)
else if (window.attachEvent)
window.attachEvent("onload", do_onload)
else if (document.getElementById)
window.onload=do_onload
if (enablepersist=="on" && document.getElementById)
window.onunload=saveswitchstate
</script>
<title>Søgning</title>
<link href="stylesheet/stylesheet.css" rel="stylesheet" type="text/css" />
<link rel="SHORTCUT ICON" href="images/icon.ico"/>
<script type="text/javascript" charset="utf-8" src="jquery/jquery-1.7.min.js"></script>
<script language="vbscript">
Dim conn 'GLOBAL doing this here so that all functions can use it
sub dotheconnection
Set conn = CreateObject("ADODB.Connection")
conn.Open "Provider=Microsoft.Jet.OLEDB.4.0; Data Source =./Database/data.mdb; User Id=; Password="
If conn.errors.count <> 0 Then
else
' if connected OK call sub getdata
getdata
end if
end sub
sub getdata
SQL_query = "SELECT * FROM dvd ORDER BY Title"
Set rsData = conn.Execute(SQL_query)
strHTML = strHTML & ""
Do Until rsData.EOF = True
strHTML = strHTML & "<table width='97%' border='0' id='bodytext' style='border-bottom: solid #000000 1px;'><tr><td width='70%' style='cursor: pointer'><span id='vis'><b>" & rsData("Title") & "</b></span></td><td align='right' style='color: #000'>" & rsData("Cat") & " <a href='#' onclick='editUser("& rsData("ID") &")' language='vbscript'><img src='images/arrow-blue.png' border='0' title='Rediger notatet' /></a> <a href='#' onclick='deleteUser("& rsData("ID") &")' language='vbscript'><img src='images/slet.png' border='0' title='Slet notatet' /></a></td><tr><td colspan='2'><span id='vis1'>" & rsData("Notes") & "</span></td></tr></table>"
rsData.moveNext ' go to next record
Loop
strHTML = strHTML & ""
SQL_query = "SELECT Count(*) AS intTotal FROM dvd"
Set rsData = conn.Execute(SQL_query)
strHTML1 = strHTML1 & ""
strHTML1 = strHTML1 & "" & rsData("intTotal") & " "
Count.innerHTML = strHTML1
end sub
sub searchdata
SQL_query = "SELECT * FROM dvd WHERE Title LIKE '%"& txtsrch.value &"%' OR Notes LIKE '%"& txtsrch.value &"%' ORDER BY Title"
Set rsData = conn.Execute(SQL_query)
strHTML2 = strHTML2 & ""
Do Until rsData.EOF = True
strHTML2 = strHTML2 & "<table width='97%' border='0' id='bodytext' style='border-bottom: solid #000000 1px;'><tr><span class'togglelink'><td width='70%' style='cursor: pointer'><b>" & rsData("Title") & "</b></td></span><td align='right' style='color: #000'>" & rsData("Cat") & " <a href='#' onclick='editUser("& rsData("ID") &")' language='vbscript'><img src='images/arrow-blue.png' border='0' title='Rediger notatet' /></a> <a href='#' onclick='deleteUser("& rsData("ID") &")' language='vbscript'><img src='images/slet.png' border='0' title='Slet notatet' /></a></td><tr><span class='toggle' style='display: block'><td colspan='2'>" & rsData("Notes") & "</td></span></tr></table>"
rsData.moveNext ' go to next record
Loop
strHTML2 = strHTML2 & ""
searchIT.innerHTML = strHTML2
end sub
sub deleteUser(id)
If MsgBox("Vil du slettet dette notat?", vbYesNo) =vbYes Then
SQL_query = "DELETE * FROM dvd WHERE ID = " & id
conn.Execute(SQL_query)
getdata
reloadpage()
Else
MsgBox("Notatet er ikke blevet slettet.")
End IF
end sub
sub addUser
SQL_query = "INSERT INTO dvd (Title,Length,Notes,Cat) VALUES ('"& txtTitle.value &"','"& txtLength.value &"','"& txtNotes.value &"','"& txtCat.value &"')"
conn.Execute(SQL_query)
reloadpage()
expandcontent("sc2")
getdata
end sub
sub editUser(id)
SQL_query = "SELECT * FROM dvd WHERE ID=" & id
Set rsData=conn.Execute(SQL_query)
txtTitle.value = rsData("Title")
txtLength.value = rsData("Length")
txtNotes.value = rsData("Notes")
txtCat.value = rsData("Cat")
txtID.value = rsData("ID")
btnUpdate.disabled = false // Show
btnOpret.disabled = true // Hide
expandcontent("sc2")
getdata
end sub
sub updateUser
SQL_query = "UPDATE dvd SET Title='"& txtTitle.value &"', Length='"& txtLength.value &"' , Notes='"& txtNotes.value &"', Cat='"& txtCat.value &"' WHERE ID= " & txtID.value
conn.Execute(SQL_query)
getdata
reloadpage()
expandcontent("sc2")
end sub
</script>
<script type="text/javascript" charset="utf-8" src="jquery/jquery-1.7.min.js"></script>
<SCRIPT TYPE="text/javascript">
function init()
{
dotheconnection();
searchdata();
getdata();
}
</SCRIPT>
<script>
function addNotat() {
btnOpret.disabled = false; // Show
btnUpdate.disabled = true; // Hide
expandcontent("sc2");
}
</script>
<script>
function reloadpage() {
location.reload();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
$('.toggle').hide();
$('div.togglelink').on('click', function (e) {
e.preventDefault();
var elem = $(this).next('.toggle')
$('.toggle').not(elem).hide('fast');
elem.toggle('fast');
});
});
</script>
</head>
<body onLoad="init()" language="vbscript">
<table width="100%" border="0" cellpadding="0" cellspacing="0">
<tr>
<td height="40" width="20%" id="top_bar">
<input language="vbscript" onload="searchdata" onkeyup="searchdata" name="txtsrch" id="filter_input" width="15%" tabindex="0" autofocus="autofocus" size="35" type="search" style="background: url(images/search_bg.png) #FFF no-repeat left; padding-left: 20px; margin-left: 10px" placeholder="Søgning"> </td>
<td id="top_bar"></div><span id="Count"></span> notater </td>
<td width="22%" id="top_bar" align="right"><input type="button" style="margin-right: 10px" onClick="history.go(0)" value="Opdater"><a onClick="addNotat()" style="cursor: hand">Opret</a> </span></td>
<td width="20%" id="top_bar" align="right"><img src="images/footer-logo.png" style="margin-right: 10px" border="0" title="Gå til forsiden" /></td>
</tr>
</table>
<br>
<div id="sc2" class="switchcontent" style="margin-left: 10px">
<b>Title:<br></b><input type="text" name="txtTitle" size="43"><br>
<b>Kategori:</b><br>
<select size="1" name="txtCat">
<option value="">Vælg kategori</option>
<option value="Thriller">Thriller</option>
<option value="Westerns">Westerns</option>
</select><br>
<b>Length</b><br><input type="text" name="txtLength" size="8"><br>
<b>Notat:</b><br><textarea rows="6" name="txtNotes" cols="55"></textarea><br>
<p align="left"><b>
<input type="button" name="btnOpret" value="Opret" onclick="addUser" language="vbscript" disabled>
<input type="button" name="btnUpdate" value="Gem" onclick="updateUser" language="vbscript" disabled>
<input type="hidden" name="txtID">
</b></p>
</div>
</div>
<div id="searchIT" style="margin-left: 10px"></div>
</body>
</script>
</html>

The div.togglelink's will be attached after the document has been loaded, your on-handler will only have an effect to elements that are present when the document loads.
Attach the handler to the body instead:
$('body').on('click','span.togglelink',function(){/*your callback*/});

Related

Two sided multiple select box highlight issues ASP Classic

I am working on a form page which has a two sided multiple select boxes. Box 1 will load from the server all the available dates. When double clicked or select and click >, box 1 options will move to box 2. Box 2 options will be highlighted and selected.
During saved, I added no.selected = true in one of the javascript code to select all the options in box 2 and save it.
But when I enter the page during edit mode, I have some problems:
1. When the page loads, all the selected options will be loaded and highlighted in Box 2. I have to pre-select them by again adding selected=’selected’ in the option tag. This will keep them selected so that when I hit update, I will manage to get their values and update the records according.
2. But when I hit transfer a single option from box 2 back to box 1, everything is selected and highlighted in box 1 and box 2, is there a way to not select things in box?
3. I don’t mind box 2 to always remain selected but is there a CSS or something to hide the selected highlights?
4. During save and update, I need the server to manage to request the values from the options tag in box2. What I did is request all the values in a long string, and split it and save. If the options is not selected, I can’t manage to get the values. Again, how to let the options remain selected when moving from Box 1 to Box 2?
5. Double click once and it will select all in box 1? Please see
Double click highlight Box1 issue.
6. Move back or transfer back it will again highlight in dark grey in box 1? Please see Transfer back highlight Box 1 issue
To all the gurus, please help me, thank you very much.
<%
sHOL_ID= request("txtHOL_ID")
iPage = request("Page")
sSearch = request("txtSearch")
sModeSub = request("sub")
if sHOL_ID <> "" then
sID = sHOL_ID
else
sID = UCase(reqForm("txtID"))
end if
sName= reqForm("txtName")
sMainURL = "tmholcal.asp?"
sAddURL = "txtSearch=" & server.HTMLEncode(sSearch) & "&Page=" & iPage
if sModeSub = "up" then
arr=Split(reqform("ToLB"),",")
if Ubound(arr) < 0 then
response.write "<script language='javascript'>"
response.write "if (confirm(""Emptying the selected box will delete the Holiday Calendar Code"")==0)"
response.write " {window.history.back();}"
response.write "</script>"
end if
sSQL = "delete from TMHOL1 where HOL_ID = '" & sID & "'"
conn.execute sSQL
for j = 0 to Ubound(arr)
sDt_Hol = arr(j)
j = j + 1
sPart = arr(j)
sSQL = "insert into tmhol1 (HOL_ID,NAME,DT_HOL,PART,USER_ID,DATETIME) "
sSQL = sSQL & "values ("
sSQL = sSQL & "'" & pRTIN(sID) & "',"
sSQL = sSQL & "'" & pRTIN(sName) & "',"
sSQL = sSQL & "'" & fdate2(sDt_Hol) & "',"
sSQL = sSQL & "'" & pRTIN(sPart) & "',"
sSQL = sSQL & "'" & session("USERNAME") & "',"
sSQL = sSQL & "'" & fdatetime2(Now()) & "'"
sSQL = sSQL & ") "
conn.execute sSQL
Next
sAddURL = "txtSearch=" & sSearch & "&Page=" & iPage
call confirmBox("Update Successful!", sMainURL&sAddURL&"&txtHOL_ID=" & sID & "")
elseif sModeSub = "save" then
if sID = "" then
alertbox(" Holiday Calendar Code cannot be empty! ")
end if
arr=Split(reqform("ToLB"),",")
for i = 0 to Ubound(arr)
sDt_Hol = arr(i)
i = i + 1
sPart = arr(i)
sSQL = "insert into tmhol1 (HOL_ID,NAME,DT_HOL,PART,USER_ID,DATETIME) "
sSQL = sSQL & "values ("
sSQL = sSQL & "'" & pRTIN(sID) & "',"
sSQL = sSQL & "'" & pRTIN(sName) & "',"
sSQL = sSQL & "'" & fdate2(sDt_Hol) & "',"
sSQL = sSQL & "'" & pRTIN(sPart) & "',"
sSQL = sSQL & "'" & session("USERNAME") & "',"
sSQL = sSQL & "'" & fdatetime2(Now()) & "'"
sSQL = sSQL & ") "
conn.execute sSQL
call confirmBox("Save Successful!", sMainURL&sAddURL&"&txtHOL_ID=" & sID & "")
next
end if
function ShowAvailDates(sParam)
Set rs=server.CreateObject("ADODB.Recordset")
sql="Select * from tmhol "
sql=sql & "order by dt_hol"
rs.open sql, conn
if len(sParam) > 0 then
do while not rs.eof
bflag=true
Set rs1=server.CreateObject("ADODB.Recordset")
sql="Select * from tmhol1 "
sql = sql & " where hol_id = '" & sParam & "'"
sql = sql & " order by dt_hol"
rs1.open sql, conn
do while not rs1.eof
if fdate2(rs("DT_HOL")) = fdate2(rs1("DT_HOL")) then
bflag= false
exit do
end if
rs1.movenext
loop
if bflag = true then
response.write "<option value='" & rs("DT_HOL") & "," & rs("PART") & "'>" & rs("DT_HOL") & " - " & rs("PART") & "</option>"
end if
rs.movenext
loop
else
do while not rs.eof
if year(rs("DT_HOL")) = year(date) then
response.write "<option value='" & rs("DT_HOL") & "," & rs("PART") & "'>" & rs("DT_HOL") & " - " & rs("PART") & "</option>"
end if
rs.movenext
loop
pCloseTables(rs)
end if
end function
Set rstTMHOL1 = server.CreateObject("ADODB.RecordSet")
sSQL = "select * from TMHOL1 where HOL_ID ='" & sID & "'"
rstTMHOL1.Open sSQL, conn, 3, 3
if not rstTMHOL1.eof then
sName = rstTMHOL1("Name")
end if
%>
</head>
<body class="hold-transition skin-blue sidebar-mini">
<div class="wrapper">
<!-- #include file="include/header.asp" -->
<!-- Left side column. contains the logo and sidebar -->
<!-- #include file="include/sidebar_tm.asp" -->
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>Holiday Calendar Details</h1>
</section>
<!-- Main content -->
<section class="content">
<div class="row">
<div class="col-md-12">
<div class="box">
<!-- /.box-header -->
<div class="box-body ">
<form name="form1" class="form-horizontal" action="tmholcal_det.asp" method="POST">
<input type="hidden" name="Page" value='<%=iPage%>' />
<div class="form-group">
<label class="col-sm-3 control-label">Holiday Calendar Code : </label>
<div class="col-sm-7">
<% if sHOL_ID <> "" then %>
<span class="mod-form-control"><% response.write sHOL_ID%> </span>
<input type="hidden" id="txtID" name="txtID" value="<%=sHOL_ID%>" />
<%else%>
<input class="form-control" id="txtID" name="txtID" value="<%=sID%>" maxlength="30" style="text-transform: uppercase" input-check />
<% end if %>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Name : </label>
<div class="col-sm-7">
<input class="form-control" id="txtName" name="txtName" value="<%=server.Htmlencode(sName)%>" maxlength="30">
</div>
</div>
<!--<div class="form-group">
<label class="col-sm-3 control-label">Year : </label>
<div class="col-sm-2">
<%if sSHFPAT_ID <> "" then%>
<span class="mod-form-control"><% response.write sYear%> </span>
<input type="hidden" id="selYear" value="<%=sYear%>" />
<%else%>
<select name="selYear" id="selYear" class="form-control">
<%For i = 1 to 34
selyear = Cint(2016) + Cint(i)
%>
<option value="<%=selyear%>" <%if sYear = selyear then%>Selected<%end if%>><%=selyear%></option>
<%Next%>
</select>
<% end if %>
</div>
</div>-->
<div>
<table id="example1">
<tbody>
<tr>
<td width="5%"></td>
<td width="20%" style="padding: 7px"><b>Available Dates :</b>
<select multiple size="15" style="width: 405px;" name="FromLB" id="FromLB" ondblclick="move(this.form.FromLB,this.form.ToLB)">
<%
ShowAvailDates(sHOL_ID)
%>
</select>
</td>
<td width="3%" style="padding: 9px" align="center">
<input type="button" class="btn btn-primary" style="width: 50px" onclick="move(this.form.FromLB, this.form.ToLB)" value=" > ">
<br>
<br>
<input type="button" class="btn btn-primary" style="width: 50px" onclick="move(this.form.ToLB, this.form.FromLB)" value=" < ">
</td>
<td width="30%" style="padding: 11px"><b>Selected : </b>
<select multiple size="15" style="width: 405px;" name="ToLB" id="ToLB" ondblclick="move(this.form.ToLB,this.form.FromLB)">
<% Set rstTMHOL1 = server.CreateObject("ADODB.RecordSet")
sSQL = "select * from TMHOL1 where HOL_ID ='" & sID & "'"
rstTMHOL1.Open sSQL, conn, 3, 3
do while not rstTMHOL1.eof
response.write "<option value='" & rstTMHOL1("DT_HOL") & "," & rstTMHOL1("PART") & "' selected='selected'>" & rstTMHOL1("DT_HOL") & " - " & rstTMHOL1("PART") & "</option>"
rstTMHOL1.movenext
loop
%>
</select>
</td>
</tr>
</tbody>
</table>
</div>
<div class="box-footer">
<%if sHOL_ID <> "" then %>
<a href="#" data-toggle="modal" data-target="#modal-delholcal" data-hol_id="<%=server.htmlencode(sHOL_ID)%>"
class="btn btn-danger pull-left" style="width: 90px">Delete</a>
<button type="submit" name="sub" value="up" class="btn btn-info pull-right" style="width: 90px">Update</button>
<%else%>
<button type="submit" name="sub" value="save" class="btn btn-default pull-right"
style="width: 90px">
Save</button>
<%end if%>
</div>
</form>
</div>
<!-- /.box-body -->
</div>
</div>
<!-- /.col -->
</div>
<!-- /.row -->
<div class="modal fade bd-example-modal-lg" id="modal-delholcal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="exampleModalLabel"></h4>
</div>
<div class="modal-body">
<div id="del-content">
<!--- Content ---->
</div>
</div>
</div>
</div>
</div>
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
<!-- #include file="include/footer.asp" -->
</div>
<!-- ./wrapper -->
<!-- input-check -->
<script src="plugins/Custom/input-check.js"></script>
<script>
$('#modal-delholcal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget) // Button that triggered the modal
var hol_id = button.data('hol_id')
var modal = $(this)
modal.find('.modal-body input').val(hol_id)
showDelmodal(hol_id)
})
function showDelmodal(str){
var xhttp;
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("del-content").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "tmholcal_del.asp?txtstring="+str, true);
xhttp.send();
}
</script>
<script>
function move(tbFrom, tbTo) {
var arrFrom = new Array(); var arrTo = new Array();
var arrLU = new Array();
var i;
for (i = 0; i < tbTo.options.length; i++) {
arrLU[tbTo.options[i].text] = tbTo.options[i].value;
arrTo[i] = tbTo.options[i].text;
}
var fLength = 0;
var tLength = arrTo.length;
for(i = 0; i < tbFrom.options.length; i++) {
arrLU[tbFrom.options[i].text] = tbFrom.options[i].value;
if (tbFrom.options[i].selected && tbFrom.options[i].value != "") {
arrTo[tLength] = tbFrom.options[i].text;
tLength++;
} else {
arrFrom[fLength] = tbFrom.options[i].text;
fLength++;
}
}
tbFrom.length = 0;
tbTo.length = 0;
var ii;
for(ii = 0; ii < arrFrom.length; ii++) {
var no = new Option();
no.value = arrLU[arrFrom[ii]];
no.text = arrFrom[ii];
no.selected = true;
tbFrom[ii] = no;
}
for(ii = 0; ii < arrTo.length; ii++) {
var no = new Option();
no.value = arrLU[arrTo[ii]];
no.text = arrTo[ii];
no.selected = true; // I enable it because when
tbTo[ii] = no;
}
}
</script>
</body>
Basically I got the flow wrong. I should have remove all the no.selected=true in the javascript code and add the following Jquery
$(document).ready(function () {
$('#btnUp').click(function () {
$('#ToLB').each(function () {
$('#ToLB option').attr("selected", "selected");
});
});
});
$(document).ready(function () {
$('#btnSave').click(function () {
$('#ToLB').each(function () {
$('#ToLB option').attr("selected", "selected");
});
});
});
Basically the Jquery will select all the options when btnSave or btnUpdate is clicked.
Hence, the server will manage to pick up the values of the option tags.

Read and write excel using javascript and hta

Here is the code to read the data from the excel sheet and paste that data into html table. It shows an error,when i convert the data from html table to excel sheet,but at the sametime this coding is working in vbscript,not working in javascript what is the solution for that..
<html>
<head>
<HTA:application
Applicationname="MyApp"
BORDER="dialog"
BORDERSTYLE="complex"
Caption="yes"
MAXIMIZEBUTTON="yes"
MINIMIZEBUTTON="yes"
SINGLEINSTANCE="no"
SYSMENU="yes"
VERSION="2.0"
WINDOWSTATE="maximize"/>
<title>Read Excel</title>
<style type="text/css">
body
{
background-color:White;
}
P
{
font:bold 18px arial;
}
</style>
<script language="javascript" type="text/javascript">
var rowCount,colCount,selectexcel,objExcel,tempcol,intRow,intCol;
var rowData;
var mySpan;
var textData;
function ReadExcelData()
{
selectexcel = prompt("Please enter the file path", "D:\VBScriptTrainee\Sample.xlsx");
objExcel = new ActiveXObject("Excel.Application");
objExcel.Visible = false;
objExcel.Workbooks.Open(selectexcel);
rowCount=objExcel.ActiveWorkbook.Sheets(1).UsedRange.Rows.Count
colCount=objExcel.ActiveWorkbook.Sheets(1).UsedRange.Columns.Count
alert(rowCount);
alert(colCount);
//colCount=colCount+1;
tempcol=colCount;
rowData="<table border=2>";
for (intRow=1;intRow <= rowCount;intRow++)
{
rowData = rowData + "<tr>";
for (intCol=1;intCol <= colCount;intCol++)
{
if ((intRow != 1) && (intCol ==tempcol))
{
rowData = rowData + "<td>" + "<input type='checkbox' id='flag_id' name='flag' />" + "</td>";
}
else if (intRow ==1)
{
rowData = rowData + "<td>" + objExcel.Cells(intRow,intCol).Value + "</td>";
}
else
{
rowData= rowData + "<td><div contentEditable='True'>" + objExcel.Cells(intRow,intCol).Value + "</div></td>";
}
}
rowData = rowData + "</tr>";
}
rowData =rowData + "</table>";
//document.write(rowData);
mySpan = document.getElementById('Span_id_two');
mySpan.innerHTML = rowData + "<br>";
//objExcel = undefined;
}
function WriteExcelData()
{
//mwresult = Msgbox ("Are you Sure to Write ?",vbOKCancel)
//var objExcelTwo;
//objExcelTwo = new ActiveXObject("Excel.Application");
//objExcelTwo.Visible = true;
//objExcelTwo.Workbooks.Open(selectexcel);
var tableValue;
var mySpan=document.getElementById('Span_id_two');
textData=mySpan.innerHTML;
var tab=document.getElementsByTagName("table")(0);
var mytable = document.getElementsByTagName("table")(0).rows.length;
//document.write(mytable);
var mytable1= document.getElementsByTagName("table")(0).rows(0).cells.length;
//document.write(mytable1);
for(n = 0;n<=(mytable-1);n++)
{
for(j = 0;j<=(mytable1-1);j++)
{
objExcel.Cells(n+1,j+1).Value = tab.Rows(n).Cells(j).innerHTML;
tableValue = tab.Rows(n).Cells(j).innerHTML;
if(tableValue == "<INPUT id=flag_id type=checkbox CHECKED name=flag>")
{
objExcel.Cells(n+1,mytable1).Value="Yes";
}
if(tableValue == "<INPUT id=flag_id type=checkbox name=flag>")
{
objExcel.Cells(n+1,mytable1).Value="No";
}
}
}
//var find ="<*>";
//var rplace =" ";
//objExcel.Cells.Replace find,rplace;
//MsgBox "Data Exported Successfully",vbInformation
//objExcel.ActiveWorkbook.Save;
//Set objExcel=nothing
}
</script>
</head>
<body>
<center>
<img src="Excel.png" height=200 width=300/>
</center>
<center>
<h1 align="center" style="color:blue"><img src="icon-developer-icon.png" height=100px width=100px/>
Read Excel (Row by Row)</h1><br>
<input type="button" name="Read" value="Click To Read" onclick="ReadExcelData()"/>
<input type="button" name="Write" value="Click To Write" onclick="WriteExcelData()"/>
</center>
<br>
<br>
<div>
<center>
<!--<table border="2px" color="Red">
<th id="thead"></th>
<tr>
<td>-->
<br>
<!--<div class="jumbotron">-->
<span ID="Span_id_two" Style="Color:blue;" name="text_name">
</span>
<br>
<!--</td>
</tr>
</table>-->
<marquee direction="Right" style="Color:red;">**Note : Select only excel files**</marquee>
</center>
</div>
</div>
</div>
</div>
</body>
</html>
It shows the following error 'object doesn't support this property or method'
in WriteExcelData function.

Website does not work when moving the files to another server?

![enter image description here][1]I'm trying to troubleshoot this problem. I created a basic asp page with Javascript in one server which works fine at the moment but when I move the asp page and all the related files to the new server it does not work. What my asp page does is ask for last or first name in text box and it has button which after it is press it returns all the matches with contact info. from Microsoft Access database.
HTML :
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<!-- JQuery Library used so that phone_dir.js can use JQuery -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<title>Corporate Phone Directory</title>
</head>
<body bgcolor="#FFFFFF" link="#003399">
<br>
<br>
<div style="font-size: 16px; font-family: Arial; color:#D6D6D6;">
<table width="745" height="81" border="0" align="left" bordercolor="#003399">
<tr>
<td width="300" height="50" align="left" valign="top">
<div align="left" valign="bottom">
Search by either First or Last Name:
<br>
<br>
<input name="Search" type="text" id="Search" value="">
<input name="btnFind2" type="button" id="btnFind2" value="Find" onClick="searchphonedirectory()">
</div>
</table>
</div>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<hr>
<div style="font-size: 16px; font-family: Arial; color:#D6D6D6;" align="left" id='results'>
<!-- Your results will go here -->
</div>
</body>
</html>
Javascript :
$(document).ready(function()
{
$( "#Search" ).keypress(function()
{
if(event.keyCode==13)
{
$("#btnFind2").click();
}; // End of If key code = Enter function
});
});
function searchphonedirectory()
{
var searchentry = document.getElementById('search').value;
if (window.XMLHttpRequest)
{
xmlhttp2=new XMLHttpRequest();
}
else
{
xmlhttp2=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp2.onreadystatechange=function()
{
if (xmlhttp2.readyState==4)
{
document.getElementById("results").innerHTML = xmlhttp2.responseText;
}
}
xmlhttp2.open("GET","phoneResults.asp?searchentry="+searchentry,true);
xmlhttp2.send();
};
Other Code which generates the results.
<!--#include file="ASPFiles/phoneDirectory.asp" -->
<%
response.expires=-1
err.clear
on error resume next
'*----------------------------------------------------------------
searchentry = request.querystring("searchentry")
'*----------------------------------------------------------------
sql = "SELECT PhoneDirectory.Name, PhoneDirectory.[Phone#], PhoneDirectory.OfficeExtension,
PhoneDirectory.[Mobile#] "
sql = sql +"FROM PhoneDirectory "
sql = sql +"WHERE (PhoneDirectory.LastName Like '" & searchentry & "%' OR
PhoneDirectory.FirstName Like '" & searchentry & "%' ) "
sql = sql + "ORDER BY LASTNAME,FIRSTNAME"
set rs=Server.CreateObject("ADODB.Recordset")
rs.Open sql,conn
'response.write(sql)
response.write("<table>")
response.write("<td width='22%' align='left' height='29'>Name</th>")
response.write("<td width='11%' align='left' >Phone</th>")
response.write("<td width='1%' align='left' >Ext</th>")
response.write("<td width='12%' align='left' >Mobile</th>")
response.write("</tr>")
do until rs.EOF
response.write("<tr>")
for each x in rs.Fields
response.write("<td align='left' >" & x.value & "</td>")
next
rs.MoveNext
response.write("</tr>")
loop
response.write("</table>")
%>
This one opens the database:
<%
' FileName="Connection_odbc_conn_dsn.htm"
' Type="ADO"
' DesigntimeType="ADO"
' HTTP="true"
' Catalog=""
' Schema=""
'Dim MM_phoneDirectory_STRING
'MM_phoneDirectory_STRING = "dsn=PhoneDB;"
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
'TESTING DB
conn.Open(Server.Mappath("/webs/corporatenet2/databases/Phone_Directory.mdb"))
%>
First thing is you missed to mention the event" in keypress event and remove the searchphonedirectory() function from HTML input "onClick",
<input name="btnFind2" type="button" id="btnFind2" value="Find">
Add it to your javascript code like this.
$( "#Search" ).keypress(function(event)
{
if(event.keyCode==13)
{
searchphonedirectory();
}; // End of If key code = Enter function
}); //End of Search Keypress Function
hope it helps.
This may not be an answer, but it will certainly help you in the right direction, if the problem is ASP based.
On the root of your web server (\inetpub\wwwroot), create a folder called errors. In that folder create a file called error.asp and paste the following into it...
<%Option Explicit%>
<%
dim LOGON_USER
LOGON_USER = UCASE(Request.ServerVariables ("LOGON_USER"))
PATH = request.ServerVariables("PATH_TRANSLATED")
Const lngMaxFormBytes = 2000
Dim objASPError, blnErrorWritten, strServername, strServerIP, strRemoteIP
Dim strMethod, lngPos, datNow, strQueryString, strURL,PATH
Dim arrError,i
If Response.Buffer Then
Response.Clear
Response.Status = "500 Internal Server Error"
Response.ContentType = "text/html"
Response.Expires = 0
End If
Set objASPError = Server.GetLastError
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
<title>eDischarge encountered an error...</title>
<meta http-equiv="Content-Type" content="text-html; charset=Windows-1252">
<link href="includes\stylesheet.css" rel="stylesheet" type="text/css">
<style type="text/css">
<!--
html {
font-family: Arial, Helvetica, sans-serif;
}
html body {
font-family: Arial, Helvetica, sans-serif;
}
body {
font-family: Arial, Helvetica, sans-serif;
color: #330000;
margin: 0;
padding: 0;
}
p {
font-size: 90%;
}
.errortitle {
font-family: Arial, Helvetica, sans-serif;
color: white;
font-size: 150%;
font-weight: bold;
width: 100%;
background-color: #770000;
padding: 1em;
}
.errorbody {
padding: 2em;
background: url(http://stas35/errors/images/error.gif) no-repeat top left;
}
.errormessage {
border-left: 10px solid #770000;
padding: 0 0 0 1em;
margin-left: 2em;
color: #770000;
}
.errorpadleft {
padding-left: 2em;
}
-->
</style>
</head>
<%
strError = strError & "<p><strong>Error Type:</strong></p>"
strError = strError & "<p class=""errorpadleft"">" & Server.HTMLEncode(objASPError.Category) & "</p>"
If objASPError.ASPCode > "" Then
strError = strError & "<p class=""errorpadleft"">" & Server.HTMLEncode(", " & objASPError.ASPCode) & "</p>"
end if
strError = strError & "<p class=""errorpadleft"">" & Server.HTMLEncode(" (0x" & Hex(objASPError.Number) & ")" ) & "</p>"
If objASPError.ASPDescription > "" Then
strError = strError & Server.HTMLEncode(objASPError.ASPDescription) & "<br/>"
elseIF (objASPError.Description > "") Then
strError = strError & "<p class=""errorpadleft"">" & Server.HTMLEncode(objASPError.Description) & "</p>"
end if
blnErrorWritten = False
' Only show the Source if it is available and the request is from the same machine as IIS
If objASPError.Source > "" Then
strServername = LCase(Request.ServerVariables("SERVER_NAME"))
strServerIP = Request.ServerVariables("LOCAL_ADDR")
strRemoteIP = Request.ServerVariables("REMOTE_ADDR")
If (strServername = "localhost" Or strServerIP = strRemoteIP) And objASPError.File <> "?" Then
strError = strError & "<p class=""errorpadleft"">" & Server.HTMLEncode(objASPError.File)
If objASPError.Line > 0 Then
strError = strError & ", line " & objASPError.Line
end if
If objASPError.Column > 0 Then
strError = strError & ", column " & objASPError.Column
end if
strError = strError & "</p>"
strError = strError & "<p class=""errorpadleft"">" & Server.HTMLEncode(objASPError.Source) & "</p>"
If objASPError.Column > 0 Then strError = strError & "<p class=""errorpadleft"">" & String((objASPError.Column - 1), "-") & "</p>"
blnErrorWritten = True
End If
End If
If Not blnErrorWritten And objASPError.File <> "?" Then
strError =strError & "<p class=""errorpadleft"">" & Server.HTMLEncode( objASPError.File)
If objASPError.Line > 0 Then
strError =strError & Server.HTMLEncode(", line " & objASPError.Line)
end if
If objASPError.Column > 0 Then
strError =strError & ", column " & objASPError.Column
end if
strError = strError & "</p>"
End If
strError = strError & "<p><strong>Browser Type:</strong></p>"
strError = strError & "<p class=""errorpadleft"">" & Server.HTMLEncode(Request.ServerVariables("HTTP_USER_AGENT")) & "</p>"
strMethod = Request.ServerVariables("REQUEST_METHOD")
If strMethod = "POST" Then
strError =strError & "<p class=""errorpadleft"">POST Data: (" & Request.TotalBytes & " bytes "
If lngPos > 1 Then strError =strError & "?" & Server.HTMLEncode(Left(Request.QueryString, (lngPos - 1)))
strError =strError & ")</p>"
arrError = split(Request.Form,"&")
For i = LBound(arrError) To UBound(arrError)
strError =strError & "<p>" & Server.HTMLEncode(arrError(i)) & "</p>"
Next
End If
strError = strError & _
"<p>" & _
"<strong>User Logon: </strong>" & LOGON_USER & "<br/>" & _
"<strong>User IP: </strong>" & Request.ServerVariables ("REMOTE_ADDR") & "<strong><br/>" & _
"Time: </strong>" & Now() & _
"</p>"
SendMail email_from,email_to,system_name &" 500-100 Error " & LOGON_USER,"<HTML>" & PATH & "<BR><BR>" & replace(strError,"%2F","/") & "</HTML>" ,2
%>
<body>
<div class="errortitle">Your system has encountered an error...</div>
<div class="errorbody">
<div class="errormessage"><%=strError%></div>
</div>
</body>
</html>
Now, in IIS, navigate to the Custom Erros section and scroll down to the 500 error. Edit... this error and select URL as the Message Type. In the URL box, beneath, type /errors/error.asp (remember that the folder should be on the root of your web server [this is usually <drive>\Inetpub\wwwroot] - if you choose to put it elsewhere then this won't work until you resolve the path).
Now try running your pages again and see if you get any ASP error messages. Your page should be redirected to the error.asp page if there is an error.
(Let me know if there are any errors with the code above - I had to mod it on the fly and haven't had chance to test it).

Php mail post stays in sending mode

When i try to send mail with the code the send button stays in "sending" and never changes to "sent". But mail is actuall sent to my mail box...
You can check in site secco.uni.me
Thanks.
The html code of main page:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Sun and Moon Calculations</title>
<link rel="shortcut icon" href="site_icon.png">
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<meta name="robots" content="index,follow">
<meta name="description" content="Calculate local sunrise, sunset, moonrise, moonset and moon illumination with a click on map. Learn your time zone. Great tool for photographers and hunters as well as security forces. ">
<link rel="stylesheet" type="text/css" href="secco.css">
<link href="fancybox/source/jquery.fancybox.css" media="all" type="text/css" rel="stylesheet">
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyD2rBJhT2rjQwA3jVKYrbbElkkm525UabU&sensor=false"></script>
<script type="text/javascript" src="map.js"></script>
<script type="text/javascript" src="time.js"></script>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript" src="fancybox/source/jquery.fancybox.js?v=2.0.6"></script>
</head>
<body>
<img alt="Under Construction" src="ribbon.png" width="132" height="100" style="position: absolute; top: 0; right: 0; border: 0;">
<script src="moon.js"></script>
<center>
<h2>Sun and Moon Calculations</h2>
<div id="bd">
<div id="gmap"></div>
<!--Lat: <span id="lat"></span> Lon: <span id="lon"></span><br/>
Zoom Level: <span id="zoom_level"></span> -->
<div id="expl"><h5>*Click <span style="color:red">red</span> marker for exact coordinates.
Center the map, then hit buttons for calculations. Your feedback is valuable...<h5></div>
</div>
<div id="form">
<form name=calc>
<table border="" cellspacing=5 bordercolor=white frame=void rules=rows>
<tr>
<td>Latitude <td><INPUT size=20 maxLength=10 name=lat>
<td>RAW Offset<td><INPUT readOnly size=35 maxLength=35 name=rawoffset>
<td>Moonrise <td><INPUT readOnly size=20 maxLength=20 name=moonrise>
<tr>
<td>Longitude <td><INPUT size=20 maxLength=20 name=lon>
<td>DST Offset<td><INPUT readOnly size=35 maxLength=35 name=dstoffset>
<td>Moonset<td><INPUT readOnly size=20 maxLength=20 name=moonset>
<tr>
<td>Zoom Level<td><INPUT readOnly size=20 maxLength=20 name=zl>
<td>Time Zone ID <td><INPUT readOnly size=35 maxLength=35 name=timezoneid>
<td>Moon Phase<td><INPUT readOnly size=20 maxLength=20 name=moonphase>
<tr>
<td>This Day <td><INPUT readOnly size=20 maxLength=20 name=thisday>
<td>Time Zone <td><INPUT readOnly size=35 maxLength=35 name=timezone>
<tr>
<td>Timestamp <td><INPUT readOnly size=20 maxLength=20 name=timestamp>
</table>
</form>
</div>
<input type="button" onclick="setLocation()" value="Set Location">
<input type="button" onclick="compute()" value="Moon Calculation">
<input type="button" onclick="sun()" value="Sun Calculation"><br>
</center>
<!-- Feedback mail post section-->
<!-- hidden inline form -->
<div id="inline">
<h2>Send us a Message</h2>
<form id="contact" name="contact" action="#" method="post">
<label for="email">Your E-mail</label>
<input type="email" id="email" name="email" class="txt">
<br>
<label for="msg">Enter a Message</label>
<textarea id="msg" name="msg" class="txtarea"></textarea>
<button id="send">Send E-mail</button>
</form>
</div>
<script type="text/javascript" src="mailpost.js"></script>
<!-- BOTTOM STUFF -->
<div id="bottom">
<script language="JavaScript">
initdate();
var count = "secco"; // Change Your Account?
var type = "war2orc"; // Change Your Counter Image?
var digits = "7"; // Change The Amount of Digits on Your Counter?
var prog = "hit"; // Change to Either hit/unique?
var statslink = "no"; // provide statistical link in counter yes/no?
var sitelink = "yes"; // provide link back to our site;~) yes/no?
var cntvisible = "yes"; // do you want counter visible yes/no?
</script>
<!-- START DO NOT TAMPER WITH ANYTHING ELSE BELOW THIS LINE FOR YOUR WEBTV & UNIX VISITORS -->
<img src="jquery-logo.png" width="70" height="15" style="position: relative;width:95% text-align:left;top:3px; left:60px;"/>
<img src="google-maps-api-v3.png" width="70" height="15" style="position: relative;width:95% text-align:left;top:3px; left:-90px;"/>
<a class = "modalbox" href="#inline"><img src="icon_mailto.gif" style="position: relative;width:95% text-align:right;top:3px; left:-8px;"/></a>
<script language="JavaScript" src="http://005.free-counters.co.uk/count-072.js">
</script>
<noscript>
<a href="http://www.free-counters.co.uk" target="_blank">
<img src="http://005.free-counters.co.uk/count-072.pl?count=secco&cntvisible=no&mode=noscript" style="position: absolute;" alt="Free Counters" title="Free Counters" border="0">
</a>The following text will not be seen after you upload your website,
please keep it in order to retain your counter functionality
<br>Trackers<br> Counter Help<br>
</noscript>
<!-- END DO NOT TAMPER WITH ANYTHING ELSE ABOVE THIS LINE FOR YOUR WEBTV & UNIX VISITORS -->
</div>
</CENTER>
</body>
</html>
My mailpost.js file:
function validateEmail(email) {
var reg = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return reg.test(email);
}
$(document).ready(function() {
$(".modalbox").fancybox();
$("#contact").submit(function() { return false; });
$("#send").on("click", function(){
var emailval = $("#email").val();
var msgval = $("#msg").val();
var msglen = msgval.length;
var mailvalid = validateEmail(emailval);
if(mailvalid == false) {
$("#email").addClass("error");
}
else if(mailvalid == true){
$("#email").removeClass("error");
}
if(msglen < 4) {
$("#msg").addClass("error");
}
else if(msglen >= 4){
$("#msg").removeClass("error");
}
if(mailvalid == true && msglen >= 4) {
// if both validate we attempt to send the e-mail
// first we hide the submit btn so the user doesnt click twice
$("#send").replaceWith("<em>sending...</em>");
$.ajax({
type: 'POST',
url: 'sendmessage.php',
data: $("#contact").serialize(),
success: function(data) {
if(data == "true") {
$("#contact").fadeOut("fast", function(){
$(this).before("<p><strong>Success! Your feedback has been sent, thanks :)</strong></p>");
setTimeout("$.fancybox.close()", 1000);
});
}
}
});
}
});
});
And sendmessage.php file
<?php
$sendto = "mail#hotmail.com";
$usermail = $_POST['email'];
$content = nl2br($_POST['msg']);
$subject = "New Feedback Message";
$headers = "From: " . strip_tags($usermail) . "\r\n";
$headers .= "Reply-To: ". strip_tags($usermail) . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html;charset=utf-8 \r\n";
$msg = "<html><body style='font-family:Arial,sans-serif;'>";
$msg .= "<h2 style='font-weight:bold;border-bottom:1px dotted #ccc;'>New User Feedback</h2>\r\n";
$msg .= "<p><strong>Sent by:</strong> ".$usermail."</p>\r\n";
$msg .= "<p><strong>Message:</strong> ".$content."</p>\r\n";
$msg .= "</body></html>";
if(#mail($sendto, $subject, $msg, $headers)) {
echo "true";
} else {
echo "false";
}
?>
You set the text to "sending..." with this:
$("#send").replaceWith("<em>sending...</em>");
But you never set it to anything else after that. So, it stays put. If you want to change it, you can add a line to your success function, like this:
success: function(data) {
if(data == "true") {
$("#contact").fadeOut("fast", function(){
$(this).before("<p><strong>Success! Your feedback has been sent, thanks :)</strong></p>");
setTimeout("$.fancybox.close()", 1000);
});
$("#send").replaceWith("<em>sent!</em>"); // This is the line to add.
}
}
PHP Code
if(#mail($sendto, $subject, $msg, $headers)) {
echo "1";
} else {
echo "0";
}
AJAX code:
$.ajax({
type: 'POST',
url: 'sendmessage.php',
data: $("#contact").serialize(),
success: function(data) {
if(data == 1) {
$("#contact").fadeOut("fast", function(){
$(this).before("<p><strong>Success! Your feedback has been sent, thanks :)</strong></p>");
setTimeout("$.fancybox.close()", 1000);
});
}
}
});
I changed the true and false echo responses to 0 and 1.
I suppose there is a problem about js code about fetching the return from php code. Anyway the code runs as it is supposed to. Thanks.
Change this line
if(#mail($sendto, $subject, $msg, $headers)) {
to
if(mail($sendto, $subject, $msg, $headers)) {
Additionally, I recommend using die("true"); or removing the closing PHP tag otherwise you risk having a confusing new line at the end of the file that can potentially produce undesired results.

PHP page with Javascript

this is my main.php
<?php
session_start();
if (!isset($_SESSION['username']))
{
header('Location: index.php');
}
include("connection/config.php");
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>TOM ELOY CONVENIENCE STORE</title>
<link rel="stylesheet" href="css/design.css" type="text/css" />
<link href="css/style.css" media="screen" rel="stylesheet" type="text/css" />
<link href="css/iconic.css" media="screen" rel="stylesheet" type="text/css" />
<script></script>
</head>
<body>
<div id="wrapper">
<!--header link -->
<div id="sitename" class="clear">
<?php include_once("header.php"); ?>
</div>
<!--menu navigation -->
<div class="wrap">
<nav>
<?php include_once("menunav.php"); ?>
<div class="clearfix"></div>
</nav>
</div>
<div id="body-wrapper">
<!-- body -->
<div id="body" class="clear">
<div class="clear">
<div id="content"></div>
<!-- script for pages -->
<script type="text/javascript" src="js/general.js"></script>
<script src="js/main.js"></script>
</div>
</div>
</div>
<!--footer link -->
<div id="footer" align="center">
<?php include_once("footer.php"); ?>
</div>
</div>
</body>
</html>
this is my javascript the main.js
$(document).ready(function () {
$('#content').load('main2.php');
$('ul#nav li a').click(function() {
var page = $(this).attr('href');
$('#content').load( page + '.php');
return false;
});
});
this is my supplierprofile.php
<?php
session_start();
if (!isset($_SESSION['username']))
{
header('Location: index.php');
}
include("connection/config.php");
?><html>
<head>
<link rel="stylesheet" href="css/styles.css" type="text/css" />
<!-- autorefresh of the table -->
<script type="text/javascript">
function Ajax()
{
var
$http,
$self = arguments.callee;
if (window.XMLHttpRequest) {
$http = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
$http = new ActiveXObject('Msxml2.XMLHTTP');
} catch(e) {
$http = new ActiveXObject('Microsoft.XMLHTTP');
}
}
if ($http) {
$http.onreadystatechange = function()
{
if (/4|^complete$/.test($http.readyState)) {
document.getElementById('ReloadThis').innerHTML = $http.responseText;
setTimeout(function(){$self();}, 0);
}
};
$http.open('GET', 'supplierprofiletable.php' + '?' + new Date().getTime(), true);
$http.send(null);
}
}
</script>
</head>
<!-- content2 -->
<div id="content">
<p id="bcp">Browse Supplier Profile</p><br><br>
<ul id="nav">
<li>
<a id="abutton">PRINT</a>
<a id="abutton" href="addspform">ADD SUPPLIER</a>
</li>
</ul>
<!-- autorefresh of the table -->
<script type="text/javascript">
setTimeout(function() {Ajax();}, 0);
</script>
<!-- table to be refresh -->
<div id="ReloadThis"><?php include_once("supplierprofiletable.php"); ?></div>
</div>
<? -- script for pages --?>
<script type="text/javascript" src="js/general.js"></script>
<script src="js/submain.js"></script>
this is the supplieprofiletable.php
<table id="spvt" align="center">
<tr>
<th id="spvth">SUPPLIER NAME</th>
<th id="spvth">TERMS DAY</th>
<th id="spvth">VAT</th>
<th id="spvth">MODIFY</th>
<th id="spvth">DELETE</th>
</tr>
<?php
include("connection/config.php");
$sql = "select * from SUPPLIER_PROFILE ORDER BY SP_NAME";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
echo "<tr id='spvtr'>";
echo "<td id='spvtd' style='text-align:left;'>" . $row['SP_NAME'] . "</td>";
echo "<td id='spvtd'>" . $row['SP_TERMS_DAY'] . "</td>";
echo "<td id='spvtd'>" . $row['SP_VAT'] . "</td>";
echo "<td id='spvtd'>MODIFY SUPPLIER</td>";
echo "<td id='spvtd'>DELETE SUPPLIER</td>";
echo "</tr>";
}
?>
this is the addspform.php
<head>
<link rel="stylesheet" href="css/design.css" type="text/css" />
<link href="style.css" media="screen" rel="stylesheet" type="text/css" />
<link href="iconic.css" media="screen" rel="stylesheet" type="text/css" />
<script type = "text/javascript">
<!--
var run1 = function()
{
var x1 = document.addsp.spname.value.length;
if(x1 == 0)
{
alert("SUPPLIER NAME SHOULD NOT BE EMPTY");
return(false);
}
else
return(true);
}
var run2 = function()
{
var x1 = document.addsp.spadd.value.length;
if(x1 == 0)
{
alert("SUPPLIER ADDRESS SHOULD NOT BE EMPTY");
return(false);
}
else
return(true);
}
var run3 = function()
{
var x1 = document.addsp.sptd.value.length;
if(x1 == 0)
{
alert("SUPPLIER TERMS DAY SHOULD NOT BE EMPTY");
return(false);
}
else
return(true);
}
var run4 = function()
{
var x1 = document.addsp.spvat.value.length;
if(x1 == 0)
{
alert("SUPPLIER VAT SHOULD NOT BE EMPTY");
return(false);
}
else
return(true);
}
function checkall()
{
if(run1() == false)
{
addsp.spname.focus();
return(false);
}
if(run2() == false)
{
addsp.spadd.focus();
return(false);
}
if(run3() == false)
{
addsp.sptd.focus();
return(false);
}
if(run4() == false)
{
addsp.spvat.focus();
return(false);
}
if(/^[0-9]+$/i.test(addsp.sptd.value) == false)
{
alert("invalid Terms Day");
addsp.sptd.focus();
return(false);
}
else
{
return(true);
}
}
-->
</script>
</head>
<!-- body -->
<div id="content">
<div class="clear">
<p id="bcp">ADD Supplier</p><br><br>
<ul id="nav">
<li>
<a id="abutton" href="supplierprofile">VIEW SUPPLIER</a>
</li>
</ul>
<br>
<form id="aft" name ="addsp" action = "addsp.php" method = "post" onsubmit = "return checkall();">
<fieldset>
<legend>SUPPLIER FORM (NEW)</legend>
<table>
<tr><td>
<span style = "width: 50px;" >Supplier Name</span>
</td><td>
<input size="100" type = "text" name = "spname" onkeyup = "this.value = this.value.toUpperCase();" value =""/><br />
</td></tr>
<tr><td>
<span style = "width: 100px;">Address</span>
</td><td>
<input size="100" type = "text" name = "spadd" value = "" /><br />
</td></tr>
<tr><td>
<span style = "width: 120px;">Telephone No.</span>
</td><td>
<input size="100" type = "text" name = "sptelno" value = "" /><br />
</td></tr>
<tr><td>
<span style = "width: 100px;">Terms Day</span>
</td><td>
<input size="100" type = "text" name = "sptd" value = "" /><br />
</td></tr>
<tr><td>
<span style = "width: 100px;">VAT</span>
</td><td>
<select name="spvat">
<option id="o1"> </option>
<option id="o2">INCLUSIVE</option>
<option id="o3">EXCLUSIVE</option>
</select>
</td></tr>
<tr><td></td><td>
<input class="afbutton" type = "submit" name = "ADD" value = "ADD" id="ADD"/>
</td></tr>
<tr><td>
</table>
</fieldset>
</form>
</div>
</div>
<? -- script for pages --?>
<script type="text/javascript" src="js/general.js"></script>
<script src="js/submain.js"></script>
this is the addsp.php
<html>
<head>
<script type="text/javascript">
<!--
function direct()
{
window.alert("Suppler has been added");
w = window || document
w.location.reload();
}
-->
</script>
</head>
<body>
<?php
include("connection/config.php");
$spname = $_POST['spname'];
$spadd = $_POST['spadd'];
$sptelno = $_POST['sptelno'];
$sptd = $_POST['sptd'];
$spvat = $_POST['spvat'];
if(!$_POST['ADD'])
{
echo "Please fill out the form";
header('Location: addspform.php');
}
else
{
$query = "SELECT * FROM supplier_profile WHERE sp_name = '$spname'";
$result = mysql_query($query)or die(mysql_error());
$counter = 0;
while($supplier = mysql_fetch_array($result))
{
$counter = $counter + 1;
}
if($counter == 0)
{
mysql_query("INSERT INTO supplier_profile(`SP_NAME`,`SP_ADDRESS`, `SP_TELNO`,`SP_VAT`,`SP_TERMS_DAY`)
VALUES('$spname','$spadd','$sptelno','$spvat','$sptd')") or die(mysql_error());
echo '<script type="text/javascript">
direct();
</script>';
}
}
?>
</body>
sorry about the previous information. Now if i click the add button to the addspform.php all i want after the javascript that pop-up and click ok is to direct the supplierprofile.php inside in the main.php
make your addsp.php like this
<?php
session_start();
include("connection/config.php");
$spname = $_POST['spname'];
$spadd = $_POST['spadd'];
$sptelno = $_POST['sptelno'];
$sptd = $_POST['sptd'];
$spvat = $_POST['spvat'];
if(!$_POST['ADD'])
{
$_SESSION['msg'] = "Please fill form";
header('Location: addspform.php');
exit;
}
else
{
$query = "SELECT * FROM supplier_profile WHERE sp_name = '$spname'";
$result = mysql_query($query)or die(mysql_error());
$counter = 0;
while($supplier = mysql_fetch_array($result))
{
$counter = $counter + 1;
}
if($counter == 0)
{
mysql_query("INSERT INTO supplier_profile(`SP_NAME`,`SP_ADDRESS`, `SP_TELNO`,`SP_VAT`,`SP_TERMS_DAY`)
VALUES('$spname','$spadd','$sptelno','$spvat','$sptd')") or die(mysql_error());
$_SESSION['msg'] = "form has been submitted successfully";
header('Location: addspform.php');
exit;
}
}
?>
you can use header function of php to redirect on some page. use session as msg and print it on your form page as follows
<?php
session_start();
if(isset($_SESSION['msg']))
{
echo $_SESSION['msg'];
unset($_SESSION['msg']);
}
?>
<form id="aft" name ="addsp" action = "addsp.php" method = "post" onsubmit = "return checkall();">
<fieldset>
<legend>SUPPLIER FORM (NEW)</legend>
<table>
<tr><td>
<span style = "width: 50px;" >Supplier Name</span>
</td><td>
<input size="100" type = "text" name = "spname" onkeyup = "this.value = this.value.toUpperCase();" value =""/><br />
</td></tr>
<tr><td>
<span style = "width: 100px;">Address</span>
</td><td>
<input size="100" type = "text" name = "spadd" value = "" /><br />
</td></tr>
<tr><td>
<span style = "width: 120px;">Telephone No.</span>
</td><td>
<input size="100" type = "text" name = "sptelno" value = "" /><br />
</td></tr>
<tr><td>
<span style = "width: 100px;">Terms Day</span>
</td><td>
<input size="100" type = "text" name = "sptd" value = "" /><br />
</td></tr>
<tr><td>
<span style = "width: 100px;">VAT</span>
</td><td>
<select name="spvat">
<option id="o1"> </option>
<option id="o2">INCLUSIVE</option>
<option id="o3">EXCLUSIVE</option>
</select>
</td></tr>
<tr><td></td><td>
<input class="afbutton" type = "submit" name = "ADD" value = "ADD" id="ADD"/>
</td></tr>
<tr><td>
</table>
</fieldset>
</form>
redefine direct as:
function direct(){
window.alert("Suppler has been added");
w = window || document
w.location.reload();
}
Just do a redirect in addsp.php
if (test){
//do something
echo '<META HTTP-EQUIV="Refresh" Content="0; URL=yourpage.php">';//This causes the browser to open the new page after 0 seconds, i.e immediately.
} else {
return false;
}
http://php.about.com/od/learnphp/ht/phpredirection.htm
//addsp.php
function direct()
{
window.alert("Suppler has been added");
document.location.href = "main.php?page='pagenamewhichlastloaded'&redirect=1";
}
//main.php
$(function(){
if($("#redirect").val() == 1){
var page = $("#page").val();
$('#content').load( page + '.php');
}
$('ul#nav li a').click(function() {
var page = $(this).attr('href');
$('#content').load( page + '.php');
return false;
});
});
<div id="content"></div>
<input type="hidden" id="page" value="<?php if(isset($_POST['page'])){ echo $_POST['page']; }?>" />
<input type="hidden" id="redirect" value="<?php if(isset($_POST['redirect'])){ echo $_POST['redirect']; }?>" />

Categories