Multi Step Form JavaScript Validation to prevent proceeding to other steps - php

The Problem
I created a multi step form, and yes the javascript and all is already functional but i have this one problem. also the user has 2 options of navigating trough the form, either using the next button or directly clicking the steps at the header. let's say the user has a form with 3 groups, ergo he has 3 steps. In my code he can't move to step 2 when he is currently in step 1 and required fields are empty, same applies with the next button. now the problem is that if he is in step 1 and he clicks step 3 he is able to proceed to it even though there are required fields that are empty in between them. I am already at lost on how do I trap this bug.
The Format of the groups
The groups are divided by table ergo 1 group is under 1 table.
How I formatted my JS
I formatted my JS by passing 3 values to it. the first value is the current category name, the second is the category list, the third is the next category after the current.
The first value is used to check whether all the required fields are filled before moving to the next step, the array is there to hide all other categories except the third value "this is done when the user clicks the next step", while the third value is used for displaying the next step.
Preview
http://screencast.com/t/QwSVFolb
The HTML
<li>step1</li>
<li>step2</li>
<li>step3</li>
<table id ="cat1"></table>
<table id ="cat2"></table>
<table id ="cat3"></table>
The JS
function dispFields2(a, b, c)
{
var valid2;
var blanks2 = Array();
var email_reg2 = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
var myVal2 = $('#'+c).find('input.required').map(function() {
return $(this).val();
}).get().join(',');
var myTitle2 = $('#'+c).find('input.required').map(function() {
return $(this).attr("title");
}).get().join(',');
var error_form2 = myVal2.split(',');
var error_title2 = myTitle2.split(',');
var errorlength2 = error_form2.length;
for(x=0;x<errorlength2;x++)
{
if(error_form2[x] == '')
{
if(myVal2 == '')
{
valid2 = true;
}
else
{
blanks2[x] = "Required - "+error_title2[x];
valid2 = false;
}
}
else
{
if(error_title2[x] == 'Email')
{
if(email_reg2.test(String(error_form2[x]).toLowerCase())==false){
blanks2[x] = error_title2[x]+" - Should be valid email";
valid2 = false;
}
}
else
{
if(blanks2 == '')
{
valid2 = true;
}
}
}
}
var requiredS2 = blanks2.toString();
var nblank2 = requiredS2.split(',').join("\n");
if(valid2 != true)
{
alert("Please review:\n\n"+nblank2);
document.getElementById(c).style.display = "";
document.getElementById(a).style.display = "none";
}
else
{
var ssplit = b.split(',');
var fieldlength = ssplit.length;
var limit;
for(i=0;i<fieldlength;i++)
{
if(a == ssplit[i])
{
limit = 1 + i;
document.getElementById(a).style.display = "";
document.getElementById("tcont").style.display = "";
document.getElementById(i).style.color = "#FF7300";
if(limit == fieldlength)
{
document.getElementById("tbutton").style.display = "";
}
else
{
document.getElementById("tbutton").style.display = "none";
}
}
else
{
document.getElementById(ssplit[i]).style.display = "none";
document.getElementById(ssplit[i]).style.color = "";
document.getElementById(i).style.color = "";
}
}
if(a == "default")
{
document.getElementById("captchas").style.display = "";
}
else
{
document.getElementById("captchas").style.display = "none";
}
}
}
Thank you.

Have the button for step 3 begin disabled, and only enable it when the user is on step 2. If the user moves back to step 1 from step 2, disable it again.

Related

Store data to database continuously without pressing 'Submit' og 'Next'

I am a student who will conduct an experiment online.
The participants go to a website (a more complex version of this one: http://auforskning.rf.gd/TEST2.php) which will track a) which buttons they press and b) how long time the buttons are pushed. This is to track how many seconds each participant spend on reading the information.
However, there is one problem: The participants have to press 'Submit' or 'Next' in order to store the informations. If they read the information behind the boxes (as intended) and just close the window, the data will be lost.
Is there a way to store data continuously, so that the data isn't lost if they just close the window?
mlweb.js-file:
dtNewDate = new Date();
starttime = dtNewDate.getTime(); // abs. starttime of experiment
// set vars for delay
prevtime = 0; // memory in timefunction to compensate for delay
dtime=0;
prevCell = -1; // delay lag memory (-1 means first cell is not delayable
loaded = false; // flag to test whether page has been loaded 9is set to true in reorder
boxOpen = false; // flag to test whether box is already open (using in showCont and hideCont)
chkFrm = false // flag to test whether additional form elements have to be checked on submission
warningTxt = "Some questions have not been answered. Please answer all questions before continuing!";
CBpreset = false; // flag to set CB order fixed by a matrix on forehand: default is set to false
prevfieldname = ""; // default for switching clicks
transpImg = new Image()
tempImg = new Image()
previousSrc="";
// default values
mlweb_outtype="XML";
mlweb_fname=0;
masterCond = 1; // number of master conditions
randomOrder = false; // force randomize of counterbalancing order
subject="";
evtOpen = 0;
evtClose = 0;
tmDirectStart = false;
tmTimeUp = false;
tmActive = false;
tmCurTime = 0;
// get source transparant image
transpImg.src="transp.gif"
function abc_num(str)
{
out=str.toUpperCase().charCodeAt(0)-65;
return out
}
function fac(x)
{
// Faculty: x!=x(x-1)...1
var outp=1;
for (var i=1; i<=x; i++)
{outp=outp*i}
return outp
}
function CountBal(subjnr, num)
{
// counterbalance based on subj number.
// first subject is 0
// Num is number of options to counterbalance
// (number of orders is Num!)
var numOrd=fac(num);
start = subjnr - numOrd*Math.floor((subjnr-1)/numOrd)
orderstr=""
for (var i=0;i<num;i++)
{orderstr+=i.toString()}
outstr=""
for (var i=num; i>0; i--)
{
var den=fac(i-1);
pos = Math.floor((start-1)/den)+1
outstr+=orderstr.charAt(pos-1)+","
orderstr = orderstr.substring(0,pos-1)+orderstr.substr(pos)
start=start-(pos-1)*den
}
outstr=outstr.substr(0,outstr.length-1)
return outstr.split(",")
}
function ExpMatrix(M)
{ // expand data matrices
var Mrows=M.split("`");
var outM = new Array();
for (rowcount=0;rowcount<Mrows.length;rowcount++)
{
outM[rowcount]=Mrows[rowcount].split("^")
}
return outM;
}
function ExpRow(M)
{ // expand data vectors
var outM = new Array();
outM = M.split("^")
return outM;
}
function btnHover(loc,act)
{
if (act=='out')
{
if (loc.className.indexOf(" ")>0) {tempstyle= loc.className.substring(0,loc.className.indexOf(" "));}
}
else
{tempstyle=loc.className + ' btnhov';}
loc.className=tempstyle;
}
function timefunction(event,name,value) {
// Record proc data in form element
mlweb_form=document.forms[mlweb_fname].elements['procdata']
dtNewDate = new Date();
eventtime = dtNewDate.getTime();
var curtime = eventtime-starttime-dtime; // dtime is to compensate for delay time (failed openings have negative time!
// if (prevtime>curtime) {curtime=prevtime;} else {prevtime=curtime}; // check with previous event time: if smaller, then delay was not finished: set curtime to prevtime so event has duration 0;
dtime=0; // reset dtime
if (mlweb_outtype=="XML")
{
var str="<eventblock><event>"+event+"</event><name>"+name+"</name><value>"+value+"</value><time>"+curtime+"</time></eventblock>";
var headerstr="<?xml version=1.0?>"
}
else
{
var str="\""+event+"\",\""+name+"\",\""+value+"\",\""+curtime+"\"\n"
var headerstr="\"event\",\"name\",\"value\",\"time\"\n"
};
if(mlweb_form.value=='')
{
mlweb_form.value=headerstr;
}
mlweb_form.value+=str;
if (event=="onload") {reorder();}
return true;
}
// convert event to eventdata and call save function
function RecordEventData(objActionElement, objEvent)
{
var strName, strEventType, strFormValue;
strName = objActionElement.name;
strFormValue = (objActionElement.value) ? objActionElement.value : "";
strEventType = objEvent.type;
//call timefunction
timefunction(strEventType,strName, strFormValue)
return false;
}
function checkForm(formHandle)
{
if (chkFrm)
{
noElm = document.forms[mlweb_fname].elements.length;
var filled=true;
for (i=0;i<noElm;i++)
{
elemHandle = document.forms[0].elements[i];
if (elemHandle.type=="hidden") {continue};
if (elemHandle.value=="") {filled = false; break};
if (elemHandle.type=="select-one") {if (elemHandle.options[elemHandle.selectedIndex].value=="") {filled = false; break};}
if (elemHandle.type=="radio") // procedure to check radio buttons
{
radio_name=elemHandle.name; // get name (needed to retrieve length)
// get length of radio button group
r_length = eval("document.forms[0]."+radio_name).length
for (ri=0;ri<r_length;ri++) // check each button and break loop if checked button was found
{ radioHandle = document.forms[0].elements[i+ri];
if (radioHandle.checked) {filled=true; break} else {filled=false};
}
if (filled) {i=i+r_length-1; continue} else {break}; // if checked button found; continue
// else break loop and show warning
}
}
if (!filled) {alert(warningTxt);timefunction('submit','submit','failed');return false};
}
if ((chkchoice=="nobuttons") | !chkFrm) {return true;}
if (chkchoice==true) {timefunction('submit','submit','succeeded');return true} else {alert(warningTxt);timefunction('submit','submit','failed');return false};
}
function objElem(name,value)
{
this.name=name
this.value=value
}
function ShowCont(fieldname, objEvent)
{
if (!loaded) {return;} // do not open boxes when page is loading
if (!tmDirectStart & tmActive & tmCurTime==0) {startTmBar();}
if (tmTimeUp) {return;}
// check if a click on a link (A) occurs. this happens for example
// when a mlweb A link gets a focus (due to clicking the box) and a subject presses enter
// this is to prevent enters from generating events when in click (rather than mouseover) mode
if (objEvent.srcElement)
{
if (objEvent.srcElement.nodeName=="A") {return}
}
else if (objEvent.target)
{
if (objEvent.target.nodeName=="A") {return}
}
var row = abc_num(fieldname);
var col = parseInt(fieldname.substr(1));
thisElem = new objElem
// check if open cell should be recorded
if ((statecont[RowOut[row]][ColOut[col]]=="0") & !(recOpenCells)) {return;}
if (boxOpen) {return;}
if (evtClose<3) {boxOpen = true;} //set flag to show box is open
// retrieve tagname and txt for this cell
thisElem.name = tagcont[RowOut[row]][ColOut[col]];
thisElem.value = txtcont[RowOut[row]][ColOut[col]];
RecordEventData(thisElem, objEvent);
if (document.getElementById)
{
// IE6/NS6>/Mozilla
HandleTxt = document.getElementById(fieldname+"_txt");
HandleBox = document.getElementById(fieldname+"_box");
}
else if (document.all)
{
//IE4/5
HandleTxt=eval("document.all['"+fieldname+"_txt"+"']");
HandleBox=eval("document.all['"+fieldname+"_box"+"']");
}
// delay
currCell = -1;
for (var i=0;i<Dlist.length;i++)
{if (tagcont[RowOut[row]][ColOut[col]]==Dlist[i]) {currCell=i;break;}}
if ((prevCell!=-1)&(currCell!=-1)) {dtime = DTimes[currCell][prevCell];} else {dtime=0};
prevCell = currCell;
//HandleTxt.style.visibility='visible';HandleBox.style.visibility='hidden';
delay=window.setTimeout("HandleTxt.style.visibility='visible';HandleBox.style.visibility='hidden';",dtime) //make image transparant
}
function HideCont(fieldname,objEvent)
{
if (!loaded) {return;} // do not open boxes when page is loading
if (!boxOpen) {return;} // do not close boxes that are not open...
window.clearTimeout(delay);
var row = abc_num(fieldname);
var col = parseInt(fieldname.substr(1));
// check if open cell should be recorded
if ((statecont[RowOut[row]][ColOut[col]]=="0") & !(recOpenCells)) {return;}
boxOpen = false; // set tag to show that box is closed again
thisElem = new objElem;
thisElem.name = tagcont[RowOut[row]][ColOut[col]];
// save procesdata
RecordEventData(thisElem, objEvent)
if (document.getElementById)
{
// IE6/NS6>/Mozilla
HandleTxt = document.getElementById(fieldname+"_txt");
HandleBox = document.getElementById(fieldname+"_box");
}
else if (document.all)
{
//IE4/5
HandleTxt=eval("document.all['"+fieldname+"_txt"+"']");
HandleBox=eval("document.all['"+fieldname+"_box"+"']");
}
HandleTxt.style.visibility='hidden';HandleBox.style.visibility='visible';
}
function SwitchCont(fieldname, objEvent)
{
// special function for clicking tasks
if (!loaded) {return;} // do not open boxes when page is loading
if (!tmDirectStart & tmActive & tmCurTime==0) {startTmBar();}
if (tmTimeUp) {return;}
// check if a click on a link (A) occurred. this happens for example
// when a mlweb A link gets a focus (due to clicking the box) and a subject presses enter
// this is to prevent enters from generating events when in click (rather than mouseover) mode
if (objEvent.srcElement)
{
if (objEvent.srcElement.nodeName=="A") {return}
}
else if (objEvent.target)
{
if (objEvent.target.nodeName=="A") {return}
}
thisElem = new objElem
var row = abc_num(fieldname);
var col = parseInt(fieldname.substr(1));
// check if open cell should be recorded
if ((statecont[RowOut[row]][ColOut[col]]=="0") & !(recOpenCells)) {return;}
if (fieldname==prevfieldname)
{
// just close current box if box is same as previous
window.clearTimeout(delay);
var row = abc_num(fieldname);
var col = parseInt(fieldname.substr(1));
thisElem.name = tagcont[RowOut[row]][ColOut[col]];
// save procesdata
RecordEventData(thisElem, objEvent)
if (document.getElementById)
{
// IE6/NS6>/Mozilla
HandleTxt = document.getElementById(fieldname+"_txt");
HandleBox = document.getElementById(fieldname+"_box");
}
else if (document.all)
{
//IE4/5
HandleTxt=eval("document.all['"+fieldname+"_txt"+"']");
HandleBox=eval("document.all['"+fieldname+"_box"+"']");
}
HandleTxt.style.visibility='hidden';HandleBox.style.visibility='visible';
prevfieldname="";
}
else
{
if ((prevfieldname!="")&(evtClose==1))
{
// first close prev box if box is not same as previous
window.clearTimeout(delay);
var row = abc_num(prevfieldname);
var col = parseInt(prevfieldname.substr(1));
thisElem.name = tagcont[RowOut[row]][ColOut[col]];
// save procesdata
RecordEventData(thisElem, objEvent)
if (document.getElementById)
{
// IE6/NS6>/Mozilla
HandleTxt = document.getElementById(prevfieldname+"_txt");
HandleBox = document.getElementById(prevfieldname+"_box");
}
else if (document.all)
{
//IE4/5
HandleTxt=eval("document.all['"+prevfieldname+"_txt"+"']");
HandleBox=eval("document.all['"+prevfieldname+"_box"+"']");
}
HandleTxt.style.visibility='hidden';HandleBox.style.visibility='visible';
}
if ((prevfieldname=="")|(evtClose==1))
{
// only if any box may be opened or there as no previous box open, show content
var row = abc_num(fieldname);
var col = parseInt(fieldname.substr(1));
thisElem.name = tagcont[RowOut[row]][ColOut[col]];
thisElem.value = txtcont[RowOut[row]][ColOut[col]];
RecordEventData(thisElem, objEvent);
if (document.getElementById)
{
// IE6/NS6>/Mozilla
HandleTxt = document.getElementById(fieldname+"_txt");
HandleBox = document.getElementById(fieldname+"_box");
}
else if (document.all)
{
//IE4/5
HandleTxt=eval("document.all['"+fieldname+"_txt"+"']");
HandleBox=eval("document.all['"+fieldname+"_box"+"']");
}
// delay
currCell = -1;
for (var i=0;i<Dlist.length;i++)
{if (tagcont[RowOut[row]][ColOut[col]]==Dlist[i]) {currCell=i;break;}}
if ((prevCell!=-1)&(currCell!=-1)) {dtime = DTimes[currCell][prevCell];} else {dtime=0};
prevCell = currCell;
//HandleTxt.style.visibility='visible';HandleBox.style.visibility='hidden';
delay=window.setTimeout("HandleTxt.style.visibility='visible';HandleBox.style.visibility='hidden';",dtime) //make image transparant
prevfieldname=fieldname;
}
}
}
function recChoice(eventname ,name, value)
{
chkchoice = true;
timefunction(eventname, name, value);
if (document.forms[mlweb_fname].choice) {document.forms[mlweb_fname].choice.value = name;}
if (btnType=="button")
{
for (i=0;i<btnTxt.length;i++)
{
if (btnFlg==1) {btnNum = ColOut[i]} else {btnNum = RowOut[i]};
HandleBut = eval("document.forms['"+mlweb_fname+"']."+btnTag[btnNum]);
if (btnTag[btnNum]==name) {HandlePressed = HandleBut};
if (btnState[btnNum]=="1") {HandleBut.className = 'btnStyle';}
}
HandlePressed.className='pressedStyle btnHov';
}
}
function loadMatrices()
{
// get settings data from script in body
txtcont = ExpMatrix(txt);
statecont = ExpMatrix(state);
tagcont = ExpMatrix(tag);
boxcont = ExpMatrix(box);
WidthCol = ExpRow(W_Col);
HeightRow = ExpRow(H_Row);
DTimes = ExpMatrix(delay);
CountCol = ExpRow(CBCol);
CountRow = ExpRow(CBRow);
btnTxt = ExpRow(btntxt);
btnTag = ExpRow(btntag);
btnState = ExpRow(btnstate);
// new in version 99.2: CB preset matrix
if (CBpreset) {
CBorder = ExpMatrix(CBord);
}
ColOut = new Array();
for (var i=0; i<CountCol.length; i++)
{ColOut[i]=i;}
RowOut = new Array();
for (var i=0; i<CountRow.length; i++)
{RowOut[i]=i;}
Dlist = new Array();
for (j=0;j<RowOut.length;j++)
{
for (i=0;i<ColOut.length;i++)
{
if (statecont[j][i]=="1") {Dlist[Dlist.length]=tagcont[j][i];}
}
}
}
function reorder()
{
// if referer present (or other php/asp code) then get current hit number
if (document.cookie.indexOf("mlweb_subject=")!=-1)
{
subjstr=document.cookie;
subject=subjstr.substr(subjstr.indexOf("mlweb_subject=")+14);
}
if (document.cookie.indexOf("mlweb_condnum=")!=-1)
{
subjstr=document.cookie;
subjnr=parseInt(subjstr.substr(subjstr.indexOf("mlweb_condnum=")+14));
subjtype = "cookie";
//alert(subjnr + " " + subjtype);
}
else
{
if (typeof ref_cur_hit!="undefined")
{subjnr = ref_cur_hit; subjtype = "header"}
else
{
subjnr=-1; subjtype = "random";
}
}
// if subj nr turns out to be not a number, or randomizer is set to true then set it to randomize
if (isNaN(subjnr)|randomOrder) {subjnr=-1; subjtype = "random";}
if (document.forms[mlweb_fname].condnum) {document.forms[mlweb_fname].condnum.value = subjnr;}
if (document.forms[mlweb_fname].expname) {document.forms[mlweb_fname].expname.value = expname;}
if (document.forms[mlweb_fname].nextURL) {document.forms[mlweb_fname].nextURL.value = nextURL;}
if (document.forms[mlweb_fname].subject) {document.forms[mlweb_fname].subject.value = subject;}
if (document.forms[mlweb_fname].to_email) {document.forms[mlweb_fname].to_email.value = to_email;}
if (CBpreset)
{
if (subjnr==-1) {subjnr=Math.floor(Math.random()*CBorder.length)}
// CB order is preset in a matrix
curord = Math.floor(subjnr/masterCond) % CBorder.length;
cbcount=0;
for (var i=0; i<CountCol.length; i++)
{
ColOut[i]=parseInt(CBorder[curord][cbcount]);
cbcount++;
}
RowOut = new Array();
for (var i=0; i<CountRow.length; i++)
{
RowOut[i]=parseInt(CBorder[curord][cbcount]);
cbcount++
}
}
else
{
// code if no prespecified CBorder
// retrieve position of counterbalance groups
var cf=new Array() // position of fixed cols
var c1=new Array() // position of c1 cols
for (var i=0; i<CountCol.length; i++)
{
switch (CountCol[i])
{
case '0': cf[cf.length]=i;break;
case '1': c1[c1.length]=i;break;
}
}
var rf=new Array() // position of fixed rows
var r1=new Array() // position of c1 rows
for (var i=0; i<CountRow.length; i++)
{
switch (CountRow[i])
{
case '0': rf[rf.length]=i;break;
case '1': r1[r1.length]=i;break;
}
}
// subjDen is the denominator used to devide the subj number for each counterbalance step
subjDen = 1;
if (subjtype!="random") {subjDen = Math.floor(subjDen * masterCond)};
// first determine column and row connects and switch on that
var numCond = (c1.length>0 ? fac(c1.length) : 1)*(r1.length>0 ? fac(r1.length) : 1);
if (subjnr==-1) {subjnr=Math.floor(Math.random()*numCond)}
//alert("total cond:" + numCond+"\nsubject: "+subjnr);
// counterbalance col groups
if (c1.length>0) {c1_order=CountBal(subjnr/subjDen+1,c1.length);
subjDen = subjDen*fac(c1.length);}
var c1count=0;
ColOut = new Array();
for (var i=0; i<CountCol.length; i++)
{
switch (CountCol[i])
{
case '0': ColOut[i]=i;break;
case '1': ColOut[i]=c1[c1_order[c1count]];c1count++;break;
}
}
// counterbalance rows
if (r1.length>0) {r1_order=CountBal(subjnr/subjDen+1,r1.length); subjDen = subjDen * fac(r1.length);}
var r1count=0;
RowOut = new Array();
for (var i=0; i<CountRow.length; i++)
{
switch (CountRow[i])
{
case '0': RowOut[i]=i;break;
case '1': RowOut[i]=r1[r1_order[r1count]];r1count++;break;
}
}
}
Dlist=new Array();
// reorder and resize table content
for (j=0;j<RowOut.length;j++)
{
for (i=0;i<ColOut.length;i++)
{
var label = String.fromCharCode(j+97)+i.toString();
if (statecont[j][i]=="1") {Dlist[Dlist.length]=tagcont[j][i];}
if (document.getElementById)
{
// IE6/NS6>/Mozilla
HandleCont = document.getElementById(label+"_cont");
HandleTxt = document.getElementById(label+"_txt");
HandleBox = document.getElementById(label+"_box");
HandleTD = document.getElementById(label+"_td");
HandleTDbox = document.getElementById(label+"_tdbox");
HandleImgBox = document.getElementById(label+"_img");
HandleImg = eval("document.images."+label);
pxstr="px";
}
else if (document.all)
{
//IE4/5
HandleCont=eval("document.all['"+label+"_cont"+"']");
HandleTxt=eval("document.all['"+label+"_txt"+"']");
HandleTD=eval("document.all['"+label+"_td"+"']");
HandleBox=eval("document.all['"+label+"_box"+"']");
HandleTDbox=eval("document.all['"+label+"_tdbox"+"']");
HandleImgbox=eval("document.all['"+label+"_img"+"']");
HandleImg = eval("document.images."+label);
pxstr="px";
}
// set txt
HandleTD.innerHTML =""; // empty for IE5 on mac bug
// if txtcont is empty or only contains spaces then replace by nbsp to keep TD layout
if (txtcont[RowOut[j]][ColOut[i]].replace(/[\x20]/gi, "")=="") {HandleTD.innerHTML = " "}
else {
// if boxes are non-active and labels are fixed, header rows should also be fixed
if (statecont[RowOut[j]][ColOut[i]]=="0")
{
if (colFix) {tempcol = i}
else {tempcol=ColOut[i]};
if (rowFix) {temprow = j}
else {temprow = RowOut[j]};
HandleTD.innerHTML = txtcont[temprow][tempcol];
}
else {HandleTD.innerHTML = txtcont[RowOut[j]][ColOut[i]]};
};
HandleTDbox.innerHTML =""; // empty for IE5 on mac bug
// if boxcont is empty or only contains spaces then replace by nbsp to keep TD layout
if (boxcont[RowOut[j]][ColOut[i]].replace(/[\x20]/gi, "")=="") {HandleTDbox.innerHTML = " "}
else {
if (colFix) {tempcol = i}
else {tempcol=ColOut[i]};
if (rowFix) {temprow = j}
else {temprow = RowOut[j]};
HandleTDbox.innerHTML = boxcont[temprow][tempcol];
};
//set sizes
HandleTD.width = parseInt(WidthCol[ColOut[i]])-5;
HandleTD.height = parseInt(HeightRow[RowOut[j]])-5;
HandleTDbox.width = parseInt(WidthCol[ColOut[i]])-5;
HandleTDbox.height = parseInt(HeightRow[RowOut[j]])-5;
if (statecont[RowOut[j]][ColOut[i]]=="1") {HandleTD.className = activeClass;} else {HandleTD.className = inactiveClass};
HandleCont.style.width = parseInt(WidthCol[ColOut[i]])+pxstr;
HandleCont.style.height = parseInt(HeightRow[RowOut[j]])+pxstr;
HandleTxt.style.width = parseInt(WidthCol[ColOut[i]])+pxstr;
HandleTxt.style.height = parseInt(HeightRow[RowOut[j]])+pxstr;
HandleTxt.style.clip = "rect(0px "+ HandleTxt.style.width + " " + HandleTxt.style.height +" 0px)";
HandleBox.style.width = parseInt(WidthCol[ColOut[i]])+pxstr;
HandleBox.style.height = parseInt(HeightRow[RowOut[j]])+pxstr;
HandleBox.style.clip = "rect(0px "+ HandleBox.style.width + " " + HandleBox.style.height +" 0px)";
HandleImgBox.style.width = parseInt(WidthCol[ColOut[i]])+pxstr;
HandleImgBox.style.height = parseInt(HeightRow[RowOut[j]])+pxstr;
HandleImg.height = parseInt(HeightRow[RowOut[j]]);
HandleImg.width = parseInt(WidthCol[ColOut[i]]);
// open state=0 boxes using img names from imgcont matrix
if (statecont[RowOut[j]][ColOut[i]] == '0') {HandleBox.style.visibility = "hidden"; HandleTxt.style.visibility = "visible";} else {HandleBox.style.visibility = "visible"; HandleTxt.style.visibility = "hidden";}
}
}
// if there are buttons then reorder the buttons according to the counterbalancing scheme
if (btnFlg>0)
{
btn_inner = new Array()
for (bc=0;bc<btnTxt.length;bc++)
{
// swap names if not counterbalancing is turned off
if (btnFlg==1)
{
//var btnNum = parseInt(ColOut[bc])
realNum=parseInt(ColOut[bc]);
if (colFix) {var txtNum = bc; }
else {var txtNum = realNum;}
}
else {
//var btnNum = parseInt(RowOut[bc])
realNum=parseInt(RowOut[bc]);
if (rowFix) {var txtNum = bc;}
else {var txtNum = realNum;}
}
if (btnState[realNum]=="1")
{
if (btnType=="radio")
{var functionstr = "onMouseOver=\"timefunction('mouseover','"+btnTag[realNum]+"','"+btnTxt[realNum]+"')\" onClick=\"recChoice('onclick','"+btnTag[realNum]+"','"+btnTxt[txtNum]+"')\" onMouseOut=\"timefunction('mouseout','"+btnTag[realNum]+"','"+btnTxt[realNum]+"')\"";
btn_inner[bc]="<INPUT type=\"radio\" name=\"mlchoice\" value=\""+btnTag[realNum]+"\" "+functionstr+">"+btnTxt[txtNum];}
else
{var functionstr = "onMouseOver=\"btnHover(this,'in');timefunction('mouseover','"+btnTag[realNum]+"','"+btnTxt[realNum]+"')\" onClick=\"recChoice('onclick','"+btnTag[realNum]+"','"+btnTxt[txtNum]+"')\" onMouseOut=\"btnHover(this,'out');timefunction('mouseout','"+btnTag[realNum]+"','"+btnTxt[realNum]+"')\"";
btn_inner[bc]="<INPUT class=\"btnStyle\" type=\"button\" name=\"" + btnTag[realNum] + "\" value=\""+btnTxt[txtNum]+"\" "+functionstr+">";}
}
else
{btn_inner[bc]=" ";}
}
for (bc=0;bc<btnTxt.length;bc++)
{
if (document.getElementById)
{
// IE6/NS6>/Mozilla
HandleTD = document.getElementById("btn_"+bc.toString());
}
else if (document.all)
{
//IE4/5
HandleTD=eval("document.all['"+"btn_"+bc.toString()+"']");
}
if (bc==0) {defTDcolor = HandleTD.style.backgroundColor;}
docstr=btn_inner[bc];
HandleTD.innerHTML =""; // empty for IE5 on mac bug
HandleTD.innerHTML = docstr;
}
}
// send col and row orders as events
timefunction("subject", subjtype,subjnr)
timefunction("order","col",ColOut.join("_"))
timefunction("order","row",RowOut.join("_"))
timefunction("events","open_close",evtOpen.toString()+"_"+evtClose.toString());
loaded = true; // set flag that page has been loaded;
if (tmActive) {
initTmBar();
if (tmDirectStart) {startTmBar();}
}
return;
}
function initTmBar() {
if (!tmActive) {return false;}
if (document.getElementById)
{
// IE6/NS6>/Mozilla
HandleTmCont = document.getElementById("tmCont");
HandleTmBar = document.getElementById("tmBar");
HandleTmTime = document.getElementById("tmTime");
}
else if (document.all)
{
//IE4/5
HandleTmCont =eval("document.all['tmCont']");
HandleTmBar=eval("document.all['tmBar']");
HandleTmTime=eval("document.all['tmTime']");
}
HandleTmCont.style.width=parseInt(tmWidthPx+4)+"px";
HandleTmTime.style.width=parseInt(tmWidthPx+4)+"px";
if (tmFill) {HandleTmBar.style.width="0px"; HandleTmTime.innerHTML="0 sec";}
else {HandleTmBar.style.width=parseInt(tmWidthPx)+"px"; HandleTmTime.innerHTML=parseInt(tmTotalSec)+" sec";}
if (tmShowTime) {HandleTmTime.style.visibility="visible";}
else {HandleTmTime.style.visibility="hidden";}
}
function startTmBar()
{
if (!tmActive) {return false;}
tmCurTime = 0;
tmInt = setInterval("refreshTmBar()", tmStepSec*1000);
}
function refreshTmBar()
{
if (!tmActive) {return false;}
tmCurTime= tmCurTime + tmStepSec*1000;
if (tmCurTime>tmTotalSec*1000) {clearInterval(tmInt); tmTimeUp=true; return;}
if (tmFill) {
HandleTmBar.style.width=parseInt(Math.round(tmCurTime/(tmTotalSec*1000)*tmWidthPx))+"px";
if (tmMinLabel=="false" | tmCurTime <60000) {HandleTmTime.innerHTML=parseInt(Math.round(tmCurTime/1000))+" "+tmSecLabel}
else
{ var mnt = parseInt(Math.floor(tmCurTime/60000));
var secs = parseInt((tmCurTime-mnt*60000)/1000);
HandleTmTime.innerHTML=mnt+" "+tmMinLabel+" : "+secs+" "+tmSecLabel} ;
}
else {HandleTmBar.style.width=parseInt(tmWidthPx-Math.round(tmCurTime/(tmTotalSec*1000)*tmWidthPx))+"px";
HandleTmTime.innerHTML=parseInt(tmTotalSec-Math.round(tmCurTime/1000))+" sec";
if (tmMinLabel=="false" | tmCurTime<60000) {HandleTmTime.innerHTML=parseInt(tmTotalSec-Math.round(tmCurTime/1000))+" "+tmSecLabel}
else
{ var timeleft = tmTotalSec*1000-tmCurTime;
var mnt = parseInt(Math.floor(timeleft/60000));
var secs = parseInt((timeleft-mnt*60000)/1000);
HandleTmTime.innerHTML=mnt+" "+tmMinLabel+" : "+secs+" "+tmSecLabel} ;
}
}
EDIT: There is a lot going on in that javascript function. A lot of it is exporting and importing values from and to the form. Without
really knuckling down into it, I can't be certain that my attempts
below won't ruin the integrity of your data.
Please consider hiring someone to correct this. It may be a relativeley simple change and a google of 'freelance javascript
developer' would help you find someone.
That code submits the words 'submit','submit','submit' to a function called timefunction. Apart from the hint that this code is a form of subliminal messaging to make your uses more subservient (/joke), it looks like that function is defined elsewhere. This means we cannot tell what it actually does. mlweb.js is an external javascript file that is linked at the start of this page, and that leads me to believe it is where that function is defined (that means all the code to handle that function comes from there).
There is, however, and obvious link from your submit button that calls the function using an onclick method. onClick=timefunction('submit','submit','submit') which could be replicated based on other criteria that doesn't require a click.
If, for example, you wished to make it submit the data IF someone tries to leave the page (this may cause an issue if they submit first.)
Rough code
window.onbeforeunload = timefunction('submit','submit','submit');
This code would tell the browser to send this function those three words before closing.
As that code seems to simply send text values (probably to hint timefunction to do some action in particular), there may be one of those values you could change to record that it was a close event rather than a submit. But we do not know which one without seeing the other code. I would experiment by changing one at a time if it was my code. But I would not advise you to do so since you don't know what the rest does.
Then you have an action on the form that does two things, one is onSubmit="return checkForm(this)" which seems like a form validator to make sure everything is filled in correctly. You could add this step in to ensure it has, but now you're going to try and prevent them from closing the window, and bug them about not submitting it.
Then the form is actually submitted to save.php which we also cannot see. Again, we can send the form details (as is) just as if it was submitted (WITHOUT VALIDATION). We would do that by adding document.forms["mlwebform"].submit(); with the previous code.
We can squeeze in the form validation, but I'm not sure what the return result is. Here's two options.
Like so
//no validation!!!
window.onbeforeunload = function() {
timefunction('submit','submit','submit');
document.forms["mlwebform"].submit();
}
//with possible validation
window.onbeforeunload = function() {
if (checkForm(document.forms["mlwebform"])) { //if the validator returns true, continue
timefunction('submit','submit','submit');
document.forms["mlwebform"].submit();
} else { //if the validator does anything else, say so
MsgBox("Apologies, something went wrong");
}
}
This COULD work, depending on the functions in that other file. I would try the second one first, because having validation would be great. Otherwise use the first one as a fall back.
I would add this after loadMatrices(); and before </script>.
Conclusion
Seeing mlweb.js would help.
We can try and fake the same response a submit would do (this could cause errors, and we don't know how they are dealt with)
If you're brave, and there are no/little consequences to you messing up your data by dumping errors and un-validated into it through experimentation at this stage, then test out the 2 code examples above.
If the integrity of your data at this stage is important, or this is a live/production site, then don't! Get someone to properly assess the code

YUI-2 Datatable : Dynamic column definition with Server side AJAX pagination sorting

I am using the below code to create a YUI datatable with dynamic data(columns). But am facing a issue in server side pagination. As of now it is working fine with client side pagination, but I need server side pagination, so that my page loading time will get reduced. Can you help me on this to fix the issue. Since I'm struggling in this area for past 2 days.Server side pagination with AJAX to render the data is my expectation.
Here is the code I Used
DataProvider.prototype = {
url:null,
data:null,
ds:null,
getData:function() {return this.data},
initialize:function(){
var str = generateRequest();
var newUrl = this.url+str;
YAHOO.util.Connect.asyncRequest('GET', newUrl, this);
},
success:function(response){
var responseVal = YAHOO.lang.JSON.parse(response.responseText);
var columnList = responseVal.columnList;
var sortedBy = responseVal.sortedBy;
this.data = responseVal.results;
if(this.data == '') {
$('#dynamicdata').html('<font style="color:red;"> No Data Found!</font>');
} else {
this.ds = new YAHOO.util.FunctionDataSource(function(){return this.dataProvider.getData()});
this.ds.responseSchema = {
resultsList:"results",
fields:columnList,
// Access to values in the server response
metaFields: {
totalRecords: "totalRecords",
startIndex: "startIndex"
}
}
this.ds.dataProvider = this;
// DataTable configuration
var myConfigs = {
paginator: new YAHOO.widget.Paginator({ rowsPerPage:20 }), // Enables pagination
width:"80%", height:"auto"
};
// FORMATTING CELL COLOUR BASED ON THEIR VALUES
var myCustomFormatter = function(elLiner, oRecord, oColumn, oData) {
var columnKey = oColumn.getKey();
var frmCurrentPeroid = $('#from').val();
//var frmCurrentPeroid = '2013-03-13';
var defaultLabels = ['Product type','Total 1','Total 2','Change'];
if (isDate(columnKey) && $.inArray(columnKey, defaultLabels) === -1) {
if(columnKey < frmCurrentPeroid) {
YAHOO.util.Dom.addClass(elLiner.parentNode,'orange');
elLiner.innerHTML = oData;
//alert('blue');
} else {
YAHOO.util.Dom.addClass(elLiner.parentNode,'blue');
elLiner.innerHTML = oData;
}
} else {
if(columnKey == 'Total 1') {
YAHOO.util.Dom.addClass(elLiner.parentNode,'orange');
elLiner.innerHTML = oData;
//alert('blue');
}
else if(columnKey == 'Total 2') {
YAHOO.util.Dom.addClass(elLiner.parentNode,'blue');
elLiner.innerHTML = oData;
//alert('blue');
}
else if(columnKey == 'Change') {
split_data = oData.toString().split('_');
var fieldData = null;
var fieldFormatter = null;
fieldData = split_data[0];
fieldFormatter = split_data[1];
if(fieldFormatter == 'green') {
YAHOO.util.Dom.addClass(elLiner.parentNode,'green');
elLiner.innerHTML = fieldData;
}
if(fieldFormatter == 'red') {
YAHOO.util.Dom.addClass(elLiner.parentNode,'red');
elLiner.innerHTML = fieldData;
}
}
else if(columnKey == 'Product Name') {
var filterStr = oData.substring(0,30);
elLiner.innerHTML = ''+filterStr+'';
//alert('blue');
}
else {
elLiner.innerHTML = oData;
}
}
};
// Add the custom formatter to the shortcuts
YAHOO.widget.DataTable.Formatter.myCustom = myCustomFormatter;
//YAHOO.widget.DataTable.formatLink = formatLink;
/* make call to initialize your table using the data set */
var myDataTable = new YAHOO.widget.DataTable("dynamicdata", columnList, this.ds, myConfigs);
}
}
}
Followed the code posted in this page
Click here
Thanks in Advance,
Raja
I haven't been doing YUI2 for quite some time so I am no longer able to help you directly. Perhaps this example can help: http://www.satyam.com.ar/yui/#ServerDriven . I do remember that there were big changes in 2.6 and this examples are marked 2.4, perhaps they no longer work.

Voting redirect

I downloaded the PHP voting script from this website:
I have installed this and it works perfectly on my website, however I am looking at customising it slightly so that once a user has voted it then redirects them to a new page, or ideally opens up a lightbox.
I have narrowed it down to a javascript problem, and the javascript file is within the voting.js file.
Below is the following code found in that file:
// Ajax Voting Script - http://www.coursesweb.net
var ivotings = Array(); // store the items with voting
var ar_elm = Array(); // store the items that will be send to votAjax()
var i_elm = 0; // Index for elements aded in ar_elm
var itemvotin = ''; // store the voting of voted item
var votingfiles = 'votingfiles/'; // directory with files for script
var advote = 0; // variable checked in addVote(), if is 0 cann vote, else, not
// gets all DIVs, store in $ivotings, and in $ar_elm DIVs with class: "vot_plus", "vot_updown", and ID="vt_..", sends to votAjax()
var getVotsElm = function () {
var obj_div = document.getElementsByTagName('div');
var nrobj_div = obj_div.length;
for(var i=0; i<nrobj_div; i++) {
// if contains class and id
if(obj_div[i].className && obj_div[i].id) {
var elm_id = obj_div[i].id;
// if class "vot_plus", "vot_updown1", "vot_updown2", or "vot_poll" and id begins with "vt_"
if((obj_div[i].className=='vot_plus' || obj_div[i].className=='vot_updown1' || obj_div[i].className=='vot_updown2') && elm_id.indexOf("vt_")==0) {
ivotings[elm_id] = obj_div[i]; // store object item in $ivotings
ar_elm[i_elm] = elm_id; // add item_ID in $ar_elm array, to be send in json string tp php
i_elm++; // index order in $ar_elm
}
}
}
// if there are elements in "ar_elm", send them to votAjax()
if(ar_elm.length>0) votAjax(ar_elm, ''); // if items in $ar_elm pass them to votAjax()
};
// add the ratting data to element in page
function addVotData(elm_id, vote, nvotes, renot) {
// exists elm_id stored in ivotings
if(ivotings[elm_id]) {
// sets to add "onclick" for vote up (plus), if renot is 0
var clik_up = (renot == 0) ? ' onclick="addVote(this, 1)"' : ' onclick="alert(\'You already voted\')"';
// if vot_plus, add code with <img> 'votplus', else, if vot_updown1/2, add code with <img> 'votup', 'votdown'
if(ivotings[elm_id].className == 'vot_plus') { // simple vote
ivotings[elm_id].innerHTML = '<h4>'+ vote+ '</h4><span><img src="'+votingfiles+'votplus.gif" alt="1" title="Vote"'+ clik_up+ '/></span>';
}
else if(ivotings[elm_id].className=='vot_updown1') { // up/down with total Votes
// sets to add "onclick" for vote down (minus), if renot is 0
var clik_down = (renot == 0) ? ' onclick="addVote(this, -1)"' : ' onclick="alert(\'You already voted\')"';
ivotings[elm_id].innerHTML = '<div id="nvotes">Votes: <b>'+ nvotes+ '</b></div><h4>'+ vote+ '</h4><span><img src="'+votingfiles+'votup.png" alt="Vote Up" title="Vote Up"'+ clik_up+ '/> <img src="'+votingfiles+'votdown.png" alt="Vote Down" title="Vote Down"'+ clik_down+ '/></span>';
}
else if(ivotings[elm_id].className=='vot_updown2') { // up/down with number of votes up and down
var nvup = (nvotes*1 + vote*1) /2; // number of votes up
var nvdown = nvotes - nvup; // number of votes down
// sets to add "onclick" for vote down (minus), if renot is 0
var clik_down = (renot == 0) ? ' onclick="addVote(this, -1)"' : ' onclick="alert(\'You already voted\')"';
ivotings[elm_id].innerHTML = '<h4>'+ vote+ '</h4><span><img src="'+votingfiles+'votup.png" alt="Vote Up" title="Vote Up"'+ clik_up+ '/> <img src="'+votingfiles+'votdown.png" alt="Vote Down" title="Vote Down"'+ clik_down+ '/></span><div id="nupdown"><b id="nvup">'+ nvup+ '</b> <b id="nvdown">'+ nvdown+ '</b></div>';
}
}
}
// Sends data to votAjax(), that will be send to PHP to register the vote
function addVote(ivot, vote) {
// if $advote is 0, can vote, else, alert message
if(advote == 0) {
var elm = Array();
elm[0] = ivot.parentNode.parentNode.id; // gets the item-name that will be voted
ivot.parentNode.innerHTML = '<i><b>Thanks</b></i>';
votAjax(elm, vote);
}
else alert('You already voted');
}
/*** Ajax ***/
// create the XMLHttpRequest object, according to browser
function get_XmlHttp() {
var xmlHttp = null; // will stere and return the XMLHttpRequest
if(window.XMLHttpRequest) xmlHttp = new XMLHttpRequest(); // Forefox, Opera, Safari, ...
else if(window.ActiveXObject) xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); // IE
return xmlHttp;
}
// sends data to PHP and receives the response
function votAjax(elm, vote) {
var cerere_http = get_XmlHttp(); // get XMLHttpRequest object
// define data to be send via POST to PHP (Array with name=value pairs)
var datasend = Array();
for(var i=0; i<elm.length; i++) datasend[i] = 'elm[]='+elm[i];
// joins the array items into a string, separated by '&'
datasend = datasend.join('&')+'&vote='+vote;
cerere_http.open("POST", votingfiles+'voting.php', true); // crate the request
cerere_http.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); // header for POST
cerere_http.send(datasend); // make the ajax request, poassing the data
// checks and receives the response
cerere_http.onreadystatechange = function() {
if (cerere_http.readyState == 4) {
// receives a JSON with one or more item:[vote, nvotes, renot]
eval("var jsonitems = "+ cerere_http.responseText);
// if jsonitems is defined variable
if (jsonitems) {
// parse the jsonitems object
for(var votitem in jsonitems) {
var renot = jsonitems[votitem][2]; // determine if the user can vote or not
// if renot=3 displays alert that already voted, else, continue with the voting reactualization
if(renot == 3) {
alert("You already voted \n You can vote again tomorrow");
window.location.reload(true); // Reload the page
}
else addVotData(votitem, jsonitems[votitem][0], jsonitems[votitem][1], renot); // calls function that shows voting
}
}
// if renot is undefined or 2 (set to 1 NRVOT in voting.php), after vote, set $advote to 1
if(vote != '' && (renot == undefined || renot == 2)) advote = 1;
}
}
}
// this function is used to access the function we need after loading page
function addLoadVote(func) {
var oldonload = window.onload;
// if the parameter is a function, calls it with "onload"
// otherwise, adds the parameter into a function, and then call it
if (typeof window.onload != 'function') window.onload = func;
else {
window.onload = function() {
if (oldonload) { oldonload(); }
func();
}
}
}
addLoadVote(getVotsElm); // calls getVotsElm() after page loads
I did have a go at doing this myself and it did work in certain browsers, but not others. All I did was add change the code on line 66 from:
ivot.parentNode.innerHTML = 'Thanks';
to:
ivot.parentNode = window.location = "register2.php";
But as I said, this only works on certain browsers as on other browsers it doesn't add the information to the database, anyone know how I can resolve this?
The ajax request and the database operations are executed in the votAjax(elm, vote). So you have to add the code for redirecting after the execution of that request.
Most likely between lines 100-115
Did you mean :
window.top.location = 'register2.php';

sending php array to javascript function onclick

Little problem about sending PHP array to javascript function, i did homework looked everywhere and i know its not reliable to do this, but at this moment i do not know any other way , so try to just advice me how to finish it anyway.
I got php code executing first , idea is on page load i get some data from MySQL , i filled php array with IDs from that select statement.
<?php
include('config.php');
$TicketExist = "select BetSlipID,probatip1.betslips.MatchID as GameID,
TipID,tim1.Name AS HomeTeam ,tim2.Name AS AwayTeam, UserID
from probatip1.betslips
inner join probatip1.matches matches on probatip1.betslips.MatchID = matches.MatchID
inner join probatip1.teams tim1 on matches.HomeTeamID = tim1.TeamID
inner join probatip1.teams tim2 on matches.AwayTeamID = tim2.TeamID
where UserID = 1";
$TicketResult = mysql_query($TicketExist);
$TicketNum = mysql_numrows($TicketResult);
mysql_close();
if($TicketNum != 0)
{
$s=0;
while($s < $TicketNum)
{
$GameID = mysql_result($TicketResult,$s,"GameID");
$TipID = mysql_result($TicketResult,$s,"TipID");
$ArrayIDs[$s] = $GameID;
echo "<script>window.onload=GetInfo($GameID,$TipID); </script>";
$s++;
}
}
?>
So i got it everything i want filled and wrote on my page , idea now is on user click , to call javascript to take this '$ArrayIDs' and execute code from script
Here is code im calling script
<ul>
<li
id="ConfirmButton" name="Insert" method="post"
onclick="GetAllIDs(<?php $ArrayIDs ?>)"><a>POTVRDI</a></li>
</ul>
And my script code
function GetAllIDs(Ticket) {
$("td.ID").each(function () {
var MatchID = $(this).attr('id');
var lab = "Label";
var Label = lab + MatchID;
var Final = document.getElementById(Label);
var TipID;
if (Final.innerHTML == '1') {
TipID = 1;
}
else if (Final.innerHTML == 'X') {
TipID = 2;
}
else if (Final.innerHTML == '2') {
TipID = 3;
}
else {
return;
}
var request_type;
var browser = navigator.appName;
if (browser == "Microsoft Internet Explorer") {
request_type = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
request_type = new XMLHttpRequest();
}
var http = request_type;
var AlreadyPlayed = false;
if (Ticket != null) {
var TicketExists = Ticket;
for (var i = 0; i < TicketExists.length; i++) {
if (TicketExists[i] == MatchID) {
AlreadyPlayed = true;
break;
}
}
}
if (http != null) {
if (AlreadyPlayed == true) {
http.open('get', 'update.php?MatchID=' + MatchID +
'&TipID=' + TipID + '&UserID=' + 1, true);
}
else {
http.open('get', 'insert.php?MatchID=' + MatchID +
'&TipID=' + TipID + '&UserID=' + 1, true);
}
http.send(null);
}
});
if (Ticket == null) {
alert('Tiket je napravljen');
}
else {
alert('Tiket je promenjen');
}
}
With this posted code when i am debugging code with firebug in mozzila i get that my 'Ticket' parameter that suppose to be '$ArrayIDs' is undefined.
Reason why i want to make array and send it to javascript onclick event is to check if user already placed a bet on some game , if he did i want to send all data for update and if he did not yet placed bet on some game to send data for insert in database.
So i need array and before anything just to check MatchID with all IDs in my array, so i know what to do.
Thanks all in advance for helping out
Your script could do with a bit of cleanup, but in essence you need to change
onclick="GetAllIDs(<?php $ArrayIDs ?>)">
to
onclick="GetAllIDs(<?php echo json_encode($ArrayIDs) ?>)">
I'd also reccomend not outputting
"<script>window.onload=GetInfo($GameID,$TipID); </script>";
for each row in mysql, instead create a single array of the values and create one script after the loop. Using mysql_fetch_row instead of mysql_numrows and mysql_result is probably neater.
while ($row = mysql_fetch_row($result)) {
//...do things here...
}
You need to output the array as valid JavaScript, use json_encode
GetAllIDs(<?php echo json_encode($ArrayIDs); ?>)

Call PHP program as popup overlay?

I am trying to use fancybox iframe to call a PHP program for payment processing from a javascript program as part of a landing page. The page also calls another PHP program that writes date to a file. I tried to simulate a click to start the fancybox function but never got it to work. I keep getting this error - $("a.hiddenclicker").fancybox is not a function. I'm not sure whether to attempt to just add this logic to the PHP file or figure out how to get fancybox to work. Here is my page. The call to fancybox is in ProcessForm().
function WriteData(url) {
var j1 = document.getElementById("hiddenclicker");
var Request2 = false;
if (window.XMLHttpRequest) {
Request2 = new XMLHttpRequest();
} else if (window.ActiveXObject) {
Request2 = new ActiveXObject("Microsoft.XMLHTTP");
}
if (Request2) {
Request2.open("GET", url, true);
Request2.onreadystatechange = function() {
if (Request2.readyState == 4 && Request2.status == 200) {
}
}
Request2.send(null);
}
}
function ProcessForm(form) {
var j1 = document.getElementById("hiddenclicker");
var firstname = "";
var lastname = "";
var payment = "";
var email = "";
var phone = "";
var donation = "";
firstname = form.firstname.value;
lastname = form.lastname.value;
email = form.email.value;
phone = form.phone.value;
donation = form.donation.value;
if (firstname == "") {
alert("You must fill in the first name");
form.firstname.focus();
return false;
}
else {
if (lastname == "") {
alert("You must fill in last name");
form.lastname.focus();
return false;
}
else {
if (email == "") {
alert("You must fill in email address");
form.email.focus();
return false; }
}
}
WriteData("writedata.php?firstname=" + firstname + "&lastname=" + lastname + "&email=" + email + "&phone=" + phone + "&donation=" + donation);
if (donation == "now") {
jQuery(document).ready(function(){
$("a.hiddenclicker").fancybox(
{
'width' : 600,
'height' : 400,
'hideOnContentClick' : false,
'type' : 'iframe'
});
});
j1.href = "http://www.ccyakids.org/donation_logic/donation_start.php#form";
$('#hiddenclicker').trigger('click');
}
}
// End hiding JavaScript statements -->
HTML needed to trigger hiddenclicker
Hidden Clicker
After looking at your code you reference your link 2 different ways:
$("a.hiddenclicker") // class
$('#hiddenclicker') // ID
Which is it? Make them both the same and i am sure your problem goes away.
Hope this helps

Categories