Javascript JQUERY AJAX: When Are These Implemented - javascript

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).

Related

How can I prevent someone from altering or avoiding my JavaScript logic when adding buttons to jQuery UI dialog?

I am using a jQuery UI dialog and I am adding buttons to the dialog in JavaScript based on some entitlements logic. (I pass in a boolean from my server-side AJAX call if I am entitled and then I show different buttons based on that flag.)
What concerned me is what is preventing someone from using developer tools like Firebug and putting a breakpoint on that line that does the check and either altering the flag or dragging to skip over that entitlements check.
So my question is specific to adding buttons onto a jQuery UI dialog (because its not like you can add the buttons from the server side since its a jQuery plugin), but I guess it highlights a more general point around any entitlements logic on the client side being "vulnerable". So if there are any general best practices around this point I would be interested (but still looking for an answer to my specific example).
NOTE: I am also doing a server-side entitlement check on POST as a backup, so I am still "protected" but I am still concerned about the point above.
Nothing prevents people from altering client-side code, it is inevitable.
You can, however, add buttons of the kind of "server-side", you just retrieve a string using the AJAX call, which happens to be a JavaScript function that adds buttons. And on the client side do eval() on that string which will execute the retrieved JS function and will add the buttons. Moreover, you can transmit your entire JavaScript code that way, so the client cannot skip anything since all is being executed in the eval().
A quick example:
Server-side function returns
string banana= "alert('test');";
return banana;
and client side does
eval(response.d);
Here is a theoretical example: FIDDLE
You cannot control what clients will do with your scripts, nor what requests they will make of your server. You must design your back-end API (not your JS client) to be the "gating mechanism" between the user and your system. It's best not to think of the JS as part of your system, but as a separate client that you ship as a reference implementation for your API.
But, if you wanted to at least make it difficult for users to mess with your code, you could minify and concatenate your JS scripts with something like Closure.
As the other person suggested, you cannot implement security on the client for exactly the reason you point out. You could use basic auth, or try setting up a token based approach.

javascript - how to execute a simple GET webrequest?

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)
});

Is Jquery *compiler* possible?

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?

jQuery - some beginner questions

I'm a very beginner to jQuery, and I'm having some basic questions:
Is it advisable to use jQuery whenever it is possible to replace something by using it? For example, is it prudent to bind all events to elements using it, instead of through HTML?
Is it better to host the jQuery .js file and all other relevant files (like JQuery UI) myself, or is it perhaps a better choice to use Google's link (they seem to host it for others too)?
When it comes to executing a script when the page is done loading, what way is preferred?
$(document).ready(function() {})
$(function() {})
$().ready(function() {})
They seem to all do the same thing, but what is the preferred way of scripting?
Yes. This way your JS is cleanly separated from your html. You can look at your file and in one glance, see how it is affecting your HTML. If it was embedded in the HTML, you would have to look for onClick, onLoad etc and it can get pretty messy for large applications.
Client browsers will cache files, so if you use the google version of JQuery, it will not have to download it off your server. Saving you bandwidth.
$(document).ready(function() {}) Is the preferred choice. $(function() {}) Just defines the block for execution, it will only execute after the page is ready if it is the last thing on the page to get executed.
1.) Yes and No. It is considered best practice to bind events unobtrusive regardless of using jQuery or not (this means, strictly separate javascript, html and any other language). Since jQuery allows to easily bind events it's a better way to use inline-handlers.
2.) You should use a CDN (like google) to deliver static files like jQuery for Caching purposes + they have a huge server network which may even be faster than your own host.
3.) I would stick to the first two calls. Anyway, basically they all will do it, but the best readability probably has $(document).ready(function() {});
1) Keep all your event binding in your script. This makes it easy to change later. You'll also appreciate having a single place to look for all event-related logic.
2) This has been answered very well already.
3) I prefer #2 for its brevity, but really the ideal way to do it is like this:
jQuery(function($) {
// Your code using failsafe $ alias here...
});
That avoid conflicts if you are using other frameworks that define $.
1: no this is completely up to you. generally jQuery incurs a performance penalty, because it is an extra layer of abstraction. Only use it, if you feel it helps you do your job easier. However, unless you truely need to optimize for performance the benefit in using it will far outway the cost. jQuery gives you tried and tested crossbrowser compatibility, which, if you wish to cater to all the different browsers out there, can be a costly affair to implement yourself.
2: Use Googles version: that way there is a chance that your users already have it cached and don't need to load it again from your site.
3: 2nd option, the shortcut is very widely used to a point where i'd say it's prefered even though 1st option is nice and specific. I'd never use 3rd option
For the 3d point, none of them. it is generally recommended, for performance reasons, to place your scripts just before the closing </body> tag. Thus you will not need to wait for the ready event: at this stage, the page is already loaded.
Check Jquery Cookbox (O'Reilly), Chapter 1.2: Executing jQuery/JavaScript Coded Ater DOM Has Loaded but Before Complete Page Load (that book is a must read all in all)
To have a quick idea about this technique, check Move jQuery to the end of body tag? (there are many other posts on SO about this subject)
I personally don't subscribe to the "cleanly separate JS from HTML" philosophy. I rarely see real world use cases where that has any benefit. Separating HTML from JS often leads to buttons that say "click here to do X" in the HTML but do nothing unless the appropriate javascript is with them. Kind of misses the point.
With the case of jQuery and events... I find it much easier to debug an app if I can inspect an HTML button in firebug and see what that button does (by looking at the onclick attribute).
Using the google version can aid with caching, but don't link directly to jquery.com. We did that here once and they went down, took us with them.

Alternative "architectural" approaches to javaScript client code?

How is your javaScript code organized? Does it follow patterns like MVC, or something else?
I've been working on a side project for some time now, and the further I get, the more my webpage has turned into a full-featured application. Right now, I'm sticking with jQuery, however, the logic on the page is growing to a point where some organization, or dare I say it, "architecture" is needed. My first approach is "MVC-ish":
The 'model' is a JSON tree that gets extended with helpers
The view is the DOM plus classes that tweak it
The controller is the object where I connect events handling and kick off view or model manipulation
I'm very interested, however, in how other people have built more substantial javaScript apps. I'm not interested in GWT, or other server-oriented approaches... just in the approach of "javaScript + <generic web service-y thingy here>"
Note: earlier I said javaScript "is not really OO, not really functional". This, I think, distracted everyone. Let's put it this way, because javaScript is unique in many ways, and I'm coming from a strongly-typed background, I don't want to force paradigms I know but were developed in very different languages.
..but Javascript has many facets that are OO.
Consider this:
var Vehicle = jQuery.Class.create({
init: function(name) { this.name = name; }
});
var Car = Vehicle.extend({
fillGas: function(){
this.gas = 100;
}
});
I've used this technique to create page-level javascript classes that have their own state, this helps keep it contained (and I often identify areas that I can reuse and put into other classes).
This is also especially useful when you have components/server controls that have their own script to execute, but when you might have multiple instances on the same page. This keeps the state separate.
JavaScriptMVC is a great choice for organizing and developing a large scale JS application.
The architecture design very well thought out. There are 4 things you will ever do with JavaScript:
Respond to an event
Request Data / Manipulate Services (Ajax)
Add domain specific information to the ajax response.
Update the DOM
JMVC splits these into the Model, View, Controller pattern.
First, and probably the most important advantage, is the Controller. Controllers use event delegation, so instead of attaching events, you simply create rules for your page. They also use the name of the Controller to limit the scope of what the controller works on. This makes your code deterministic, meaning if you see an event happen in a '#todos' element you know there has to be a todos controller.
$.Controller.extend('TodosController',{
'click' : function(el, ev){ ... },
'.delete mouseover': function(el, ev){ ...}
'.drag draginit' : function(el, ev, drag){ ...}
})
Next comes the model. JMVC provides a powerful Class and basic model that lets you quickly organize Ajax functionality (#2) and wrap the data with domain specific functionality (#3). When complete, you can use models from your controller like:
Todo.findAll({after: new Date()}, myCallbackFunction);
Finally, once your todos come back, you have to display them (#4). This is where you use JMVC's view.
'.show click' : function(el, ev){
Todo.findAll({after: new Date()}, this.callback('list'));
},
list : function(todos){
$('#todos').html( this.view(todos));
}
In 'views/todos/list.ejs'
<% for(var i =0; i < this.length; i++){ %>
<label><%= this[i].description %></label>
<%}%>
JMVC provides a lot more than architecture. It helps you in ever part of the development cycle with:
Code generators
Integrated Browser, Selenium, and Rhino Testing
Documentation
Script compression
Error reporting
MochiKit is great -- and was my first love, so-to-speak, as far as js libraries go. But I found that while MochiKit has very expressive syntax, it didn't feel nearly as comfortable to me as Prototype/Scriptaculous or jQuery did for me.
I think if you know or like python, then MochiKit is a good tool for you.
Thank you all kindly for your answers. After some time, I'd like to post what I've learned so far.
So far, I see a very large difference the approach using something like Ext, and others like JQuery UI, Scriptaculous, MochiKit, etc.
With Ext, the HTML is just a single placeholder - UI goes here. From then on, everything is described in JavaScript. DOM interaction is minimized under another (perhaps stronger) API layer.
With the other kits, I find myself starting by doing a bit of HTML design, and then extending the DOM directly with snazzy effects, or just replacing the form input here, an addition there.
The major differences start to happen as I need to deal with event handling, etc. As modules need to "talk" to each other, I find myself needing to step away from the DOM, abstracting it away in pieces.
I note that many of these libraries also include some interesting modularization techniques as well. A very clear description is contributed on the Ext website, which includes a fancy way to "protect" your code with modules.
A new player I haven completely evaluated is Sproutcore. It seems like Ext in approach, where the DOM is hidden, and you mostly want to deal with the project's API.
Tristan, you will find that when you try to architecture JavaScript as an MVC application it tends to come up short in one area -- the model. The most difficult area to deal with is the model because the data does not persist throughout the application, and by nature the models seem to change on the client-side pretty consistently. You could standardize how you pass and receive data from the server, but then at that point the model does not really belong to JavaScript -- it belongs to your server-side application.
I did see one attempt awhile back where someone created a framework for modeling data in JavaScript, much like the way SQLite belongs to the application. It was like Model.select( "Product" ) and Model.update( "Product", "Some data..." ). It was basically an object notation that held a bunch of data to manage the state of the current page. However, the minute you refresh, all that data is lost. I'm probably off on the syntax, but you get the point.
If you are using jQuery, then Ben's approach is really the best. Extend the jQuery object with your functions and properties, and then compartmentalize your "controllers". I usually do this by putting them into separate source files, and loading them on a section-by-section basis. For instance, if it were an e-commerce site, I might have a JS file full of controllers that handle functionality for the checkout process. This tends to keep things lightweight and easy to manage.
Just a quick clarification.
It is perfectly feasible to write GWT apps that are not server-oriented. I am assuming that from Server-Oriented you mean GWT RPC that needs java based back-end.
I have written GWT apps that are very "MVC-ish" on the client side alone.
The model was an object graph. Although you code in Java, at runtime the objects are in javascript with no need of any JVM in either client or server-side. GWT also supports JSON with complete parsing and manipulation support. You can connect to JSON webservices easily, see 2 for a JSON mashup example.
View was composed of standard GWT widgets (plus some of our own composite widgets)
Controller layer was neatly separated from View via Observer pattern.
If your "strongly-typed" background is with Java or similar language, I think you should seriously consider GWT for large projects. For small projects I usually prefer jQuery. Upcoming GWTQuery that works with GWT 1.5 may change that though not in near future because of abundance of plugins for jQuery.
Not 100% sure what you mean here, but I will say that after doing ASP.NET for the last 6 years, my web pages are now mostly driven by JavaScript once the basic page rendering is done by the server. I use JSON for everything (have been for about 3 years now) and use MochiKit for my client-side needs.
By the way, JavaScript is OO, but since it uses prototypical inheritance, people don't give it credit in that way. I would also argue that it is functional as well, it all depends on how you write it. If you are really interested in functional programming styles, check out MochiKit - you may like it; it leans quite a bit towards the functional programming side of JavaScript.

Categories

Resources