Change query argument of jQuery suggest plugin - javascript

This question is kind-of crappy because I try to get around some limitations:
Current JS sends an ajax query with the following code
jQuery('#searchbox').suggest('/?live=1');
What the server get is the following query string:
?live=1&q=searchstring
Problem:
The server expects the query string to be preceded with 's=' not 'q='
I have to use the existing scripts so what I'm trying to so is find a way to change 'q=' to 's=' in javascript, without altering the exisiting suggest plugin or the php search script.
Thanks.

The only way you will do that is by modifying the plugin, if you want to avoid changing the script forever and need this only for one page, override the function temporarily.
$.suggest.suggest = function() {
var q = $.trim($input.val());
if (q.length >= options.minchars) {
cached = checkCache(q);
if (cached) {
displayItems(cached['items']);
} else {
//This is the line we r changing
$.get(options.source, {s: q}, function(txt) {
$results.hide();
var items = parseTxt(txt, q);
displayItems(items);
addToCache(q, items, txt.length);
});
}
} else {
$results.hide();
}
}

Related

How to detect if any of css/js files failed to load and alert user to refresh browser [duplicate]

I have an HTML page where several JavaScript, CSS and images files are referenced. These references are dynamically injected and user can manually copy the HTML page and the support files to another machine.
If some JS or CSS are missing, the browser complains in the console. For example:
Error GET file:///E:/SSC_Temp/html_005/temp/Support/jquery.js
I need somehow these errors reported back to me on the inline JavaScript of the HTML page so I can ask user to first verify that support files are copied correctly.
There's the window.onerror event which just inform me that there's a JS error on the page such as an Unexpected Syntax error, but this doesn't fire in the event of a 404 Not Found error. I want to check for this condition in case of any resource type, including CSS, JS, and images.
I do not like to use jQuery AJAX to verify that file physically exists - the I/O overhead is expensive for every page load.
The error report has to contain the name of the file missing so I can check if the file is core or optional.
Any Ideas?
To capture all error events on the page, you can use addEventListener with the useCapture argument set to true. The reason window.onerror will not do this is because it uses the bubble event phase, and the error events you want to capture do not bubble.
If you add the following script to your HTML before you load any external content, you should be able to capture all the error events, even when loading offline.
<script type="text/javascript">
window.addEventListener('error', function(e) {
console.log(e);
}, true);
</script>
You can access the element that caused the error through e.target. For example, if you want to know what file did not load on an img tag, you can use e.target.src to get the URL that failed to load.
NOTE: This technically will not detect the error code, it detects if the image failed to load, as it technically behaves the same regardless of the status code. Depending on your setup this would probably be enough, but for example if a 404 is returned with a valid image it will not trigger an error event.
you can use the onload and onerror attributes to detect the error
for example upon loading the following html it gives alert error1 and error2 you can call your own function e.g onerror(logError(this);) and record them in an Array and once the page is fully loaded post is with single Ajax call.
<html>
<head>
<script src="file:///SSC_Temp/html_005/temp/Support/jquery.js" onerror="alert('error1');" onload="alert('load');" type="text/javascript" ></script>
</head>
<body>
<script src="file:///SSC_Temp/html_005/temp/Support/jquery.js" onerror="alert('error2');" onload="alert('load');" type="text/javascript" ></script>
</body>
</html>
I've put together the code below in pure JavaScript, tested, and it works.
All the source code (html, css, and Javascript) + images and example font is here: on github.
The first code block is an object with methods for specific file extensions: html and css.
The second is explained below, but here is a short description.
It does the following:
the function check_file takes 2 arguments: a string path and a callback function.
gets the contents of given path
gets the file extension (ext) of the given path
calls the srcFrom [ext] object method that returns an array of relative paths that was referenced in the string context by src, href, etc.
makes a synchronous call to each of these paths in the paths array
halts on error, and returns the HTTP error message and the path that had a problem, so you can use it for other issues as well, like 403 (forbidden), etc.
For convenience, it resolves to relative path names and does not care about which protocol is used (http or https, either is fine).
It also cleans up the DOM after parsing the CSS.
var srcFrom = // object
{
html:function(str)
{
var prs = new DOMParser();
var obj = prs.parseFromString(str, 'text/html');
var rsl = [], nds;
['data', 'href', 'src'].forEach(function(atr)
{
nds = [].slice.call(obj.querySelectorAll('['+atr+']'));
nds.forEach(function(nde)
{ rsl[rsl.length] = nde.getAttribute(atr); });
});
return rsl;
},
css:function(str)
{
var css = document.createElement('style');
var rsl = [], nds, tmp;
css.id = 'cssTest';
css.innerHTML = str;
document.head.appendChild(css);
css = [].slice.call(document.styleSheets);
for (var idx in css)
{
if (css[idx].ownerNode.id == 'cssTest')
{
[].slice.call(css[idx].cssRules).forEach(function(ssn)
{
['src', 'backgroundImage'].forEach(function(pty)
{
if (ssn.style[pty].length > 0)
{
tmp = ssn.style[pty].slice(4, -1);
tmp = tmp.split(window.location.pathname).join('');
tmp = tmp.split(window.location.origin).join('');
tmp = ((tmp[0] == '/') ? tmp.substr(1) : tmp);
rsl[rsl.length] = tmp;
}
});
});
break;
}
}
css = document.getElementById('cssTest');
css.parentNode.removeChild(css);
return rsl;
}
};
And here is the function that gets the file contents and calls the above object method according to the file extension:
function check_file(url, cbf)
{
var xhr = new XMLHttpRequest();
var uri = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onload = function()
{
var ext = url.split('.').pop();
var lst = srcFrom[ext](this.response);
var rsl = [null, null], nds;
var Break = {};
try
{
lst.forEach(function(tgt)
{
uri.open('GET', tgt, false);
uri.send(null);
if (uri.statusText != 'OK')
{
rsl = [uri.statusText, tgt];
throw Break;
}
});
}
catch(e){}
cbf(rsl[0], rsl[1]);
};
xhr.send(null);
}
To use it, simply call it like this:
var uri = 'htm/stuff.html'; // html example
check_file(uri, function(err, pth)
{
if (err)
{ document.write('Aw Snap! "'+pth+'" is missing !'); }
});
Please feel free to comment and edit as you wish, i did this is a hurry, so it may not be so pretty :)
#alexander-omara gave the solution.
You can even add it in many files but the window handler can/should be added once.
I use the singleton pattern to achieve this:
some_global_object = {
error: (function(){
var activate = false;
return function(enable){
if(!activate){
activate = true;
window.addEventListener('error', function(e){
// maybe extra code here...
// if(e.target.custom_property)
// ...
}, true);
}
return activate;
};
}());
Now, from any context call it as many times you want as the handler is attached only once:
some_global_object.error();

Import keywords into ace editor highlighter in webpy server (python)

I am using the Javascript Ace text editor and need to load keywords into the (DynHighlightRules) to provide highlighting of the imported keywords. I have highlights working from static keywords in the
editor.getSession().setMode("ace/mode/highlightRules")
, but I need to import new rules after the editor is rendered. I found a great solution which works perfectly in an Apache server but not in the Web.py python server. I believe this is due to the template page not being at the root level of the server. Has anyone deployed the Ace editor in Webpy and solved this issue?
Ok, I found a solution to my problem. It's a work around and not the way I was originally going to solve the issue. My first attempts were to embed an ajax call in the "ace.define" function but it wouldn't process it correctly and parts would be missing causing errors. Then I tried to dynamically import the keywords but couldn't make that work in the python environment. Finally I thought to just wrap the whole thing in the success of the ajax call and now it works exactly right. I guess when embedded in the ace function the timing between the ajax events and the other parts of the definition were out of sync.
So the answer in short is to wrap the whole definition in the ajax success callback.
$.ajax({
url: "/readUserCreatedKeywords",
type: "POST",
success: function(response){
var keywordsString = "";
var tmpArr = response.split(",");
var tmpArrLen = tmpArr.length;
var s = 0;
var halfNum = 0;
while (s < tmpArrLen) { // Clean array and save keywords and args into respective arrays
halfNum = parseInt(s/2);
tmpArr[s] = tmpArr[s].replace("u'", "").replace("[", "").replace("'", "").replace("(u", "").replace(")", "").replace("]", "").replace("(", "").replace(" ", "");
if (s % 2 == 0){ //Store even values in keywords
keywordsString += tmpArr[s] + "|";
//console.log("tmpArr[" + s + "]" + tmpArr[s]);
}
s++;
}
ace.define("ace/mode/python_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) {
...............................................lots of code..........................................
exports.Mode = Mode;
});
}
});

Java script URL Loader and URL Varialbles

I have a URL to a text file which specifies what my menu controller is called and whether I am in debug mode etc....
eg. menudriver=MenuController.aspx&debug=true&webroot=https://somewebsite.com
Now what I would like to do is have this loaded into a variable in javascript then also each URL variable also saved into some array.
Once this has been done I have a menu that is dynamically populated according to what is received from a separate URL. Here is an as3 example:
var request:URLRequest = new URLRequest(WebRoot+fill+CallerURI+"?KR_ID="+Math.random());
This URL basically contains labels as well as URI for buttons in my menu.
How is this done is javascript?
I do have a completed implementation in as3 but I am battling to find the javascript alternatives.
in Reply to the comment, pure javascript solution
var query = (function() {
function decode(string) {
return decodeURIComponent(string.replace(/\+/g, " "));
}
var result = {};
if (location.search) {
location.search.substring(1).split('&').forEach(function(pair) {
pair = pair.split('=');
result[decode(pair[0])] = decode(pair[1]);
});
}
return result;
})();
it use ECMAScript 5 function forEach, if you need to support browsers that don't support it, you can use es5-shim.

KDE plasmoid ind autorefresh

I'm trying to write KDE4 plasmoid in JavaScript, but have not success.
So, I need to get some data via HTTP and display it in Label. That's working well, but I need regular refresh (once in 10 seconds), it's not working.
My code:
inLabel = new Label();
var timer= new QTimer();
var job=0;
var fileContent="";
function onData(job, data){
if(data.length > 0){
var content = new String(data.valueOf());
fileContent += content;
}
}
function onFinished(job) {
inLabel.text=fileContent;
}
plasmoid.sizeChanged=function()
{
plasmoid.update();
}
timer.timeout.connect(getData);
timer.singleShot=false;
getData();
timer.start(10000);
function getData()
{
fileContent="";
job = plasmoid.getUrl("http://192.168.0.10/script.cgi");
job.data.connect(onData);
job.finished.connect(onFinished);
plasmoid.update();
}
It gets script once and does not refresh it after 10 seconds. Where is my mistake?
It is working just fine in here at least (running a recent build from git master), getData() is being called as expected. Can you see any errors in the console?
EDIT: The problem was that getUrl() explicitly sets NoReload for KIO::get() which causes it load data from cache instead of forcing a reload from the server. Solution was to add a query parameter to the URL in order to make it force reload it.

How to get timezone before postback

I am making a page that accepts post data from any number of pages that I cannot change, access, or in any way control.
I need, in one way or another, to get the timezone of the user. I know, ideally the posting page would do this, but I cannot access these pages.
I've read other answers on this site and come up with 2 almost, but not quite there solutions.
First, there is javascript. I can get the javascript function to return (or change a label to) the correct value, but the problem is I need this info before the postback. I've been trying to write the timezone name on another page and read that page, but I have no idea how to begin to do that? Any other workaround to use the javascript is welcome, or any way to force call this before Page_Load is called?
function getTimeZone()
{
var d = new Date()
var gmtHours = -d.getTimezoneOffset()/60;
var label = document.getElementById("<%=TZ.ClientID%>");
label.textContent = "GMT " + gmtHours;
}
The second solution is to read it from another page, and I am using this:
http://ipinfodb.com/ip_query.php?ip=192.36.167.120&timezone=true
(Completely random ip in there, btw)
So here is my function to get the info from that site:
public string GetTimezone(string ip)
{
string address = string.Format("http://ipinfodb.com/ip_query.php?ip={0}&timezone=true", ip);
string timezone = "";
try
{
XmlTextReader reader = new XmlTextReader(address);
HttpWebRequest wrq = (HttpWebRequest)WebRequest.Create(address);
wrq.Proxy.Credentials = CredentialCache.DefaultCredentials;
reader = new XmlTextReader(wrq.GetResponse().GetResponseStream());
string lastRead = "";
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
lastRead = reader.Name;
}
if (reader.NodeType == XmlNodeType.Text)
{
if (string.Compare(lastRead, "TimezoneName", true) == 0)
{
timezone = reader.Value;
break;
}
}
}
}
catch
{
timezone = "";
}
return timezone;
}
Basically, this works in debug mode, but when it's live only an empty string is returned. I am baffled? Is there any better way to read data from a page? I am using Request.ServerVariables["REMOTE_ADDR"] to get the ip, and that seems to be correct, since it inserts the correct ip into the database I'm using.
Here is the call:
GetTimezone(Request.ServerVariables["REMOTE_ADDR"]);
You're getting an exception, probably because of a trust issue / firewall on the production server.
Get rid of the evil catch block so you can find out what the exception is.

Categories