how to trigger jquery call with a variable from a querystring - javascript

Have a problem, I'm about to rebuild the search feature on my site, but I can't make it work as I want to. The problem is that when comes to the page with a querystring 'q' I want the search box to be filled in and a search will begin. I have tested back and forth but can't get it to work. The search works if you type in the search box and wait for 500ms but i don’t manage the trigger the call after the search box is automatic filled in.
This is the code that works without the querystring feature.
<script type="text/javascript">
$(document).ready(function () { // 1
jQuery("abbr.timeago").timeago();
$("tr:even").addClass("even");
$("tr:odd").addClass("odd");
var q = getQuerystring('q', '');
$("input#q").val(q);
}); // 1
$(document).ready(
function () { // 1
// Hide update box
$('#updater').hide();
var retrieveData = function (path, query, funStart, funEnd, funHandleData)
{ // 2
// for displaying updater
funStart();
// retrieve JSON result
$.getJSON(
path,
{ name: query },
function (data)
{ // 3
// handle incoming data
funHandleData(data);
// for hiding updater
funEnd();
} // 3
); // 2
}; // 1
$(function ()
{ // 1
var timer;
$("#q").keyup(function ()
{ // 2
clearTimeout(timer);
var ms = 500; // milliseconds
var val = this.value;
timer = setTimeout(
function ()
{ // 3
retrieveData('/Search/FindPaste/', $('#q')[0].value,
function () { $('#updater').show(); },
function () { $('#updater').hide(); },
function (data)
{ // 4
$('#codelist > tr').remove();
for (s in data)
{ // 5
var code = data[s];
var d1 = new Date(parseInt(code.Created.substr(6)));
$('#codelist').append('<tr><td>' + code.Title + '</td><td><abbr class="timeago" title="' + d1.toString('yyyy-MM-dd HH:mm:ss') + '">' + d1.toString('yyyy-MM-dd HH:mm:ss') + '</abbr></td><td>' + code.Syntax + '</td><td>' + code.Views + '</td><td>' + code.Username + '</td></tr>');
jQuery("abbr.timeago").timeago();
$("tr:even").addClass("even");
$("tr:odd").addClass("odd");
} // 5
}) // 4
}, ms); // 3
}); // 2
}); // 1
}
);
function getQuerystring(key, default_)
{
if (default_ == null) default_ = "";
key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
var qs = regex.exec(window.location.href);
if (qs == null)
return default_;
else
return qs[1];
}
SOLUTION!
<script type="text/javascript">
$(document).ready(function () { // 1
}); // 1
$(document).ready(function () {
// Hide update box
$('#updater').hide();
var retrieveData = function (path, query, funStart, funEnd, funHandleData) { // 2
// for displaying updater
funStart();
// retrieve JSON result
$.getJSON(
path,
{ name: query },
function (data) { // 3
// handle incoming data
funHandleData(data);
// for hiding updater
funEnd();
}
);
};
var timer;
$("#q").keyup(function () { // 2
clearTimeout(timer);
var ms = 500; // milliseconds
var val = this.value;
timer = setTimeout(
function () { // 3
retrieveData('/Search/FindPaste/', $('#q')[0].value,
function () { $('#updater').show(); },
function () { $('#updater').hide(); },
function (data) { // 4
$('#codelist > tr').remove();
for (s in data) { // 5
var code = data[s];
var d1 = new Date(parseInt(code.Created.substr(6)));
$('#codelist').append('<tr><td>' + code.Title + '</td><td><abbr class="timeago" title="' + d1.toString('yyyy-MM-dd HH:mm:ss') + '">' + d1.toString('yyyy-MM-dd HH:mm:ss') + '</abbr></td><td>' + code.Syntax + '</td><td>' + code.Views + '</td><td>' + code.Username + '</td></tr>');
jQuery("abbr.timeago").timeago();
$("tr:even").addClass("even");
$("tr:odd").addClass("odd");
} // 5
}) // 4
}, ms); // 3
}); // 2
jQuery("abbr.timeago").timeago();
$("tr:even").addClass("even");
$("tr:odd").addClass("odd");
var q = getQuerystring('q', '');
$('input#q').val(q).keyup()
}
);
function getQuerystring(key, default_) {
if (default_ == null) default_ = "";
key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
var qs = regex.exec(window.location.href);
if (qs == null)
return default_;
else
return qs[1];
}
</script>

Just populate the box and trigger the change() event on the box.
$('input#q').val(q).change();
EDIT: Or in your case, the keyup event: $('input#q').val(q).keyup()

Related

JavaScript clearTimeout not firing correctly

I have a submit function on a textbox with JavaScript. When the script fires, it checks a Kendo grid for a certain article and adds +1 to its quantity as well as opening the corresponding cell in editing mode. What I want to achieve is that on every submit the timer that starts grid.editCell() will reset its timer.
Currently, the event fires properly. However, the timer doesn't get reset, although the clearTimeout() does work if I just simply start the timer and then clear it right afterwards.
JavaScript:
$('#txtBarcode').submit(function (e) {
var grid = $("#PickListDetailGrid").data("kendoGrid");
var dataSource = $("#PickListDetailGrid").data("kendoGrid").dataSource;
var allData = grid.dataSource.data();
var code = this.value;
var notification = $("#notification").data("kendoNotification");
var timer = null;
clearTimeout(timer);
$.each(allData, function (index, item) {
if (item.ArticleID == code) {
clearTimeout(timer);
timer = null;
if (item.Quantity > item.PickedQuantity && item.PickedQuantity.toString().length < 4) {
var edit = function () {
if (item.PickedQuantity != item.Quantity && timer != null) {
grid.select("tr:eq(" + (index) + ")");
grid.editCell("tr:eq(" + (index + 1) + ") td:eq(" + (5) + ")");
} else {
//do nothing
}
}
item.PickedQuantity++;
item.dirty = true;
dataSource.sync();
if (item.PickedQuantity != item.Quantity) {
console.log("tik tok");
if (timer) {
clearTimeout(timer); //cancel the previous timer.
timer = null;
}
timer = setTimeout(edit, 3000);
} else {
clearTimeout(timer);
timer = null;
}
document.getElementById("txtBarcode").value = "";
} else {
if (item.PickedQuantity.toString().length > 4) {
notification.hide();
notification.show({
message: "Added item"
}, "upload-success");
} else {
notification.hide();
notification.show({
title: "Quantity Error",
message: "You already picked this item to the maximum"
}, "error");
document.getElementById("txtBarcode").value = "";
grid.select("tr:eq(" + (index) + ")");
grid.editCell("tr:eq(" + (index + 1) + ") td:eq(" + (5) + ")");
$('.focus :input').focus();
}
}
}
})
})
You can try delay function like this. The delay function should be outside of the each function.
var delay = (function() {
var timer = 0;
return function(callback, ms) {
clearTimeout(timer);
timer = setTimeout(callback, ms);
};
})();
delay(function() {
//do something
}, 3000);
The problem was that var timer = null; had to be outside of the submit function to be properly cleared and set to null before assigning a new setTimeout() to it.

calling a function and callback not working

So I have a function that checks for Login and runs a few different things. Then I'm trying to call that function later in the page and have it execute another function after that's successful. Maybe my structures not correct, although I've tried moving things around quite a bit and nothing seems to change anything or it breaks my code. Maybe this isn't the best way to this. Any ideas.
function callLogin(callback) {
if (document.getElementById("userLoggedIn") === null) {
$(".cover").fadeIn(200, function() {
$(".sixPinInputContainer").fadeIn(200, function() {
$('.sixPinInput').first().focus()
$("#pageBody").css("overflow", "hidden");
var failedAttempts = 0;
var password = "";
$('.sixPinInput').keyup(function(k) {
//DATA ENTERED INTO FIELD
if (this.value.length == this.maxLength) {
password = password + this.value;
$(this).next('.sixPinInput').focus();
}
//PRESSING DELETE
if (k.keyCode == 8) {
$(this).prev().val("").focus();
password = password.slice(0, -1);
}
password = password.substring(0, 6);
$(".pinIncorrectMessage").css("display", "none");
});
$("#f").keyup(function(callback) {
if ($("#f").val().length > 0) {
$.post("http://heber/QC/includes/pinInput/getUserInfo.php", {
user: password
}, function(data, status) {
password = "";
$(".sixPinInput").val("");
$(data).each(function(index, value) {
var firstName = value.firstName;
var color1 = value.color1;
var color2 = value.color2;
var authorizationLevel = value.authorizationLevel;
var something = value.something;
//IF SUCCESSFUL LOGIN
if (firstName) {
$(".cover").fadeOut(200);
$(".sixPinInputContainer").fadeOut(200);
$("#pageBody").css("overflow", "scroll");
$("#userName").html(firstName);
$("#pageBody").css("background", "radial-gradient(at top left," + color1 + "," + color2 + ")");
$("#userSession").html("<div id='userLoggedIn'></div>");
password = "";
}
//IF FAILED LOGIN
if (!firstName) {
$(".pinIncorrectMessage").css("display", "block");
$(".sixPinInput").first().focus();
$(".sixPinInput").val("");
$("#userName").html(firstName);
$("#pageBody").css("background", "radial-gradient(at top left," + color1 + "," + color2 + ")");
password = "";
failedAttempts = failedAttempts + 1;
if (failedAttempts >= 3) {
alert("If you forgot your password Please have it reset, You have " + (6 - failedAttempts) + " more Attempts");
};
if (failedAttempts >= 6) {
$(".cover").css("background-color", "black").css("z-index", "2000").css("cursor", "none");
}
}
})
})
}
})
});
});
};
callback();
};
Here's where I call the function and it runs the code inside before my login has completed.
callLogin(function() {
$("#" + rowID).load("eventHandlersPHP/updateStart.php", {
roomID: id }, function(data, status) {
$("#notStartedCount").load("eventHandlersPHP/jobsNotStartedCount.php");
});
});
Try moving the call of callback to the point where your request has completed :
//IF SUCCESSFUL LOGIN
if (firstName) {
$(".cover").fadeOut(200);
$(".sixPinInputContainer").fadeOut(200);
$("#pageBody").css("overflow", "scroll");
$("#userName").html(firstName);
$("#pageBody").css("background","radial-gradient(at top left," + color1 + "," + color2 + ")");
$("#userSession").html("<div id='userLoggedIn'></div>");
password = "";
callback();
}

How to execute this function without clicking on a button

So this is a part of greasemonkey userscript. It's an adviser for an online game. At the end of it i've got this:
function do_login() {
// var loc = reg2.exec(document.location.href);
//Auto backing to login page
if (document.location.href.search("logout") != -1) {
window.setTimeout(function () {
document.location.href = "http://www" + gamepage;
}, 100);
}
else {
//login
try {
var logindata = explode(GM_getValue("logindata", "[]"));
}
catch (err) {
var logindata = new Array;
}
unsafeWindow.showDiv("login_div");
$("login_div").style.zIndex = "20";
$("login_div").getElementsByClassName("kh_btn")[0].addEventListener("click", function () {
var currServer = $("l_server").value;
var currUser = $("l_loginname").value.toLowerCase();
GM_setValue(lng + "_" + currServer + "_username", currUser);
}, false);
function submit_login(currUserNr) {
$("l_server").value = logindata[currUserNr][1];
$("l_loginname").value = logindata[currUserNr][2];
$("l_password").value = logindata[currUserNr][3];
$("login_div").getElementsByClassName("kh_btn")[0].click();
}
var newdiv = createElement("div", {style: "position:absolute;top:0px;left:0px;width:412px;padding:10px;background-color:#999;-moz-border-radius:10px;"}, $("login_div"));
for (var v = 0; v < logindata.length; v++) if (logindata[v][1] != "0") {
var newbutton = createElement("button", {type: "button", class: "cursorclickable", id: "autologin" + v, style: "width:200px;height:20px;margin:3px;"}, newdiv, texte["server"] + " " + logindata[v][1] + "." + logindata[v][0] + ": " + logindata[v][2]);
newbutton.addEventListener("click", function () {
submit_login(this.id.replace("autologin", ""));
}, false);
}
newdiv = null;
newbutton = null;
}
}
It's executed when script finds "logout" in the url.
Now, everything works, it's entering main-page, creating a button, the button itself works, but now i would like to execute "onlick" automatically.
You could select the element and then invoke the .click() method:
document.querySelector('#myElement')[0].click();

Javascript tracking script polling

I have the JS tracking code below:
var jTGateway = "trackingurl";
var jTGatewaySSL = "trackingurl";
var jTDomain = "trackingurl";
var jTUser = "";
var jTPage = "";
var jTProtocol = window.location.protocol;
var jTImage = document.createElement('img');
var jTChatElement; var jTSession; var jTUrl;
jTImage.border = 0;
(function () {
if (jTUser == "") {
var dt = new Date(); var jTCookie = document.cookie.toString();
if (jTCookie.indexOf("jtrack") == -1) { jTSession = parseInt(Math.random() * 1000) + "-" + dt.getTime(); document.cookie = "jtrack=" + jTSession + ";expires=Thu, 31-Dec-2020 00:00:00 GMT; path=/"; }
jTCookie = document.cookie.toString();
if (jTCookie.indexOf('jtrack') == -1) { jTSession = ""; } else {
var s = jTCookie.indexOf("jtrack=") + "jtrack=".length; var e = jTCookie.indexOf(";", s);
if (e == -1) e = jTCookie.length; jTSession = jTCookie.substring(s, e);
}
}
if (jTProtocol == "https:") jTGateway = jTGatewaySSL; if (jTUser != "") jTSession = jTUser; if (jTProtocol == "file:") jTProtocol = "http:";
})();
function jTTrackPage() {
if (jTPage == "") jTPage = escape(window.location);
jTUrl = jTProtocol + "//" + jTGateway + "/jtrack.ashx?u=" + jTSession + "&d=" + jTDomain;
jTUrl += "&p='" + jTPage + "'&r='" + escape(document.referrer) + "'";
jTImage.src = jTUrl;
}
I call it on my page like:
<script type='text/javascript' >
if (typeof jTTrackPage == 'function') jTTrackPage();
</script>
My question is, is it possible to have it make the call every 10 seconds say? To show that the user is still on tha page. How would I go about that. Any pointers appreciated. Thanks!
You could either use setInterval:
window.setInterval(jTTrackPage, 10000); // call it every 10 000 ms = 10 s
or setTimeout:
function trackPage() {
jTTrackPage();
window.setTimeout(trackPage), 10000); // call the function again in 10 000 ms
}
trackPage();
The difference between both is that the first one calls it every 10s, and if one call takes more than 10s (unlikely here) the next one will be triggered just after, without waiting 10s. The second solution solves this problem.
You can clear an interval or a timeout using respectively clearInterval and clearTimeout:
var interval = window.setInterval(jTTrackPage, 10000);
window.clearInterval(interval); // <-- stop it
var timeout = window.setTimeout(trackPage, 10000);
window.clearTimeout(timeout); // <-- stop it

Accessing a jQuery Closure function outside

I have this code embedded in my file for managing session time out. This was referred from http://www.fairwaytech.com/2012/01/handling-session-timeout-gracefully/
I want to call SessionManager.extend() for all the ajax request
complete. So i can automatically refresh my session manager time.
This is what i tried
<script type="text/javascript">
$(document).ajaxSuccess(function (event, xhr, settings) {
if (xhr.status === 200) {
SessionManager().extend();
}
});
</script>
Getting an error that SessionManager object not found. How do we call this?
Below is the library code taken from that site
$(function () { // Wrap it all in jQuery documentReady because we use jQuery UI Dialog
// HtmlHelpers Module
// Call by using HtmlHelpers.getQueryStringValue("myname");
var HtmlHelpers = function () {
return {
// Based on http://stackoverflow.com/questions/901115/get-query-string-values-in-javascript
getQueryStringValue: function (name) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
};
} ();
// StringHelpers Module
// Call by using StringHelpers.padLeft("1", "000");
var StringHelpers = function () {
return {
// Pad string using padMask. string '1' with padMask '000' will produce '001'.
padLeft: function (string, padMask) {
string = '' + string;
return (padMask.substr(0, (padMask.length - string.length)) + string);
}
};
} ();
// SessionManager Module
var SessionManager = function () {
// NOTE: globalTimeoutPeriod is defined in _Layout.cshtml
var sessionTimeoutSeconds = HtmlHelpers.getQueryStringValue('smt') || (globalTimeoutPeriod),
countdownSeconds = HtmlHelpers.getQueryStringValue('smc') || 300,
secondsBeforePrompt = sessionTimeoutSeconds - countdownSeconds,
$dlg,
displayCountdownIntervalId,
promptToExtendSessionTimeoutId,
originalTitle = document.title,
count = countdownSeconds,
extendSessionUrl = '/Session/Extend',
expireSessionUrl = '/Session/Expire?returnUrl=' + location.pathname;
var endSession = function () {
$dlg.dialog('close');
location.href = expireSessionUrl;
};
var displayCountdown = function () {
var countdown = function () {
var cd = new Date(count * 1000),
minutes = cd.getUTCMinutes(),
seconds = cd.getUTCSeconds(),
minutesDisplay = minutes === 1 ? '1 minute ' : minutes === 0 ? '' : minutes + ' minutes ',
secondsDisplay = seconds === 1 ? '1 second' : seconds + ' seconds',
cdDisplay = minutesDisplay + secondsDisplay;
document.title = 'Expire in ' +
StringHelpers.padLeft(minutes, '00') + ':' +
StringHelpers.padLeft(seconds, '00');
$('#sm-countdown').html(cdDisplay);
if (count === 0) {
document.title = 'Session Expired';
endSession();
}
count--;
};
countdown();
displayCountdownIntervalId = window.setInterval(countdown, 1000);
};
var promptToExtendSession = function () {
$dlg = $('#sm-countdown-dialog')
.dialog({
title: 'Session Timeout Warning',
height: 250,
width: 350,
bgiframe: true,
modal: true,
buttons: {
'Continue': function () {
$(this).dialog('close');
refreshSession();
document.title = originalTitle;
},
'Log Out': function () {
endSession(false);
}
}
});
count = countdownSeconds;
displayCountdown();
};
var refreshSession = function () {
window.clearInterval(displayCountdownIntervalId);
var img = new Image(1, 1);
img.src = extendSessionUrl;
window.clearTimeout(promptToExtendSessionTimeoutId);
startSessionManager();
};
var startSessionManager = function () {
promptToExtendSessionTimeoutId =
window.setTimeout(promptToExtendSession, secondsBeforePrompt * 1000);
};
// Public Functions
return {
start: function () {
startSessionManager();
},
extend: function () {
refreshSession();
}
};
} ();
SessionManager.start();
});
Remove the var prefix from SessionManager.
Bit of info here about scope, http://msdn.microsoft.com/en-us/library/ie/bzt2dkta(v=vs.94).aspx

Categories

Resources