How can I execute a simple webrequest in javascript.
Such as
var str = *whatever_comes_back_from*("search.php?term=hello");
This is usually handed via XMLHttpRequest, usually abstracted via a library that irons out the differences between browsers (bigger libraries that do lots of other stuff include YUI and jQuery).
You could use jQuery, or another javascript library, but instead of thinking of populating the variable then continueing with the script in a linear way, you should think in terms of a callback once the value is retrieved, because it can take a variable amount of time to retrieve the data.
This event based architecture is a feature of javascript that is rare in other programming languages.
$.get('search.php?term=hello', function(data){
alert(data)
});
Related
Is there any other way to call a JavaScript function stored in MongoDB from node.js other than db.eval()?
Tried db.eval() since its degrading my server performance, I'm have to use some other methods to invoke the JavaScript functions
Try including jQuery and comparing jQuery.getScript performance to eval()
with the new Function you avoid eval();
var mydbfunction=new Function('here the function string');
mydbfunction();
this executes the function directly
(new Function('here the function string'))()
The logical answer is no, not if you wish to evaluate from within MongoDB. This is due to the way that eval is actually extended and manipulated within the JavaScript engine implementation in MongoDB.
Instead you should avoid eval. Most likely you have coded your application in such manner that makes use of these stored JavaScript functions as though they are stored procedures. That is not the case, they are not stored procedures and definitely should not be used application side if at all possible.
That being said storing JavaScript isn really useful for Map Reduces who use common code. You can just include the saved code in the system.js collection and jobs a good'un.
When I saw this question I thought it would be helpful if a jQuery compiler could be written. Now, by compiler, I mean something that takes in jQuery code and outputs raw javascript code that is ultimately executed.
This is how I vision a block of jQuery code execution:
a jQuery function is called and parameters are passed to it
the function calls a raw javascript function and passes the parameters it received to it
the newly called function performs the intended action
I understand that this is a very simplified model and it could be much more complex, but I think the complexity is reduced to steps 2 and 3 being repeated with different raw js functions being called and each time fed with all or a subset of parameters / previous results.
If we subscribe to that model, then we might come up with methods to make the jQuery functions perform double-duty:
What they already do
Logging what they did in form of raw_function(passed_params)
Am I making some wrong assumptions that would make this impossible?
Any ideas how Firebug's profiler attempts to get function names? Could it be used here?
Edit
What I was thinking was making a black box with input / output as:
normal jquery code → [BB] → code you'd write if you used no library
I called this a compiler, because you compiled once and then would use the resulting code.
I argued that it could have at least educational use, and probably other uses as well.
People said this would take in a small amount of code and output a huge mass; that does not defy the intended purpose as far as I see
People said I'd be adding an extra, needless step to page rendering, which, given only the resulting code would ultimately be used (and probably be used just for studying), is not correct.
People said there is no one-to-one relation between javascript functions and jquery functions, and implied such a converter would be too complicated and probably not worth the effort. With this I now agree.
Thank you all!
I think what you mean is: if you write
var myId = $("#myId")
it will be converted to
var myId = document.getElementById("myId")
I think its possible, but the problem is, jQuery functions return jQuery objects, so in the above example, the first myId will be a jQuery object & the second will be a node object(i think) which will affect other functions that needs to use it later in the code after compilation. Especially if they are chained
secondly you will have to be sure that the conversion actually has performance benefits.
However if you are aware of all this and you can plan you code accordingly, i think it will be possible
If the purpose of the compiler to convert Javascript (which may be jquery or anything) to better Javascript (which I understood from you saying "ultimately executed"), then Google has already done that. They made closure compiler and some have tried it with JQuery in this post. Isn't this what you are suggesting ?
jQuery code is "raw JavaScript code" so I'm not sure what a compiler would really buy you. That's like writing a C# compiler which takes C# 4.0 code and emits C# 1.1 code. What's the benefit?
jQuery isn't a different language which replaces or even sits on top of JavaScript. It's a framework of JavaScript code which provides lots of useful helpers for common tasks. In my view, it's greatest benefit is that its distinctive structure helps to differentiate it from the more "Java-like" languages.
JavaScript by itself is deceptively similar to other languages and this tends to be one of its biggest faults as a language. People try to think of it in terms of Java, even though the similarities pretty much stop at the name. Structurally, JavaScript is very different in many ways (typing, scope, concurrence, inheritance, polymorphism, etc.) and I particularly like how jQuery and other modern JavaScript projects have brought the language to stand on its own merits.
I guess to get back to the question... If you're looking to turn jQuery-style JavaScript into Java-style JavaScript, then that's something of a step backwards. Both versions would be interpreted by the browser the same way, but one of the versions is less elegant and represents the language more poorly than the other.
Note that jQuery isn't the only framework that does these things, it's just the most popular. Would such a compiler need to also handle all the other frameworks? They all do different things in different ways to take advantage of the language. I don't think that homogenizing them to a "simpler" form buys us anything.
Edit: (In response to the various comments around this question and its answers, kind of...
How would you structure this compiler? Given that (as we've tried to point out) jQuery is JavaScript and is just a library of JavaScript code, and given how browsers and JavaScript work, your "compiler" would just have to be another JavaScript library. So essentially, what you want is to go from:
A web page
The jQuery library
Some JavaScript code which uses the jQuery library
to:
A web page
The jQuery library
Some JavaScript code which uses the jQuery library
Your "compiler" library
Some more JavaScript code which sends the previous JavaScript code through your library somehow
Your "jQuery-equivalent" library
Some more JavaScript code which replaces the original JavaScript code with your new version
in order to make things simpler? Or to somehow make debugging tools like FireBug easier to use? What you're proposing is called an "obfuscator" and its sole purpose is to make code more difficult to reverse-engineer. A side effect is that it also make code more difficult to understand and maintain.
Now, by compiler, I mean something
that takes in jQuery code and outputs
raw javascript code that is ultimately
executed.
I think that statement may indicate what's going wrong for you.
jQuery is a library implemented in the Javascript language. jQuery isn't a language separated from Javascript. jQuery is a collection of Javascript code that you can use to make Javascript development easier. It's all Javascript. A "jQuery compiler" to convert "jQuery code" to "raw Javascript" would be quite useless because jQuery is raw Javascript.
What you probably actually want is a Javascript compiler. In that case, it's certainly possible. In fact, some web browsers nowadays actually "compile" on the Javascript code in some kind of bytecode to enhance performance. But development workflows involving Javascript typically don't involve a compiler tool of some kind.
Apparently what you actually want is to "inline" jQuery code into your code, sort of like this:
var myfoo = $('#foo'); → var myfoo = document.getElementById('foo');
This is actually something a C++ compiler would do to optimize performance, but Javascript is not C++ so it doesn't apply here.
I don't see how this is useful. The point of jQuery is to simplify Javascript development by providing a consistent interface like the $() function. By performing this "inlining" procedure you produce code that is even harder to read and maintain.
And why add an extra step? Why not just deliver the application javascript code and the jQuery library to the browser? Why add an extra step involving an extra tool to convert Javascript to Javascript that doesn't provide any substantial extra benefits?
I'm learning javascript. Poked around this excellent site to gather intel. Keep coming across questions / answers about javascript, JQUERY, JQUERY with AJAX, javascript with JQUERY, AJAX alone. My conclusion: these are all individually powerful and useful. My confusion: how does one determine which/which combination to use ?
I've concluded that javascript is readily available on most browsers. For example, I can extend a simple HTML page with
<html>
<body>
<script type="text/javascript">
document.write("Hello World!");
</script>
</body>
</html>
However, within the scope of Python/DJANGO, many of these questions are JQUERY and AJAX related. At which point or under what development circumstances would I conclude that javascript alone isn't going to "cut it", and I need to implement JQUERY and/or AJAX and/or some other permutation ?
Javascript is code that runs client-side in the browser.
AJAX is a term used to refer to the process of Javascript contacting the webserver directly and getting a response as opposed to the user navigating to a different page
jQuery is a javascript library that provides an easy-to-use abstraction over top of AJAX and the browser DOM
Django is Python code that runs server-side
In some situations you can do the same operation on either the client or on the server. Typically however, you determine if it should be done client/server by asking yourself, "where is the resource that needs to be used located?" For example, querying a database would be done on the webserver, because that's where that resource is. Conversely re-arranging the webpage's UI is done client-side, because that's where the the UI is.
Javascript alone can always "cut it", but the advantage jQuery brings is that it makes things easier and faster, and cuts out a lot of the browser issues in doing AJAX and DOM manipulation.
Since you are new to Javascript development, I'll try with relatable examples.
You can vote questions up or down on StackOverflow. Your vote action is sent to the server, and it gets recorded there. Had it not been for AJAX (and some other techniques), the entire page would need to be refreshed for that one action. AJAX solves the problem of asynchronously communicating with a server without requiring full page reloads.
jQuery is a library that provides convenient access to common Javascript tasks such as DOM manipulation, AJAX handling, etc. jQuery also hides away browser differences and provides a consistent interface for the end user. To illustrate these two points, see these examples:
finding all div elements on the page
// Javascript
var divs = document.getElementsByTagName("div")
// jQuery
$("div")
adding a click event handler to a button (illustrates browser differences)
With pure Javascript, it's best to create a cross-browser method to add events, as you surely wouldn't want to write this code every single time. Source - http://www.scottandrew.com/weblog/articles/cbs-events
function addEvent(obj, evType, fn, useCapture){
if (obj.addEventListener) { // standards-based browsers
obj.addEventListener(evType, fn, useCapture);
return true;
} else if (obj.attachEvent) { // IE
var r = obj.attachEvent("on"+evType, fn);
return r;
} else { // some unknown browser
alert("Handler could not be attached");
}
}
Once this is setup (one-time only), you can add events to any elements using this function.
// Javascript
var button = document.getElementById("buttonID");
addEvent(button, "click", function() { alert("clicked"); }, false);
// jQuery (contains code similar to above function to handle browser differences)
$("#buttonID").click(function() { alert("clicked"); });
AJAX is part of Javascript and not a separate technology in itself. You would use AJAX to avoid doing full page refreshes when you need to send/receive data from the server.
jQuery, MooTools, Dojo, Ext.JS, Prototype.JS, and many other libraries provide a wrapper around Javascript to abstract away browser differences, and provide an easier interface to work with. The question is would you want to do all of this re-work yourselves. If you're not exactly sure what re-work you may need to do, researching pure Javascript examples of common tasks such as AJAX calls, DOM manipulation, event handling, along with abstracting away browser quirks and comparing those to examples to equivalents in libraries such as jQuery might be a good start.
The reason are exactly the same as you choose to use Django instead of Python alone.
jQuery is javascript library which will make your life easier and extends javascript.
Beyond the fact that jQuery is useful, I advise you to learn javascript first, as you should have learnt python before to use Django.
To resume :
pure javascript => simple code, native function exists for what you need
jQuery => complex code, rich application, functions doesn't exists in pure javascript ($.each() method for example).
JSON allows you to retrieve data in multiple formats from an AJAX call. For example:
$.get(sourceUrl, data, callBack, 'json');
could be used to get and parse JSON code from sourceUrl.
JSON is the simply JavaScript code used to describe data. This could be evaled by a JavaScript interpreter to get a data structure back.
It's generally a bad idea to evaluate code from remote sources. I know the JSON spec doesn't specifically allow for function declarations, but there's no reason you couldn't include one in code and have an unsafe and naive consumer compile/execute the code.
How does jQuery handle the parsing? Does it evaluate this code? What safeguards are in place to stop someone from hacking sourceUrl and distributing malicious code?
The last time I looked (late 2008) the JQuery functions get() getJSON() etc internally eval the JSon string and so are exposed to the same security issue as eval.
Therefore it is a very good idea to use a parsing function that validates the JSON string to ensure it contains no dodgy non-JSON javascript code, before using eval() in any form.
You can find such a function at https://github.com/douglascrockford/JSON-js/blob/master/json2.js.
See JSON and Broswer Security for a good discussion of this area.
In summary, using JQuery's JSON functions without parsing the input JSON (using the above linked function or similar) is not 100% safe.
NB: If this sort of parsing is still missing from getJSON (might have recently been added) it is even more important to understand this risk due to the cross domain capability, from the JQuery reference docs:
As of jQuery 1.2, you can load JSON
data located on another domain if you
specify a JSONP callback, which can be
done like so: "myurl?callback=?".
jQuery automatically replaces the ?
with the correct method name to call,
calling your specified callback.
$.getJSON() is used to execute (rather than using eval) javascript code from remote sources (using the JSONP idiom if a callback is specified). When using this method, it is totally up to you to trust the source, because they will have control to your entire page (they can even be sending cookies around).
From Douglas Crockford site about The Script Tag Hack (jsonp):
So the script can access and use
its cookies. It can access the
originating server using the user's
authorization. It can inspect the DOM
and the JavaScript global object, and
send any information it finds anywhere
in the world. The Script Tag Hack is
not secure and should be avoided.
Both IE 8 and Firefox 3.1 will have native JSON support, which will provide a safe alternative to eval(). I would expect other browsers to follow suit. I would also expect jQuery to change its implementation to use these native methods.
All browsers I know of disable cross-site requests through Ajax. That is, if your page sits on my.example.com, you can't load anything using Ajax unless its URL is also at my.example.com.
This actually can be something of a nuisance, and there are ways for an attacker to inject source in other ways, but ostensibly this restriction is in place to address exactly the concern you mention.
On a more abstract level then a previous question, in my experience there are 3 ways to call a javascript function on an html page from an embedded .swf using AS3: ExternalInterface, fscommand, and navigateToURL.
Let's compare and contrast these methods (and maybe others I haven't listed) and talk about the pros and cons of each - right now, ExternalInterface seems like the way to go in terms of flexibility, but is it right for all situations? Are there concrete benefits in terms of execution speed or anything like that? I'm curious - what do we think?
ExternalInferface was created to make communication between JS and Flash easier, so it doens't really make sense to use anything else. Common practice is to check if its available first by evaluating the value of the ExternalInterface.available property before making a call to some JS. This property tells you if the SWF in which you want to call some JS from is inside a container that offers an external interface. In otherwords, if using ExternalInterface will work. If its not available then just use flash.net.sendToUrl. Never use fscommand() as it uses VBScript and can cause conflicts with other VBScript on a page. Additionally, you can only send one argument string with fscommand and have to split it on the JS side.
It all depends on if you want the communication to be synchronous or not as ExternaInterface can return data as where navigatoToURL and fscommand are asynchronous and can only call a javascript function; they cannot return values or a response.
From live docs in relation to External Interface:
From ActionScript, you can do the following on the HTML page:
Call any JavaScript function.
Pass any number of arguments, with any names.
Pass various data types (Boolean, Number, String, and so on).
Receive a return value from the JavaScript function.
From JavaScript on the HTML page, you can:
Call an ActionScript function.
Pass arguments using standard function call notation.
Return a value to the JavaScript function.
The flash.external.ExternalInterface class is a direct replacement for the flash.system.fscommand class.
So using ExternalInterface is the preferred method or communication between flash and a Javascript function, though if the call is merely Asynchronous it is ok to use flash.net.navigateToURL.
ExternalInterface
You can get the return value from JS-AS and AS-JS calls
Encodes your arguments (call with arrays, objects, etc. No need to encode them)
Cross browser
Flawed when you send HTML or JSON (special encoding), it breaks internally
getURL
You can only call JS, you not get the return value and you need to encode your data
Was nice than deprecated and in Flash 10 it's removed
It is really removed, so don't use it ;)
fscommand
Come on, ExternalInterface is the solution (for 2008).