I have an extremely simple little JavaScript/Perl CGI example that I've used to get started with a larger project. When I run it as client.html and server.pl, it works flawlessly. However, when I change the client.html to client.tmpl, and call it from the same server.pl script using Template Toolkit, it can't seem to find jQuery functions.
I have even created a master.tmpl file, and used [% INCLUDE client.html %] inside it, and it fails. The browser console verifies that the path to jquery.js is correct, but it's like it fails to load it when it's inside a template.
The following is the HTML file that I'm essentially trying to turn into a .tmpl file (formatting messed up, first time here, sorry):
client.html
<!DOCTYPE html>
<html>
<head>
<title>AJAX Example</title>
<meta charset="UTF-8" />
<script src="http://domainname/ajax_example/jquery.js"></script>
<script type="text/javascript">
function myTimer() {
var typingTimer;
var doneTypingInterval = 2000;
$("#user_text").keyup( function() {
clearTimeout(typingTimer);
if ( $('#user_text' ).val()) {
typingTimer = setTimeout(updateText, doneTypingInterval);
}
});
function updateText() {
var current_text = document.getElementById('user_text').value;
var http = new XMLHttpRequest();
http.onreadystatechange = function() {
if ( http.readyState == 4 && http.status == 200 ) {
var response = http.responseText;
document.getElementById('server_response').value = response;
}
};
http.open("GET", "http://domainname/ajax_example/cgi-bin/server.pl?user_text=" + current_text , true );
http.send();
}
}
</script>
</head>
<body>
<div>Input Text: <input type="text" id="user_text" name="user_text" onkeyup="myTimer()"/></div><br/>
<div>Server Resp.: <textarea id="server_response" name="server_response"> </textarea></div>
<br/>
</body>
</html>
The server.pl that works:
server.pl
$cgi = CGI->new;
$id = $cgi->param('user_text');
$result = uc($id);
print $cgi->header();
print $result;
The server.pl that doesn't work:
server.pl
$cgi = CGI->new;
$id = $cgi->param('user_text');
**returned from result calculation sub** $result = uc($id);
my $config = {
EVAL_PERL => 1,
POST_CHOMP => 1,
INTERPOLATE => 1,
INCLUDE_PATH => '/usr/lib/cgi-bin/ajax_example/:/var/www/html/ajax_example/',
};
print $cgi->header( -charset=>'utf-8' );
my $tt = Template->new($config);
$tt->process('client.tmpl', \$result);
}
Keep in mind, I am trying my best to summarize the code, but the Perl and JavaScript work just fine, unless it's being used through TT. The error is:
#user_text.keyup is not a function:
("#user_text").keyup(function(){
Same error I would get if I put in a bad path to jquery.js. The path is good though, without a doubt.
Thank you for any recommendations anyone can provide.
The immediate problem is that you have enabled the INTERPOLATE option, which interpolates Perl variables anywhere in the template. That makes the module attempt to replace $( by its value, and destroys the JavaScript syntax
It's a sloppy way of using templates anyway: you should pass all the values you need in the $vars hash, and extract them from there using [% variable %] template directives. The same applies to the EVAL_PERL option, as any complex data manipulation should ordinarily be in the code that calls process. Everything you need to do inside the template is available as a Template directive
Talking of the $vars hash, you should be getting Not a HASH reference errors, because you are passing to process a reference to the string variable $result instead of a hash containing that value. It's unclear how you want that value to be handled, but the only mention of id in your HTML is the id attribute of the <input> element at the bottom of the HTML, so I've put a directive in their to show you how it all works
Take a look at this code
CGI program
use strict;
use warnings 'all';
use CGI;
use Template;
my $cgi = CGI->new;
my $id = $cgi->param('user_text') // 'abc123';
my $result = uc $id;
print $cgi->header( -charset => 'utf-8' );
my $tt = Template->new( {
# INCLUDE_PATH => '/usr/lib/cgi-bin/ajax_example/:/var/www/html/ajax_example/',
POST_CHOMP => 1,
} );
$tt->process('client.html', { result => $result } );
I have modified your HTML file like this. I couldn't tell what you wanted to do with the value that the CGI code pulls from the user_text parameter, so I put it into a value attribute for the first input field
Template file
<!DOCTYPE html>
<html>
<head>
<title>AJAX Example</title>
<meta charset="UTF-8" />
<script src="http://domainname/ajax_example/jquery.js" />
<script type="text/javascript">
function myTimer() {
var typingTimer;
var doneTypingInterval = 2000;
$("#user_text").keyup( function() {
clearTimeout(typingTimer);
if ( $('#user_text' ).val() ) {
typingTimer = setTimeout(updateText, doneTypingInterval);
}
} );
function updateText() {
var current_text = document.getElementById('user_text').value;
var http = new XMLHttpRequest();
http.onreadystatechange = function() {
if ( http.readyState == 4 && http.status == 200 ) {
var response = http.responseText;
document.getElementById('server_response').value = response;
}
};
http.open("GET",
"http://domainname/ajax_example/cgi-bin/server.pl?user_text=" + current_text,
true );
http.send();
}
}
</script>
</head>
<body>
<div>Input Text:
<input type="text" id="user_text" name="user_text" value="[% result %]" onkeyup="myTimer()"/>
</div>
<br/>
<div>Server Resp.:
<textarea id="server_response" name="server_response"/>
</div>
<br/>
</body>
</html>
And here's the resulting output from the CGI code. As you can see, the $("#user_text").keyup call remains intact, and the value from the CGI code—the result element passed in the $vars hash—has been substituted into the value attribute of the text input element
I hope this helps you to progress and get your application working
output
Content-Type: text/html; charset=utf-8
<!DOCTYPE html>
<html>
<head>
<title>AJAX Example</title>
<meta charset="UTF-8" />
<script src="http://domainname/ajax_example/jquery.js" />
<script type="text/javascript">
function myTimer() {
var typingTimer;
var doneTypingInterval = 2000;
$("#user_text").keyup( function() {
clearTimeout(typingTimer);
if ( $('#user_text' ).val() ) {
typingTimer = setTimeout(updateText, doneTypingInterval);
}
} );
function updateText() {
var current_text = document.getElementById('user_text').value;
var http = new XMLHttpRequest();
http.onreadystatechange = function() {
if ( http.readyState == 4 && http.status == 200 ) {
var response = http.responseText;
document.getElementById('server_response').value = response;
}
};
http.open("GET",
"http://domainname/ajax_example/cgi-bin/server.pl?user_text=" + current_text,
true );
http.send();
}
}
</script>
</head>
<body>
<div>Input Text:
<input type="text" id="user_text" name="user_text" value="ABC123" onkeyup="myTimer()"/>
</div>
<br/>
<div>Server Resp.:
<textarea id="server_response" name="server_response"/>
</div>
<br/>
</body>
</html>
Related
I have a heroku website with ruby, but my issue is with one page in particular. The issue with that page is javascript. The page also has ajax on it. Here is my page:
<!DOCTYPE html>
<html>
<head>
<script>
var refreshDelay = 5000000;
function createRequestObject() {
var ro;
if(navigator.appName == "Microsoft Internet Explorer"){
ro = new ActiveXObject("Microsoft.XMLHTTP");
}else{
ro = new XMLHttpRequest();
}
return ro;
}
var http = createRequestObject();
function sndReq() {
var newParent = document.getElementById('2');
var oldParent = document.getElementById('target');
while (document.getElementById('target').childNodes.length > 0) {
newParent.appendChild(document.getElementById('target').childNodes[0]);
}
http.open('post', '/chatContent?n=<%=#name%>');
http.onreadystatechange = handleResponse;
http.send(null);
}
function handleResponse() {
var newParent = document.getElementById('2');
var oldParent = document.getElementById('target');
while (document.getElementById('target').childNodes.length > 0) {
newParent.appendChild(document.getElementById('target').childNodes[0]);
}
if(http.readyState == 4){
var response = http.responseText;
document.getElementById('target').innerHTML = response;
setTimeout(sndReq(), refreshDelay);
}
}
setTimeout(sndReq(), refreshDelay);
</script>
<script>
scrollDown = function() {
document.body.scrollTop = document.body.scrollHeight;
}
</script>
</head>
<body onload='scrollDown()'>
<div id='2'>
</div>
<div id='target'>
<%=#chat%> <!-- #chat is a variable from my ruby file -->
</div>
<form action="/addChat?n=<%=#name%>" method='post'>
<input name='nchat' type='text' autofill='no' style='width:100%;height:10em;vertical-align:top'>
<input type='submit'>
</form>
<a href='/home'>Go home!</a>
</body>
</html>
When I load the page, it gives me this error in the console regarding line 24:
Uncaught TypeError: Cannot read property 'childNodes' of null
But when I enter into the console document.getElementById('target').childNodes.length it gives me however many nodes there are (it changes dynamically). What is going on??
Any extra things you want to see to answer this question I will try to promptly post. Just ask!
You are calling setTimeout(sndReq(), refreshDelay); which will execute sndReq() immediately because of the way you pass the function to setTimeout.
Since your sndReq() is in your head, the HTML will not have fully loaded yet so you are receiving the selector error because the element doesn't exist (yet).
You can change setTimeout(sndReq(), refreshDelay); to setTimeout(sndReq, refreshDelay); to pass the function reference to setTimeout so sndReq() doesn't fire immediately.
Ref: setTimeout
When I do console.log(req.responsetext) i get [11:38:04.967] ReferenceError: req is not defined. But i define req as a new xml request on window load so I am kind of stumped. Is there a way that I should be passing a reference?
the console output is as follows
[12:29:06.839] GET getterms.php?query=DFA [HTTP/1.1 200 OK 99ms]
[12:29:06.888] SyntaxError: JSON.parse: unexpected character # search.php:21
[12:33:24.316] console.log(req.responsetext)
[12:33:24.318] ReferenceError: req is not defined
Any and all help would be most gratefully appreciated. Thank you to anyone who takes the time to read and/or answer even if you cannot help!
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8'>
<title>Auto Complete</title>
</head>
<body>
<script>
window.onload = function () {
var req = new XMLHttpRequest(); //the HTTP request which will invoke the query
var input = document.getElementById('search'); //where to grab the search from
var output = document.getElementById('results'); //where to display the sugestions
input.oninput = getSuggestions;
function getSuggestions() {
req.onreadystatechange = function () {
output.innerHTML = ""; //CLEAR the previous results!! only once the server can process new ones though
if (this.readyState == 4 && input.value != "") {
var response = JSON.parse(req.responseText);
for (var i = 0; i < response.length; i++)
addSuggestion(response[i].terms);
}
}
req.open('GET', 'getterms.php?query=' + input.value, true); //GET request to getterms.php?=
req.send(null);
}
addSuggestion = function (suggestion) {
var div = document.createElement('div');
var p = document.createElement('p');
div.classList.add('suggestion'); //suggestion[x]...
p.textContent = suggestion;
div.appendChild(p);
output.appendChild(div);
div.onclick = function() {
input.value = p.innerHTML; //set the search box
getSuggestions(); //GET new suggesions
}
}
}
</script>
<input type='text' id='search' name='search' autofocus='autofocus'>
<div id='results'></div>
</body>
</html>
edit this is my php page that echos the json.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'On');
if (!isset($_GET['query']) || empty($_GET['query']))
header('HTTP/1.0 400 Bad Request', true, 400);
else {
$db = new PDO(
my database
);
$search_query = $db->prepare("
SELECT * FROM `words` WHERE `word` LIKE :keywords LIMIT 5
");
$params = array(
':keywords' => $_GET['query'] . '%',
);
$search_query->execute($params);
$results = $search_query->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($results);
}
?>
Scope problem! Remove var in front of req to make it global and it should work
So I am trying to make a simple autocomplete form but keep getting a error when I try to test the program.
When I try to test the program my console spits out [11:25:26.267] SyntaxError: JSON.parse: unexpected character # /search.php:22 which is this line. I am pretty sure my syntax is fine but I could be mistaken. Any and all help would be most gratefully appreciated. Thank you to anyone who takes the time to read and/or answer even if you cannot help!
for (var i = 0; i < response.length; i++)
My Full code is as follows.
Edit: Now with page that echos the json. When I do console.log(req.responsetext) i get [11:38:04.967] ReferenceError: req is not defined. But i define req as a new xml request on window load so I am kind of stumped.
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8'>
<title>Auto Complete</title>
</head>
<body>
<script>
window.onload = function () {
var req = new XMLHttpRequest(); //the HTTP request which will invoke the query
var input = document.getElementById('search'); //where to grab the search from
var output = document.getElementById('results'); //where to display the sugestions
input.oninput = getSuggestions;
function getSuggestions() {
req.onreadystatechange = function () {
output.innerHTML = ""; //CLEAR the previous results!! only once the server can process new ones though
if (this.readyState == 4 && input.value != "") {
var response = JSON.parse('(' + req.responseText + ')');
for (var i = 0; i < response.length; i++)
addSuggestion(response[i].terms);
}
}
req.open('GET', 'getterms.php?query=' + input.value, true); //GET request to getterms.php?=
req.send(null);
}
addSuggestion = function (suggestion) {
var div = document.createElement('div');
var p = document.createElement('p');
div.classList.add('suggestion'); //suggestion[x]...
p.textContent = suggestion;
div.appendChild(p);
output.appendChild(div);
div.onclick = function() {
input.value = p.innerHTML; //set the search box
getSuggestions(); //GET new suggesions
}
}
}
</script>
<input type='text' id='search' name='search' autofocus='autofocus'>
<div id='results'></div>
</body>
</html>
edit this is my php page that echos the json.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'On');
if (!isset($_GET['query']) || empty($_GET['query']))
header('HTTP/1.0 400 Bad Request', true, 400);
else {
$db = new PDO(
my database
);
$search_query = $db->prepare("
SELECT * FROM `words` WHERE `word` LIKE :keywords LIMIT 5
");
$params = array(
':keywords' => $_GET['query'] . '%',
);
$search_query->execute($params);
$results = $search_query->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($results);
}
?>
Get rid of the ( and ) in the JSON.parse!
JSON.parse('(' + req.responseText + ')')
should be
JSON.parse( req.responseText );
hopefully the responseText is valid JSON
I am trying to load a text file into my JavaScript file and then read the lines from that file in order to get information, and I tried the FileReader but it does not seem to be working. Can anyone help?
function analyze(){
var f = new FileReader();
f.onloadend = function(){
console.log("success");
}
f.readAsText("cities.txt");
}
Yeah it is possible with FileReader, I have already done an example of this, here's the code:
<!DOCTYPE html>
<html>
<head>
<title>Read File (via User Input selection)</title>
<script type="text/javascript">
var reader; //GLOBAL File Reader object for demo purpose only
/**
* Check for the various File API support.
*/
function checkFileAPI() {
if (window.File && window.FileReader && window.FileList && window.Blob) {
reader = new FileReader();
return true;
} else {
alert('The File APIs are not fully supported by your browser. Fallback required.');
return false;
}
}
/**
* read text input
*/
function readText(filePath) {
var output = ""; //placeholder for text output
if(filePath.files && filePath.files[0]) {
reader.onload = function (e) {
output = e.target.result;
displayContents(output);
};//end onload()
reader.readAsText(filePath.files[0]);
}//end if html5 filelist support
else if(ActiveXObject && filePath) { //fallback to IE 6-8 support via ActiveX
try {
reader = new ActiveXObject("Scripting.FileSystemObject");
var file = reader.OpenTextFile(filePath, 1); //ActiveX File Object
output = file.ReadAll(); //text contents of file
file.Close(); //close file "input stream"
displayContents(output);
} catch (e) {
if (e.number == -2146827859) {
alert('Unable to access local files due to browser security settings. ' +
'To overcome this, go to Tools->Internet Options->Security->Custom Level. ' +
'Find the setting for "Initialize and script ActiveX controls not marked as safe" and change it to "Enable" or "Prompt"');
}
}
}
else { //this is where you could fallback to Java Applet, Flash or similar
return false;
}
return true;
}
/**
* display content using a basic HTML replacement
*/
function displayContents(txt) {
var el = document.getElementById('main');
el.innerHTML = txt; //display output in DOM
}
</script>
</head>
<body onload="checkFileAPI();">
<div id="container">
<input type="file" onchange='readText(this)' />
<br/>
<hr/>
<h3>Contents of the Text file:</h3>
<div id="main">
...
</div>
</div>
</body>
</html>
It's also possible to do the same thing to support some older versions of IE (I think 6-8) using the ActiveX Object, I had some old code which does that too but its been a while so I'll have to dig it up I've found a solution similar to the one I used courtesy of Jacky Cui's blog and edited this answer (also cleaned up code a bit). Hope it helps.
Lastly, I just read some other answers that beat me to the draw, but as they suggest, you might be looking for code that lets you load a text file from the server (or device) where the JavaScript file is sitting. If that's the case then you want AJAX code to load the document dynamically which would be something as follows:
<!DOCTYPE html>
<html>
<head><meta charset="utf-8" />
<title>Read File (via AJAX)</title>
<script type="text/javascript">
var reader = new XMLHttpRequest() || new ActiveXObject('MSXML2.XMLHTTP');
function loadFile() {
reader.open('get', 'test.txt', true);
reader.onreadystatechange = displayContents;
reader.send(null);
}
function displayContents() {
if(reader.readyState==4) {
var el = document.getElementById('main');
el.innerHTML = reader.responseText;
}
}
</script>
</head>
<body>
<div id="container">
<input type="button" value="test.txt" onclick="loadFile()" />
<div id="main">
</div>
</div>
</body>
</html>
This can be done quite easily using javascript XMLHttpRequest() class (AJAX):
function FileHelper()
{
FileHelper.readStringFromFileAtPath = function(pathOfFileToReadFrom)
{
var request = new XMLHttpRequest();
request.open("GET", pathOfFileToReadFrom, false);
request.send(null);
var returnValue = request.responseText;
return returnValue;
}
}
...
var text = FileHelper.readStringFromFileAtPath ( "mytext.txt" );
Javascript doesn't have access to the user's filesystem for security reasons. FileReader is only for files manually selected by the user.
(fiddle:
https://jsfiddle.net/ya3ya6/7hfkdnrg/2/ )
Usage
Html:
<textarea id='tbMain' ></textarea>
<a id='btnOpen' href='#' >Open</a>
Js:
document.getElementById('btnOpen').onclick = function(){
openFile(function(txt){
document.getElementById('tbMain').value = txt;
});
}
Js Helper functions
function openFile(callBack){
var element = document.createElement('input');
element.setAttribute('type', "file");
element.setAttribute('id', "btnOpenFile");
element.onchange = function(){
readText(this,callBack);
document.body.removeChild(this);
}
element.style.display = 'none';
document.body.appendChild(element);
element.click();
}
function readText(filePath,callBack) {
var reader;
if (window.File && window.FileReader && window.FileList && window.Blob) {
reader = new FileReader();
} else {
alert('The File APIs are not fully supported by your browser. Fallback required.');
return false;
}
var output = ""; //placeholder for text output
if(filePath.files && filePath.files[0]) {
reader.onload = function (e) {
output = e.target.result;
callBack(output);
};//end onload()
reader.readAsText(filePath.files[0]);
}//end if html5 filelist support
else { //this is where you could fallback to Java Applet, Flash or similar
return false;
}
return true;
}
my example
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
</head>
<body>
<script>
function PreviewText() {
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("uploadText").files[0]);
oFReader.onload = function(oFREvent) {
document.getElementById("uploadTextValue").value = oFREvent.target.result;
document.getElementById("obj").data = oFREvent.target.result;
};
};
jQuery(document).ready(function() {
$('#viewSource').click(function() {
var text = $('#uploadTextValue').val();
alert(text);
//here ajax
});
});
</script>
<object width="100%" height="400" data="" id="obj"></object>
<div>
<input type="hidden" id="uploadTextValue" name="uploadTextValue" value="" />
<input id="uploadText" style="width:120px" type="file" size="10" onchange="PreviewText();" />
</div>
Source file
</body>
</html>
This is an old question but I think in 2022 there are ES6 ways to handle this:
const $node = document.getElementById('output')
const $file = document.getElementById('file')
const processTextByLine = text => {
const arr = text.split(/\r?\n/gm)
arr.map(line => console.log(line))
}
const openFile = event => {
const input = event.target
if (!input) throw new Error('null input')
const [first] = input.files
const reader = new FileReader()
reader.onload = () => {
const text = reader.result
$node.innerText = text
processTextByLine(text)
}
reader.readAsText(first)
}
$file.onchange = openFile
<input id='file' type='file' accept='text/plain'><br>
<div id='output'>
...
</div>
If your file is encoded using UTF-8 then we can make an async call using Blob.text()
const $node = document.getElementById('output')
const $file = document.getElementById('file')
const processTextByLine = text => {
const arr = text.split(/\r?\n/gm)
arr.map(line => console.log(line))
}
const openFile = async event => {
const input = event.target
if (!input) throw new Error('null input')
const [file] = input.files
const text = await file.text()
$node.innerText = text
processTextByLine(text)
}
$file.onchange = openFile
<input id='file' type='file' accept='text/plain'><br>
<div id='output'>
...
</div>
Note:
processTextByLine() function is not needed, it just shows a case if we need to process the file line by line.
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().