I'm working on a project where I on a website display content users can "interact" with using keypress W or P. Doing this, the site executes a function posting to a php writing to a mysql-database. However, if the key is pressed and HOLD or pressed multiple times in a row - I get multiple setTimeouts running and crap happens. How can I temporarily remove access to running (or disable) the keypress-functions when executed once?
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script language="javascript" type="text/javascript" src="jquery-1.6.4.min.js"></script>
<script language="javascript" type="text/javascript" src="jquery.jkey-1.2.js"></script>
<link rel="stylesheet" href="custom.css">
<script>
$(function content(){
var reloading = function(data){
$.ajax({
url: 'api.php',
data: "",
dataType: 'json',
success: function(data)
{
var id = data[0];
_id = id;
var vname = data[1];
var message = data[2];
var field1 = data[3];
_field1 = field1;
var field2 = data[4];
_field2 = field2;
var ans1 = data[5];
_ans1 = ans1;
var ans2 = data[6];
_ans2 = ans2;
var val1 = parseInt(ans1, 10) ;
_val1 = val1;
var val2 = parseInt(ans2, 10) ;
_val2 = val2;
$('#output').hide().html( message ).fadeIn("slow");
$('#username').hide().html( "#"+vname +":" ).fadeIn("slow");
$('#valg1').hide().html( field1 ).fadeIn("slow");
$('#valg2').hide().html( field2 ).fadeIn("slow");
window["reload_timer"] = setTimeout(reloading,6000);
}
});
}
reloading();
$(document).jkey('p',function() {
$.post("update.php", { "id": _id} )
$('#output').hide().html( "<i>Thx!</i>< ).fadeIn("slow");
$('#username').fadeOut("fast");
$('#valg1').fadeOut("fast");
$('#valg2').fadeOut("fast");
clearTimeout(window["reload_timer"]);
setTimeout(reloading,5000);
});
$(document).jkey('w',function() {
$.post("update.php", { "id2": _id} )
$('#output').hide().html( "<i>Thx!</i>< ).fadeIn("slow");
$('#username').fadeOut("fast");
$('#valg1').fadeOut("fast");
$('#valg2').fadeOut("fast");
clearTimeout(window["reload_timer"]);
setTimeout(reloading,5000);
});
});
</script>
</head>
<body><div id="container">
<div id="username">
</div>
<div id="output"></div>
<div id="posted"></div>
<div id="field1"></div>
<div id="valg1"></div>
<div id="valg2"></div>
</div>
</body>
</html>
Introduce a variable called e.g. blocked:
var blocked = false;
In the key handlers, abort if blocked and set blocked to true otherwise:
$(document).jkey('w',function() {
if(blocked) return; // abort
blocked = true; // disallow any further key presses
Unblock in the success handler of reloading:
success: function() {
blocked = false; // allow again
Add a flag and check it in your two keypress handlers:
var allowKeyPress = true;
$(document).jkey('p',function() {
if (!allowKeyPress)
return;
allowKeyPress = false;
// your existing code here
}
Somewhere else in your code you then set allowKeyPress = true; again - I'm not sure exactly where you want to do that: perhaps within your reloading() function, perhaps in the success callback from your $.ajax() (in which case really you should add an error or complete handler to reset the flag if the ajax call fails), or perhaps just with a new, separate setTimeout().
Related
I want to know if it is possible to refer to an dynamically created variables and if yes how?
I create on this site many forms which have p elements on the bottom is one button and if I click that button I want to transmit the variable(IdJB) which was created specific in this form.
I marked the variable with a command in the code.
$(document).ready(function() {
var Id = sessionStorage.getItem('Id');
var status = 0;
var nummer = 0;
$.ajax({
type: "POST",
url: "http://localhost/jQuery&PHPnew/Markt.N.php",
data: {
status: status
},
success: function(data) {
var anzahl = data;
status = 1;
while (anzahl > nummer) {
nummer++;
$.ajax({
type: "POST",
url: "http://localhost/jQuery&PHPnew/Markt.N.php",
data: {
nummer: nummer,
status: status
},
success: function(data) {
var Daten = JSON.parse(data);
var Ausgabebereich = document.getElementById('main');
var IdJB = Daten.id;
window.IdJB = IdJB; //This Variable !!!!!!!!!!!!!
var f = document.createElement("form");
var pInhalt = document.createElement('p');
var Inhalt = document.createTextNode(Daten.inhalt);
pInhalt.appendChild(Inhalt);
f.appendChild(pInhalt);
var pDatum = document.createElement('p');
var Inhalt = document.createTextNode(Daten.datum);
pDatum.appendChild(Inhalt);
f.appendChild(pDatum);
var pUhrzeit = document.createElement('p');
var Inhalt = document.createTextNode(Daten.uhrzeit);
pUhrzeit.appendChild(Inhalt);
f.appendChild(pUhrzeit);
var pGehalt = document.createElement('p');
var Inhalt = document.createTextNode(Daten.gehalt);
pGehalt.appendChild(Inhalt);
f.appendChild(pGehalt);
var pDauer = document.createElement('p');
var Inhalt = document.createTextNode(Daten.dauer);
pDauer.appendChild(Inhalt);
f.appendChild(pDauer);
var pAdresse = document.createElement('p');
var Inhalt = document.createTextNode(Daten.adresse);
pAdresse.appendChild(Inhalt);
f.appendChild(pAdresse);
var pNam_ersteller = document.createElement('p');
var Inhalt = document.createTextNode(Daten.nam_ersteller);
pNam_ersteller.appendChild(Inhalt);
f.appendChild(pNam_ersteller);
var bInhalt = document.createElement('button');
var Inhalt = document.createTextNode("Senden");
bInhalt.appendChild(Inhalt);
bInhalt.setAttribute("type", "button");
bInhalt.setAttribute("onclick", "zuJB()");
f.appendChild(bInhalt);
Ausgabebereich.appendChild(f);
$(document).on('click', 'button', function() {
sessionStorage.setItem('IdJB', IdJB); //Here !!!!!!!!!!!!!
alert(IdJB);
window.location = "http://localhost/jQuery&PHPnew/JobBlock.html";
});
}
})
}
}
})
$("#sub").click(function() {
window.location = "http://localhost/jQuery&PHPnew/Markt.html";
})
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Jobs</title>
<script type="text/javascript" src="jQuery.js"></script>
<script type="text/javascript">
</script>
</head>
<body>
<button id="sub">Update</button>
Alle Jobs
Meine Jobs
Einstellungen
<main id="main">
</main>
</body>
</html>
This is how the Programm looks like
Don't use a global variable. Put IdJB in an attribute of the button. You can use the jQuery .data() method for this.
Also, don't add the event handler every time through the loop. When you use event delegation, you should just add the handler once.
$(document).ready(function() {
$(document).on('click', 'button', function() {
var IdJB = $(this).data("IdJB");
sessionStorage.setItem('IdJB', IdJB);
alert(IdJB);
window.location = "http://localhost/jQuery&PHPnew/JobBlock.html";
});
var Id = sessionStorage.getItem('Id');
var status = 0;
var nummer = 0;
$.ajax({
type: "POST",
url: "http://localhost/jQuery&PHPnew/Markt.N.php",
data: {
status: status
},
success: function(data) {
var anzahl = data;
status = 1;
while (anzahl > nummer) {
nummer++;
$.ajax({
type: "POST",
url: "http://localhost/jQuery&PHPnew/Markt.N.php",
data: {
nummer: nummer,
status: status
},
success: function(data) {
var Daten = JSON.parse(data);
var Ausgabebereich = document.getElementById('main');
var IdJB = Daten.id;
window.IdJB = IdJB; //This Variable !!!!!!!!!!!!!
var f = document.createElement("form");
var pInhalt = document.createElement('p');
var Inhalt = document.createTextNode(Daten.inhalt);
pInhalt.appendChild(Inhalt);
f.appendChild(pInhalt);
var pDatum = document.createElement('p');
var Inhalt = document.createTextNode(Daten.datum);
pDatum.appendChild(Inhalt);
f.appendChild(pDatum);
var pUhrzeit = document.createElement('p');
var Inhalt = document.createTextNode(Daten.uhrzeit);
pUhrzeit.appendChild(Inhalt);
f.appendChild(pUhrzeit);
var pGehalt = document.createElement('p');
var Inhalt = document.createTextNode(Daten.gehalt);
pGehalt.appendChild(Inhalt);
f.appendChild(pGehalt);
var pDauer = document.createElement('p');
var Inhalt = document.createTextNode(Daten.dauer);
pDauer.appendChild(Inhalt);
f.appendChild(pDauer);
var pAdresse = document.createElement('p');
var Inhalt = document.createTextNode(Daten.adresse);
pAdresse.appendChild(Inhalt);
f.appendChild(pAdresse);
var pNam_ersteller = document.createElement('p');
var Inhalt = document.createTextNode(Daten.nam_ersteller);
pNam_ersteller.appendChild(Inhalt);
f.appendChild(pNam_ersteller);
var bInhalt = document.createElement('button');
var Inhalt = document.createTextNode("Senden");
bInhalt.appendChild(Inhalt);
bInhalt.setAttribute("type", "button");
bInhalt.setAttribute("onclick", "zuJB()");
f.appendChild(bInhalt);
$(bInhalt).data('IdJB', IdJB);
Ausgabebereich.appendChild(f);
}
})
}
}
})
$("#sub").click(function() {
window.location = "http://localhost/jQuery&PHPnew/Markt.html";
})
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Jobs</title>
<script type="text/javascript" src="jQuery.js"></script>
<script type="text/javascript">
</script>
</head>
<body>
<button id="sub">Update</button>
Alle Jobs
Meine Jobs
Einstellungen
<main id="main">
</main>
</body>
</html>
I may be misunderstanding your question, but if not: In order to reference dynamically created elements, the click handler just needs to be instantiated after the element is created and put in the DOM. An easy way to handle this is by having a function generate your tag like so:
function appendTag(parent, child){
parent.append(child)
child.click(function(){
//Click code here
});
}
So it looks like when you are adding the button click event dynamically you are adding it to all the buttons on the page. This is why when you click one it runs 3 times.
This can be seen by the button text in this line of code:
$(document).on('click', 'button', function() {
.....
});
To address this problem you need to make the click listener specific to the button. You can do that by making a more specific button selector. Although it's not a perfect solution one way to do this is to give each button a unique I'd. Something like button-## where ## here is a different number each time you create a new button. You can then do:
$(document).on('click', '#button-##', function() {
.....
});
Again replacing ## with the corresponding Id value.
Edit: actually you can use the answer #Laif posted by rather than using the $(document).on( call just simply do b.click()
I have a situation where I have two different sites, siteA.com and siteB.com, which need to share a common piece of information when a visitor navigates from siteA to siteB. I don't have access to the server-side code or navigation links from siteA, only limitied customizations and javascript. In order to share the information I have built a new page that is fully under my control at siteC.com, and then added this page as an iframe to both siteA and siteB. I am using the postMessage method to get and set the cookie from within the iframe which is working fine from each site, however I actually end up with two different cookies, one for each siteA and siteB even though the cookie belongs to siteC because it was set by the page in the iframe, confirmed through F12 debugger. I would have expected to have a single cookie and both sites could share the same cookie via the iframe, am I missing something here, should this be possible or is there another way to do this?
This is the code for my page at siteC that gets loaded into the iframe
<!DOCTYPE html>
<html>
<head>
<title>iframe source</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(function () {
var ck = document.cookie;
var expDate = new Date();
expDate.setFullYear(expDate.getFullYear() + 20)
$("#auditlog").append("iframe loaded<br/>");
if (ck) {
$("#auditlog").append("cookie exists<br/>");
} else {
$("#auditlog").append("cookie not set<br/>");
}
// Assign handler to message event
if (window.addEventListener) {
window.addEventListener('message', messageHandler, false);
} else if (window.attachEvent) { // ie8
window.attachEvent('onmessage', messageHandler);
}
})
function messageHandler(e) {
var msg = {};
var response;
// Check origin
if (e.origin === 'http://siteA' || e.origin === 'http://siteB') {
// Retrieve data sent in postMessage
msg = JSON.parse(e.data);
if (msg.action == "getCookie") {
response = getCookie();
} else if (msg.action == "setCookie") {
setCookie(msg.payload);
response = "cookie set";
} else {
response = "action not supported";
}
// Send reply to source of message
e.source.postMessage(response, e.origin);
}
}
function setCookie(cookieVal) {
var expDate = new Date();
expDate.setFullYear(expDate.getFullYear() + 20)
document.cookie = cookieVal + "; expires=" + expDate.toUTCString();
}
function getCookie() {
return document.cookie;
}
</script>
</head>
<body>
<div id="auditlog"></div>
<div id="cookieinfo"></div>
</body>
</html>
And this is code for my pages at siteA and siteB, both are using this same code, this is a sample I set up in order to test the set and get cookie functions in the iframe
<!DOCTYPE html>
<html>
<head>
<title>Main content page</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(function () {
// Assign handler to message event
if (window.addEventListener) {
window.addEventListener('message', messageHandler, false);
} else if (window.attachEvent) { // ie8
window.attachEvent('onmessage', messageHandler);
}
$("#btnGetIframeCookie").click(function () {
var postMsg = {
action:"getCookie"
}
// get reference to window inside the iframe
var wn = document.getElementById('cookieiframe').contentWindow;
// postMessage arguments: data to send, target origin
wn.postMessage(JSON.stringify(postMsg), 'http://siteC');
})
$("#btnSetIframeCookie").click(function () {
var cookieVal = $("#txtCookieValue").val();
var postMsg = {
action: "setCookie",
payload: cookieVal
}
var wn = document.getElementById('cookieiframe').contentWindow;
// postMessage arguments: data to send, target origin
wn.postMessage(JSON.stringify(postMsg), 'http://siteC');
})
})
function messageHandler(e) {
if (e.origin === 'http://siteC') {
$("#divMessages").append("response from iframe: <br/>" + e.data + "<br/>");
}
}
</script>
</head>
<body>
<div>
This is the iframe container
</div>
<div>
<input type="button" id="btnGetIframeCookie" value="Get iframe cookie" />
</div>
<div>
<input type="text" size="60" id="txtCookieValue" />
<input type="button" id="btnSetIframeCookie" value="Set iframe cookie" />
</div>
<iframe id="cookieiframe" src="http://siteC/iframe/index.html" style="width: 300px; height: 300px; border:1px solid black;"></iframe>
<div id="divMessages"></div>
</body>
</html>
Using this setup, if I set a cookie from siteA via the iframe with a value of "keyabc=value123" for example, I can then read that same cookie back, but when I go to siteB which has the same page in the iframe there, I don't have a cookie until I set one there, for example "keyabc=value456". Now if I look at my actual cookie files at C:\Users\aakoehle\AppData\Local\Packages\Microsoft.MicrosoftEdge_8wekyb3d8bbwe\AC\#!001\MicrosoftEdge\Cookies I see two files, one with each of the values I set and both have the path of siteC. I also launched the F12 tools for each browser tab, each tab shows it's own cookie belonging to siteC.
-- UPDATE --
With the current version of my code posted here I am now only seeing the cookie issue in the Edge browser. Chrome and IE are sharing a single cookie between siteA and siteB as expected.
Here's an example for sharing data between cross origin sites, using localStorage and postMessage.
site1 : localhost:9091
<html>
<body>
<h1>site 1</h1>
<button id='postBtn'>Post message</button>
<br/>
<iframe id='commonSite' src='http://localhost:9093/commonSite.html' style='height:150px'></iframe>
<script>
(function () {
var commonSite = document.querySelector('#commonSite').contentWindow;
var postCounter = localStorage.getItem('postCounter');
postCounter = postCounter != null ? +postCounter : 1;
var commonOrigin = 'http://localhost:9093';
document.querySelector('#postBtn').onclick = function () {
commonSite.postMessage(postCounter++, commonOrigin);
localStorage.setItem('postCounter', postCounter);
console.log('site 1 posted');
}
})();
</script>
</body>
</html>
site2: localhost:9092
<html>
<body>
<h1>site 2</h1>
<button id='postBtn'>Post message</button>
<br/>
<iframe id='commonSite' src='http://localhost:9093/commonSite.html' style='height:150px'></iframe>
<script>
(function () {
var commonSite = document.querySelector('#commonSite').contentWindow;
var postCounter = localStorage.getItem('postCounter');
postCounter = postCounter != null ? +postCounter : 1;
var commonOrigin = 'http://localhost:9093';
document.querySelector('#postBtn').onclick = function () {
commonSite.postMessage(postCounter++, commonOrigin);
localStorage.setItem('postCounter', postCounter);
console.log('site 2 posted');
}
})();
</script>
</body>
</html>
commonSite: localhost:9093
<html>
<body>
<h3>Common site</h1>
<h4> Site 1 count: <span id='count1'></span></h3>
<h4> Site 2 count: <span id='count2'></span></h3>
<script>
(function () {
console.log('Adding message listener');
var origin1 = 'http://localhost:9091';
var origin2 = 'http://localhost:9092';
var count1 = document.querySelector('#count1');
var count2 = document.querySelector('#count2');
if(localStorage.getItem('count1')) {
count1.textContent = localStorage.getItem('count1');
}
if(localStorage.getItem('count2')) {
count2.textContent = localStorage.getItem('count2');
}
window.addEventListener('message', function (event) {
var origin = event.origin;
var data = event.data;
if(origin === origin1) {
localStorage.setItem('count1', data);
count1.textContent = localStorage.getItem('count1');
} else if(origin === origin2) {
localStorage.setItem('count2', data);
count2.textContent = localStorage.getItem('count2');
}
console.log('received (' + data + ') from ' + origin);
}, false);
})();
</script>
</body>
</html>
Hi I want to put rating stars on my webpage.
Its is working fine. Rating is being added to database
But a user can rate again and again.
I want that stars should disable after rate once.
Here is my code. Kindly help me Thank you.
<!DOCTYPE html>
<html lang="en">
<head>
<link href="http://online-btw-berekenen.nl/rating/rating.css" rel="stylesheet" type="text/css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript" src="http://online-btw-berekenen.nl/rating/rating.js"></script>
<script language="javascript" type="text/javascript">
$(function() {
$("#rating_star").codexworld_rating_widget({
starLength: '5',
initialValue: '',
callbackFunctionName: 'processRating',
imageDirectory: 'images/',
inputAttr: 'postID'
});
});
function processRating(val, attrVal){
$.ajax({
type: 'POST',
url: 'rating.php',
data: 'postID='+attrVal+'&ratingPoints='+val,
dataType: 'json',
success : function(data) {
if (data.status == 'ok') {
alert('You have rated '+val+' to CodexWorld');
$('#avgrat').text(data.average_rating);
$('#totalrat').text(data.rating_number);
}else{
alert('Some problem occured, please try again.');
}
}
});
}
</script>
<style type="text/css">
.overall-rating{font-size: 14px;margin-top: 5px;color: #8e8d8d;}
</style>
</head>
<body style="background-color:black">
<h1>Give us star</h1>
<input name="rating" value="0" id="rating_star" type="hidden" postID="1" />
<div class="overall-rating">(Average Rating <span id="avgrat"><?php echo $ratingRow['average_rating']; ?></span>
Based on <span id="totalrat"><?php echo $ratingRow['rating_number']; ?></span> rating)</span></div>
</body>
</html>
Click and Hover funtion in javascript.
(function(a){
a.fn.codexworld_rating_widget = function(p){
var p = p||{};
var b = p&&p.starLength?p.starLength:"5";
var c = p&&p.callbackFunctionName?p.callbackFunctionName:"";
var e = p&&p.initialValue?p.initialValue:"0";
var d = p&&p.imageDirectory?p.imageDirectory:"images";
var r = p&&p.inputAttr?p.inputAttr:"";
var f = e;
var g = a(this);
b = parseInt(b);
init();
g.next("ul").children("li").hover(function(){
$(this).parent().children("li").css('background-position','0px 0px');
var a = $(this).parent().children("li").index($(this));
$(this).parent().children("li").slice(0,a+1).css('background-position','0px -28px')
},function(){});
g.next("ul").children("li").click(function(){
var a = $(this).parent().children("li").index($(this));
var attrVal = (r != '')?g.attr(r):'';
f = a+1;
g.val(f);
if(c != ""){
eval(c+"("+g.val()+", "+attrVal+")")
}
});
g.next("ul").hover(function(){},function(){
if(f == ""){
$(this).children("li").slice(0,f).css('background-position','0px 0px')
}else{
$(this).children("li").css('background-position','0px 0px');
$(this).children("li").slice(0,f).css('background-position','0px -28px')
}
});
function init(){
$('<div style="clear:both;"></div>').insertAfter(g);
g.css("float","left");
var a = $("<ul>");
a.addClass("codexworld_rating_widget");
for(var i=1;i<=b;i++){
a.append('<li style="background-image:url('+d+'/widget_star.gif)"><span>'+i+'</span></li>')
}
a.insertAfter(g);
if(e != ""){
f = e;
g.val(e);
g.next("ul").children("li").slice(0,f).css('background-position','0px -28px')
}
}
}
})(jQuery);
ok, in you click handler just remove the click event listener using the jquery off() method.
There are a few steps to disable to click and hover events AFTER a user has successfully selected (& recorded) a rating:
Add a line into your ajax success
success : function(data) {
if (data.status == 'ok') {
alert('You have rated '+val+' to CodexWorld');
$('#avgrat').text(data.average_rating);
$('#totalrat').text(data.rating_number);
$('.codexworld_rating_widget').addClass('already_set');
}else{...
Then add a function to disable each hover & click on the <li> in the "http://online-btw-berekenen.nl/rating/rating.js" script. See example below:
g.next("ul").children("li").hover(function(){
if ('.codexworld_rating_widget.alreadyset') {
$('.codexworld_rating_widget').off('click','li').off('hover','li');
}else{
// original script goes here
});
});
Anyways, I'm not able to test it without building a sandbox, so...hope it helps to point you in the right direction.
I have this script below which is used in a survey. The problem I have is, onbeforeunload() works when I don't call a function inside it. If I make any function call(save_survey() or fetch_demographics()) inside it, the browser or the tab closes without any prompt.
<script type="text/javascript">
$(document).ready(function() {
$('#select_message').hide();
startTime = new Date().getTime();
});
loc = 0;
block_size = {{ block_size }};
sid = {{ sid }};
survey = {{ survey|tojson }};
survey_choices = '';
startTime = 0;
demographics_content = {};
function save_survey(sf)
{
var timeSpentMilliseconds = new Date().getTime() - startTime;
var t = timeSpentMilliseconds / 1000 / 60;
var surveydat = '';
if(sf==1)
{ //Success
surveydat = 'sid='+sid+'&dem='+JSON.stringify(demographics_content)+'&loc='+loc+'&t='+t+'&survey_choice='+JSON.stringify(survey_choices);
}
if(sf==0)
{ //Fail
surveydat = 'sid='+sid+'&dem='+json_encode(demographics_content)+'&loc='+loc+'&t='+t+'&survey_choice='+json_encode(survey_choices);
}
//Survey Save Call
$.ajax({
type: 'POST',
url: '/save_surveyresponse/'+sf,
data: surveydat,
beforeSend:function(){
// this is where we append a loading image
$('#survey_holder').html('<div class="loading"><img src="/static/img/loading.gif" alt="Loading..." /></div>');
},
success:function(data){
// successful request; do something with the data
$('#ajax-panel').empty();
$('#survey_holder').html('Success');
alert("Dev Alert: All surveys are over! Saving data now...");
window.location.replace('http://localhost:5000/surveys/thankyou');
},
error:function(){
// failed request; give feedback to user
$('#survey_holder').html('<p class="error"><strong>Oops!</strong> Try that again in a few moments.</p>');
}
});
}
function verify_captcha()
{
// alert($('#g-recaptcha-response').html());
}
function block_by_block()
{
var div_content ='<table border="0" cellspacing="10" class="table-condensed"><tr>';
var ii=0;
var block = survey[loc];
var temp_array = block.split("::");
if(loc>=1)
{
var radio_val = $('input[name=block_child'+(loc-1)+']:checked', '#listform').val();
//console.log(radio_val);
if(radio_val!=undefined)
survey_choices += radio_val +'\t';
else
{
alert("Please select one of the choices");
loc--;
return false;
}
}
for(ii=0;ii<block_size;ii++)
{
//Chop the strings and change the div content
div_content+="<td>" + temp_array[ii]+"</td>";
div_content+="<td>" + ' <label class="btn btn-default"><input type="radio" id = "block_child'+loc+'" name="block_child'+loc+'" value="'+temp_array[ii]+'"></label></td>';
div_content+="</tr><tr>";
}
div_content+='<tr><td><input type="button" class="btn" value="Next" onClick="survey_handle()"></td><td>';
div_content+='<input type="button" class="btn" value="Quit" onClick="quit_survey()"></td></tr>';
div_content+="</table></br>";
$("#survey_holder").html(div_content);
//return Success;
}
function updateProgress()
{
var progress = (loc/survey.length)*100;
$('.progress-bar').css('width', progress+'%').attr('aria-valuenow', progress);
$("#active-bar").html(Math.ceil(progress));
}
function survey_handle()
{
if(loc==0)
{
verify_captcha();
$("#message").hide();
//Save the participant data and start showing survey
fetch_demographics();
block_by_block();
updateProgress();
$('#select_message').show();
}
else if(loc<survey.length)
{
block_by_block();
updateProgress();
}
else if(loc == survey.length)
{
//Save your data and show final page
$('#select_message').hide();
survey_choices += $('input[name=block_child'+(loc-1)+']:checked', '#listform').val()+'\t';
//alert(survey_choices);
//Great way to call AJAX
save_survey(1);
}
loc++;
return false;
}
</script>
<script type="text/javascript">
window.onbeforeunload = function() {
var timeSpentMilliseconds = new Date().getTime() - startTime;
var t = timeSpentMilliseconds / 1000 / 60;
//fetch_demographics();
save_survey(0);
return "You have spent "+Math.ceil(t)+ " minute/s on the survey!";
//!!delete last inserted element if not quit
}
</script>
I have checked whether those functions have any problem but they work fine when I call them from different part of the code. Later, I thought it might be because of unreachable function scope but its not the case. I have tried moving the onbeforeunload() at the end of script and the problem still persists. Wondering why this is happening, can anyone enlighten me?
I identified where the problem was. I am using json_encode instead of JSON.stringify and hence it is crashing(which I found and changed already in sf=1 case). That tip with debugger is invaluable. Also, its working fine even without async: false.
Thank you again #AdrianoRepetti!
My setTimeout seems to be working for logging in, but not for submitting data. :
<script type="text/javascript" src="../scripts/jquery.js"></script>
<script type="text/javascript">
$.ajaxSetup({async:false});
function Validate_submit(form) {
var Address1_input = form.address1.value;
var Address2_input = form.address2.value;
var City_input = form.city.value;
var State_input = form.state.value;
$.post('../scripts/submit_check.php', {address1php: Address1_input, address2php: Address2_input, cityphp: City_input, statephp: State_input},
function(output) {
$('#submit_msg').html(output).fadeIn(500);
if (output == 'Submitting...') {
var timeoutID = window.setTimeout(function () {location.reload();}, 1000);
} else {
$('#submit_msg').html('something went wrong').fadeIn(500);
}
}
);
}
The same code works in my log-in popup window:
<script type="text/javascript" src="../scripts/jquery.js"></script>
<script type="text/javascript">
$.ajaxSetup({async:false});
function Validate_login(form) {
var Email_input = form.email.value;
var Password_input = form.password.value;
var Rememberme_input = form.remember_me.checked;
$.post('../scripts/login_check.php', { emailphp: Email_input, passwordphp: Password_input, rememberphp: Rememberme_input},
function(output) {
$('#login_msg').html(output).fadeIn(500);
if (output == 'Logging in...') {
var timeoutID = window.setTimeout(function () {location.reload();}, 1000);
}
}
);
}
When I click the submit button in the submit form, it shows 'Submitting...' for a split second, but not for the whole second (like in the login-popup). Can someone help me?
You'll probably need to cancel the actual <form>'s submission. return false from the onsubmit handler after you call Validate_submit.