I am trying to submit a form without a button click or page refresh. Once the form is submitted then I will echo the value in the input field through php. The problem is that I added a timer but is not doing anything at all. How can i set a timer once user stops typing give two seconds(keyup) and then take the value? EXAMPLE
JS
<script>
$(function() {
var timer;
$(".submit").click(function() {
$('submit').on('keyup', function() {
var name = $("#name").val();
var dataString = 'name='+ name;
$.ajax({
type: "POST",
url: "index.php",
data: dataString,
success: function(result){
/*$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();*/
$('#special').append('<p>' + $('#resultval', result).html() + '</p>');
}
});
return false;
});
}, 2000;
});
</script>
PHP
<?php
if($_POST){
$url = $_POST['name'];
echo ('<b><span id="resultval">'.$url.'</span></b>');
}
?>
http://jsfiddle.net/earlonrails/pXA6U/2/
$(function() {
var timer = null;
var dataString;
function submitForm(){
alert("success");
$.ajax({ type: "POST",
url: "index.php",
data: dataString,
success: function(result){
alert("success");
}
});
return false;
}
$('#submit').on('keyup', function() {
clearTimeout(timer);
timer = setTimeout(submitForm, 2000);
var name = $("#name").val();
dataString = 'name='+ name;
});
});
I use the following to provide an auto-refreshing page with a visual timer. It does more than you need, but it could be stripped back to something simpler.
Launch it at page load with
auto_refresh();
Supporting functions below
/**
* This function checks if the auto-refresh check box is checked and then refreshes the page.
*
*
*/
function auto_refresh() {
// ****************************************
// Countdown display
// ****************************************
$("#countdown").progressbar({ value: 100 });
check_refresh(120, 120);
$("#autorefresh").click(function() {
if ($(this).attr("checked") == "checked") {
$("#countdown").progressbar("option", "disabled", false );
$("#countdown").progressbar("option", "value", 100);
check_refresh(120, 120);
}
});
}
And...
/**
* This functions sets the time interval used to auto-refresh the page.
*/
function check_refresh(countdownValue, secondsRemaining) {
var autorefresh = $("#autorefresh");
if ($(autorefresh).attr("checked") == "checked") {
setTimeout(function() {
var value = Math.round(secondsRemaining / countdownValue * 100);
// consoleDebug("Seconds remaining: " + secondsRemaining);
secondsRemaining -= 10;
$("#countdown").progressbar("option", "value", value);
if (secondsRemaining < 0) {
loadDashboard(); // <--- Launch whatever you want here.
check_refresh(120, 120);
} else {
check_refresh(countdownValue, secondsRemaining);
}
}, 10000);
} else {
$("#countdown").progressbar({ disabled: true });
}
}
Related
All code example is here:
I need to add debounce time for this search ( on every keyup delay ) ?
Like keyup. For every maybe 0.5 second delay.
var searchRequest = null;
$(function () {
var minlength = 3;
$("#sample_search").keyup(function () {
var that = this,
value = $(this).val();
console.log('value', value)
if (value.length >= minlength ) {
if (searchRequest != null)
searchRequest.abort();
searchRequest = $.ajax({
type: "GET",
url: "https://jsonplaceholder.typicode.com/comments",
data: {
'search_keyword' : value
},
dataType: "text",
success: function(msg){
//we need to check if the value is the same
if (value==$(that).val()) {
console.log('value real' , msg)
//Receiving the result of search here
}
}
});
}
});
});
Look at the code below.
$("#sample_search").keyup(function() {
// If the user kept typing. Delete the previous timeout.
clearTimeout(delayTime);
// call 'ajaxCall' function after 500ms
var delayTime = setTimeout(ajaxCall, 500);
});
you can use setTimeout() function:
$(function () {
var minlength = 3;
$("#sample_search").keyup(function () {
var that = this,
value = $(this).val();
console.log('value', value);
if (value.length >= minlength ) {
if (searchRequest != null)
searchRequest.abort();
setTimeout(function(){
searchRequest = $.ajax({
type: "GET",
url: "https://jsonplaceholder.typicode.com/comments",
data: {
'search_keyword' : value
},
dataType: "text",
success: function(msg){
//we need to check if the value is the same
if (value==$(that).val()) {
console.log('value real' , msg)
//Receiving the result of search here
}
}
});
}, 500);
}
});
});
I have a start button which triggers a function.
<button type="button" onclick="start()">START</button>
Here is my java script
function start() {
var cookieValue = document.getElementById('balance').getAttribute('value');
if (cookieValue == 0){
alert("insufficient funds");
exit();
}else{
var url = $("#url").val() + '.php?check=';
console.log(url);
var line = $("#ccs").val();
var linesend = line.split("\n");
linesend.forEach(function(value, index) {
setTimeout(
function start() {
Array.prototype.randomElement = function () {
return this[Math.floor(Math.random() * this.length)]
}
$.ajax({
url: url + value,
type: 'GET',
async: true,
success: function(result) {
if (result.match("success")) {
removeline();
live(result);
}else {
removeline();
dead(result);
}
}
});
},2500 * index);
});
}
}
How do I stop this 2500 * index loop right here using a stop function? Cause I wanted a stop button for this one
Clear timeout?
var timeout = setTimeout(start, 2500*index);
clearTimeout(timeout);
i have a script that reload the page when the value is >= 100 the problem is that location.reload(true); are not working in ie11, i also have tried with window.location = self.location.href; but i am having the same problem, in other browsers it works good.
$(function () {
if (value < 100) {
var timer = setInterval(function () {
$.ajax({
type: "GET",
url: $("#ancUrl").attr('href'),
data: {},
success: function (msg) {
console.log("This is msg:" + msg);
var msgInt = parseInt(msg);
if (msgInt > value)
value = msgInt;
},
error: function (err) {
console.log(err.responseText);
},
dataType: "json"
});
$("#progress-bar").width(value.toString() + "%");
if (value >= 100) {
clearInterval(timer);
window.location = self.location.href;
}
}, 2000);
}
});
You don't appear to have defined self anywhere, so you may have an error there. Beyond that, you're trying to assign the value of href as the whole value of location - which is meant to be an object. Instead, try:
window.location.href = window.location.href;
Try to move the if statement into the success callback.
Like that you can clear the interval into the same stack and reload the page on the good
.
$(function() {
if (value < 100) {
var timer = setInterval(function() {
$.ajax({
type: "GET",
url: $("#ancUrl").attr('href'),
data: {},
success: function(msg) {
console.log("This is msg:" + msg);
var msgInt = parseInt(msg);
if (msgInt > value)
value = msgInt;
$("#progress-bar").width(value.toString() + "%");
if (value >= 100) {
clearInterval(timer);
window.location = self.location.href;
}
},
error: function(err) {
clearInterval(timer);
console.log(err.responseText);
},
dataType: "json"
});
}, 2000);
}
});
place the if in the success function, ajax is asynchronous the if will execute immediately but value will change after the ajax has completed so the code may never reach the if statement
$(function () {
if (value < 100) {
var timer = setInterval(function () {
$.ajax({
type: "GET",
url: $("#ancUrl").attr('href'),
data: {},
success: function (msg) {
console.log("This is msg:" + msg);
var msgInt = parseInt(msg);
if (msgInt > value) {
value = msgInt;
$("#progress-bar").width(value.toString() + "%");
if (value >= 100) {
clearInterval(timer);
location.reload(true);
}
}
},
error: function (err) {
console.log(err.responseText);
},
dataType: "json"
});
}, 2000);
}
});
I have a button that is responsible for performing multiple task, and has lot of scripting for it. When this button
<button type="submit" value="submit" name="submit" class="second_button">Negotiate</button>
the script applied on this button is
<script>
var startClock;
var submitamt;
var walkaway;
var digits;
$(function() {
startClock = $('#startClock').on('click', onStart);
submitamt = $('#submitamt').on('click', onSubmit);
walkaway = $('#walkaway').on('click', onWalkAway);
digits = $('#count span');
beforeStart();
});
var onStart = function(e) {
startClock.fadeOut(function() {
startTimer();
submitamt.fadeIn(function() {
submitamt.trigger('click'); // fire click event on submit
});
walkaway.fadeIn();
});
};
var onSubmit = function(e) {
var txtbox = $('#txt').val();
var hiddenTxt = $('#hidden').val();
$.ajax({
type: 'post',
url: 'test2.php',
dataType: 'json',
data: {
txt: txtbox,
hidden: hiddenTxt
},
cache: false,
success: function(returndata) {
console.log(returndata[3]);
// $('#proddisplay').html(returndata);
},
error: function() {
console.error('Failed to process ajax !');
}
});
};
var onWalkAway = function(e) {
console.log('onWalkAway ...');
};
var counter;
var timer;
var startTimer = function() {
counter = 120;
timer = null;
timer = setInterval(ticker, 1000);
};
var beforeStart = function() {
digits.eq(0).text('2');
digits.eq(2).text('0');
digits.eq(3).text('0');
};
var ticker = function() {
counter--;
var t = (counter / 60) | 0; // it is round off
digits.eq(0).text(t);
t = ((counter % 60) / 10) | 0;
digits.eq(2).text(t);
t = (counter % 60) % 10;
digits.eq(3).text(t);
if (!counter) {
clearInterval(timer);
alert('Time out !');
resetView();
}
};
var resetView = function() {
walkaway.fadeOut();
submitamt.fadeOut(function() {
beforeStart();
startClock.fadeIn();
});
};
</script>
before this script executes i wish to check if the user is logged in or not, In normal php i use this code
<?
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true || isset($_SESSION['fb_logged_in']) && $_SESSION['fb_logged_in'] == true )
{?>
<!--display message-->
<?}?>
but i am not able to understand how to embed it with the script i wish to display a popup message if the user is not logged in and ask user to login first
it is not recommended to check it with client side scripting. try it with hidden variable..
<input type="hidden" name="userLog" id="userLog" value="<?=$_SESSION['fb_logged_in'];?>">
and in script check
if($('#userLog')!=''){
// do something..
}
Embed the Session check in the http post. Return an error code (for example 400) when not logged in and process popup handling in the error function.
<?
if (isset($_SESSION['loggedin'])
&& $_SESSION['loggedin'] == true || isset($_SESSION['fb_logged_in'])
&& $_SESSION['fb_logged_in'] == true ) {?>
<!-- display message -->
<?}else{
http_response_code(400);
}?>
I have a script that pulls data from my CMS and then allows a person to vote on a poll. The script works fine. However, I have Ad Block Plus Plugin installed in Firefox. When that is enabled to blocks the script from submitting the form correctly. It appears to submit correctly in the front end but is never registered in the back end.
Why does Ad Block Plus block my script that has nothing to do with ads?
The script is below:
$(document).ready(function () {
var Engine = {
ui: {
buildChart: function() {
if ($("#pieChart").size() === 0) {
return;
}
var pieChartData = [],
totalVotes = 0,
$dataItems = $("ul.key li");
// grab total votes
$dataItems.each(function (index, item) {
totalVotes += parseInt($(item).data('votes'));
});
// iterate through items to draw pie chart
// and populate % in dom
$dataItems.each(function (index, item) {
var votes = parseInt($(item).data('votes')),
votePercentage = votes / totalVotes * 100,
roundedPrecentage = Math.round(votePercentage * 10) / 10;
$(this).find(".vote-percentage").text(roundedPrecentage);
pieChartData.push({
value: roundedPrecentage,
color: $(item).data('color')
});
});
var ctx = $("#pieChart").get(0).getContext("2d");
var myNewChart = new Chart(ctx).Pie(pieChartData, {});
}, // buildChart
pollSubmit: function() {
if ($("#pollAnswers").size() === 0) {
return;
}
var $form = $("#pollAnswers"),
$radioOptions = $form.find("input[type='radio']"),
$existingDataWrapper = $(".web-app-item-data"),
$webAppItemName = $existingDataWrapper.data("item-name"),
$formButton = $form.find("button"),
bcField_1 = "CAT_Custom_1",
bcField_2 = "CAT_Custom_2",
bcField_3 = "CAT_Custom_3",
$formSubmitData = "";
$radioOptions.on("change", function() {
$formButton.removeAttr("disabled"); // enable button
var chosenField = $(this).data("field"), // gather value
answer_1 = parseInt($existingDataWrapper.data("answer-1")),
answer_2 = parseInt($existingDataWrapper.data("answer-2")),
answer_3 = parseInt($existingDataWrapper.data("answer-3"));
if (chosenField == bcField_1) {
answer_1 = answer_1 + 1;
$formSubmitData = {
ItemName: $webAppItemName,
CAT_Custom_1: answer_1,
CAT_Custom_2: answer_2,
CAT_Custom_3: answer_3
};
}
if (chosenField == bcField_2) {
answer_2 = answer_2 + 1;
$formSubmitData = {
ItemName: $webAppItemName,
CAT_Custom_1: answer_1,
CAT_Custom_2: answer_2,
CAT_Custom_3: answer_3
};
}
if (chosenField == bcField_3) {
answer_3 = answer_3 + 1;
$formSubmitData = {
ItemName: $webAppItemName,
CAT_Custom_1: answer_1,
CAT_Custom_2: answer_2,
CAT_Custom_3: answer_3
};
}
prepForm($formSubmitData);
});
function prepForm(formSubmitData) {
$formButton.click(function(e) {
e.preventDefault();
logAnonUserIn("anon", "anon", formSubmitData); // log user in
}); // submit
} // prepForm
function logAnonUserIn(username, password, formSubmitData) {
$.ajax({
type: 'POST',
url: '/ZoneProcess.aspx?ZoneID=-1&Username=' + username + '&Password=' + password,
async: true,
beforeSend: function () {},
success: function () {},
complete: function () {
fireForm(formSubmitData);
}
});
} // logAnonUserIn
function fireForm(formSubmitData) {
// submit the form
var url = "/CustomContentProcess.aspx?A=EditSave&CCID=13998&OID=3931634&OTYPE=35";
$.ajax({
type: 'POST',
url: url,
data: formSubmitData,
async: true,
success: function () {},
error: function () {},
complete: function () {
window.location = "/";
}
});
}
} // pollSubmit
} // end ui
};
Engine.ui.buildChart();
Engine.ui.pollSubmit();
});
As it turns out easylist contains this filter:
.aspx?zoneid=
This is why my script is being blocked.
I was told I can try this exception filter:
##||example.com/ZoneProcess.aspx?*$xmlhttprequest
I could also ask easylist to add an exception.
Answer comes from Ad Block Plus Forums.