setTimeout not working - javascript

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.

Related

jQuery/JavaScript operator equal SQL LIKE %Example%

Is there any way to search a specific part on my input with Javascript/jQuery?
Tried to do with 2 different ways, but no results for that
<script type="text/javascript">
$("#button").click(function () {
$("#DivToToggle").toggle();
var campo = document.getElementById('FieldToSearch');
if (campo.contains("Test")) {
document.getElementById('FieldToWrite').value = "123";
}
else {
document.getElementById('FieldToWrite').value = "456";
}
});
and
<script type="text/javascript">
$("#button").click(function () {
$("#DivToToggle").toggle();
var field = document.getElementById('FieldToSearch');
if (field.match(/Test.*/)) {
document.getElementById('FieldToWrite').value = "123";
}
else {
document.getElementById('FieldToWrite').value = "456";
}
});
#EDIT
Thanks to #TalhaAbrar, found the correct way to do it.
<script type="text/javascript">
$("#button").click(function () {
var field = document.getElementById('FieldToSearch').value;
if (field.indexOf("Test")) {
$("#DivToToggle").toggle();
document.getElementById('FieldToWrite').value = "123";
}
else {
$("#DivToToggle").toggle();
document.getElementById('FieldToWrite').value = "456";
}
});
Try to fetch the value of search field like document.getElementById('FieldToSearch').value and then use function indexOf in your if statement, that should work for you.
example code:
var field = document.getElementById('FieldToSearch').value;
if (field.indexOf("value_to_check")) {
// true if exists
} else {
// false if doesn't
}
I think you need to check the value of the field, e.g.
var campo = document.getElementById('FieldToSearch').value;
...
And then use includes(), e.g.
if (campo.includes("Test")) {
...

AJAX - reload page if JSON has changed

I cannot find a suitable way to achieve this:
I have this script
<script type="text/javascript">
function updateSpots() {
$.ajax({
url : '/epark/api/spots/last',
dataType : 'text',
success : function(data) {
var json = $.parseJSON(data);
var currentMessage = json.dateTime;
var idPosto = json.idPosto;
console.log('current '+currentMessage);
console.log('old '+oldMessage);
if(currentMessage != oldMessage){
setTimeout(function(){location.reload();}, 5000);
$('#idPosto').toggle("higlight");
}
oldMessage = currentMessage;
}
});
}
var intervalId = 0;
intervalId = setInterval(updateSpots, 3000);
var oldMessage ="";
</script>
This should check every 3 seconds if the dateTimehas changed on the JSON.
The problem is that I cannot get to go further first step. I mean, when the page loads, oldMessageempty so the if condition is not satisfied. If I could "jump" this first iteration, then everything would go well...
var oldMessage = false;
//...
if (oldMessage && oldMessage !== currentMessage) {
//...

Javascript 'onbeforeunload()' not working with a function call

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!

Strophe.js Notification Received (Composing)

I am trying to get notified when typing.
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="/js/strophe.min.js"></script>
connection.addHandler(onNotificationReceived, null, "message", "chat", null, null);
function onNotificationReceived(msg)
{
var composing = $(msg).find('composing'),
paused = $(msg).find('paused'),
active = $(msg).find('active'),
jid = $(msg).attr('from');
if (composing.length > 0)
{
$('.chat-feedback').css('display', 'block');
alert(1);
}
if (paused.length > 0)
{
$('.chat-feedback').css('display', 'none');
alert(2);
}
if (active.length > 0)
{
$('.chat-feedback').css('display', 'none');
alert(3);
}
return true;
}
But it does not work :(
Please help!
PS.
Сomplete script http://sitechat.ru/tests/chat1/
You need to parse the response as XML in onNotificationReceived(msg)
var msg = $.parseXML(msg);
And I think you meant
jid = $(msg).find('message').attr('from');

Temporarily remove access to execute function

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().

Categories

Resources