Calling a java script function with php on click - php

Ok so i have paid a coder to code me a walk around map script were users can press up and down on the keyboard and walk aroud a map using jquery. But now im trying to make it so i have a up and down image and then on click it will call the up and down function. So the suer can use the up and down keys plus clicking the images.
Here is the up function im using for when the user presses the up key on the keyboard. But now some how i need to call the same function when a image is clicked..
function move(d)
{
if(d == "UP")
{
var top = (parseInt(document.getElementById('move').style.top) - 10);
var left = parseInt(document.getElementById('move').style.left);
if(canMove(new xy(left,top)))
{
document.getElementById('move').style.top = (parseInt(document.getElementById('move').style.top) - 10) + 'px';
document.player.src = "maps/sprites/playerUp.png";
//if(lastStep != "UP") clearTimeouts();
//setTimeout('document.player.src="playerUp.png"', 500);
//lastStep = "UP";
reloadF();
}
}
How would i do about doing that ??
Im guessing i just need to call function move(d) and set it to up some how ?? On click of image ?

var keynum = 0;
if(window.event) { keynum = e.keyCode; } // for IE
else if(e.which) { keynum = e.which; } // for others browsers
if(keynum === 38) { // up
//if KEY UP
}
if(keynum === 40) { // down
//if KEY DOWN
}
I hope this help...

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

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

How to fix a not defined javascript error?

I am fairly new to Javascript and what I am trying to do is have a cookie set as soon as I click on a link. When I return back to the previous page from the link, I want the page to auto refresh and notify the user by color to show what link they just clicked. I used this example to guide me http://webdesign.about.com/od/cookies/a/aa083198.htm. But I am still not getting it.
The code below is what I have. The problem is that as soon as I click on the link firebug brings up the error "getLink not defined". Also through web developer on Firefox, it seems that my cookie is not actually being set even though I am calling it from the Html.I am also showing gave the most important part in my Html that calls the function.
The videoId i have in setCookie is a php variable that is defined somewhere else in my code. I would really appreciate it if someone can point me in the right direction. Thanks!
<head>
<script language="text/javascript">
var cookie_name = "watched";
function setCookie(cookie_name,cookie_value)
{
if (document.cookie!="") {
index = document.cookie.indexOf(cookie_name);
} else {
index = -1;
}
if (index == -1) {
var finish = 7200;
var cookie_value = videoId + "; expires=" + finish;
document.cookie=cookie_name + "=" + cookie_value;
}
}
function getLink(cookie_value) {
if (document.cookie) {
index = document.cookie.indexOf(cookie_value);
if (index != -1) {
colorLinks;
}
else{
//alert("No color");
}
}
return colorLinks;
}
function colorLinks()
{
$('#' + videoId).css('background-color: pink');
}
</script>
</head>
<body onLoad=window.refresh>
<div id="page">
echo '<a href="' . $link . '" onclick="setCookie(); return true;">' . $this->Links
This does not make sense:
function getLink(cookie_value) {
if (document.cookie) {
index = document.cookie.indexOf(cookie_value);
if (index != -1) {
colorLinks; // you mean colorLinks(); ???
}
else {
//alert("No color");
}
}
// why return a function that sets color instead of just calling it?
return colorLinks;
}
and there is luckily nothing called window.refresh (unless you have created it yourself) or you would loop forever
In the code i don't see where videoId is given a value
You don't call the function setCookie(cookie_name,cookie_value); to set the cookie.
Please read about cookies: http://www.quirksmode.org/js/cookies.html
<script type = "text/javascript">
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
</script>

Split Problem Internet Explorer

After an earlier question relating to this error.
Error: unable to get value of the property ‘split’: object is null or undefined
An answer was offered to add the following code:
/* Cross-Browser Split 1.0.1
(c) Steven Levithan <stevenlevithan.com>; MIT License
An ECMA-compliant, uniform cross-browser split method */
var cbSplit;
// avoid running twice, which would break `cbSplit._nativeSplit`'s reference to the native `split`
if (!cbSplit) {
cbSplit = function (str, separator, limit) {
// if `separator` is not a regex, use the native `split`
if (Object.prototype.toString.call(separator) !== "[object RegExp]") {
return cbSplit._nativeSplit.call(str, separator, limit);
}
var output = [],
lastLastIndex = 0,
flags = (separator.ignoreCase ? "i" : "") +
(separator.multiline ? "m" : "") +
(separator.sticky ? "y" : ""),
separator = RegExp(separator.source, flags + "g"), // make `global` and avoid `lastIndex` issues by working with a copy
separator2, match, lastIndex, lastLength;
str = str + ""; // type conversion
if (!cbSplit._compliantExecNpcg) {
separator2 = RegExp("^" + separator.source + "$(?!\\s)", flags); // doesn't need /g or /y, but they don't hurt
}
/* behavior for `limit`: if it's...
- `undefined`: no limit.
- `NaN` or zero: return an empty array.
- a positive number: use `Math.floor(limit)`.
- a negative number: no limit.
- other: type-convert, then use the above rules. */
if (limit === undefined || +limit < 0) {
limit = Infinity;
} else {
limit = Math.floor(+limit);
if (!limit) {
return [];
}
}
while (match = separator.exec(str)) {
lastIndex = match.index + match[0].length; // `separator.lastIndex` is not reliable cross-browser
if (lastIndex > lastLastIndex) {
output.push(str.slice(lastLastIndex, match.index));
// fix browsers whose `exec` methods don't consistently return `undefined` for nonparticipating capturing groups
if (!cbSplit._compliantExecNpcg && match.length > 1) {
match[0].replace(separator2, function () {
for (var i = 1; i < arguments.length - 2; i++) {
if (arguments[i] === undefined) {
match[i] = undefined;
}
}
});
}
if (match.length > 1 && match.index < str.length) {
Array.prototype.push.apply(output, match.slice(1));
}
lastLength = match[0].length;
lastLastIndex = lastIndex;
if (output.length >= limit) {
break;
}
}
if (separator.lastIndex === match.index) {
separator.lastIndex++; // avoid an infinite loop
}
}
if (lastLastIndex === str.length) {
if (lastLength || !separator.test("")) {
output.push("");
}
} else {
output.push(str.slice(lastLastIndex));
}
return output.length > limit ? output.slice(0, limit) : output;
};
cbSplit._compliantExecNpcg = /()??/.exec("")[1] === undefined; // NPCG: nonparticipating capturing group
cbSplit._nativeSplit = String.prototype.split;
} // end `if (!cbSplit)`
// for convenience...
String.prototype.split = function (separator, limit) {
return cbSplit(this, separator, limit);
};
After trialling the code above and deleting caches it was found to do nothing...can anyone help at all, kind regards in advance.
Thanks EdoDodo for the above code but can you offer any further help as I am almost tearing my hair out and it did not work in the end, one point to note, the linked in button on the home page (if commented out) makes that site work for the home page and the error goes away but I really want the linked in buttons for each post excerpt on the home page.
site is:
www.mobileinquirer.com
Firefox shows me a script error on line 913 in this part of your script:
<script type="text/javascript">
// <![CDATA[
var disqus_shortname = 'mobileinquirer';
var disqus_domain = 'disqus.com';
(function () {
var nodes = document.getElementsByTagName('span');
for (var i = 0, url; i < nodes.length; i++) {
if (nodes[i].className.indexOf('dsq-postid') != -1) {
nodes[i].parentNode.setAttribute('data-disqus-identifier', nodes[i].getAttribute('rel'));
url = nodes[i].parentNode.href.split('#', 1);
if (url.length == 1) url = url[0];
else url = url[1]
nodes[i].parentNode.href = url + '#disqus_thread';
}
}
var s = document.createElement('script'); s.async = true;
s.type = 'text/javascript';
s.src = 'http://' + disqus_domain + '/forums/' + disqus_shortname + '/count.js';
(document.getElementsByTagName('HEAD')[0] || document.getElementsByTagName('BODY')[0]).appendChild(s);
}());
//]]>
</script>
The specific error is on this line:
url = nodes[i].parentNode.href.split('#', 1);
and it's because parentNode does not have an href. This error has nothing to do with the split function. The code is trying to obtain the value of the href attribute on the parentNode, but there is no href attribute so that resolves to undefined so the call to split fails. It has nothing to do with the split function. The issue is that your markup is apparently wrong and what I think is disqus code is expecting an tag around a tag, but it isn't finding that.
If you look at line 664-665 in the mobilinquirer.com HTML source, you will find this sequence at that line and then several times following:
<p><span
class="dsq-postid">8 Comments</span></p>
This code causes the error. The <span class="dsq-postid"> tag must have an <a href="xxx"> tag as it's parent or you will get this error. I see this same problem several problems in your HTML.
This problem has NOTHING to do with the split function. To make this error go away, you need to fix your HTML so that it is what the disqus code is expecting or remove the offending disqus code (which you don't seem to need) or both.

Categories