How can I make an ajax call in a web worker? - javascript

I need to make ajax calls to a REST/JSON server from javascript. Both to pull down data to the browser and to push data up. In a web worker.
Because this is in a web worker JQuery cannot be used (details here). And JQuery-hive is a library for managing web workers, not for using JQuery in a web worker (as far as I can tell from the documentation). So JQuery is not an option.
In the limited environment of a web worker, how can I make ajax calls?

Here's something to consider: jQuery is a abstraction tool: it can't do anything which isn't possible with basic JS. it might be easier with pure JS, it might be harder. But it's not magical. It just provides an abstract interface which unifies the different implementations of javascript engines in different browsers.
In this case, jQuery is an abstraction for an XMLHttpRequest. You can find a guide on how to use this on every major javascript website: w3schools.com, MDN, MSDN,... There are also many questions on stack overflow that explain how to do this.
Slightly off-topic, but this is also one of the reasons that I recommend people learning or developing javascript to first learn how to do the things manually, and only switching to a library once they've learned the basics. A library is great for abstraction, but if you haven't learned WHAT is abstracted, you get into trouble once you end up in a situation where you don't have access to the abstraction.

Related

Is there a high-level inter-process communications API that is implemented in both C++ and Javascript

I am working on app where I need to pass messages between a C++ application and a Javascript web app.
Certainly I could write sockets code myself in either language and I have done this in the past when necessary.
What I would really like is a higher-level message posting or message queueing API that does a lot of the work for me. Does anyone know of such an API?
I have looked at ICE, and it doesn't appear to have Javascript bindings. I have also looked at Boost message queue, but it only caters for the C++ side of things. If necessary I might roll my own Javascript bindings for either of these technologies.
UPDATE: Sorry should have mentioned this before, I want to run this in a browser.
To give a more complete story what I want is a simple browser-based app that is used to configure and display logging for a C++ application.
I know there are other ways of doing this, but I am specifically interested in a high-level library in both C++ and browser-based Javascript that builds a message queue ontop of the sockets API (if there isn't one then I might consider implementing it myself and writing up a code project article).
ALSO: I'm not bothered about portability in terms of the web browser. Eg if there is a high-level IPC Javascript library that only works in Chrome, I'll be happy with that.
With JavaScript I assume that you are running it in a browser? In this case your C++ application needs to provide a webserver and some kind of JSON based webservice that you can call. On the JavaScript side you just use AJAX to communicate with that webservice.
An alternative would be websockets which might be a little harder to implement on the C++ side though.
To simply answer your question: No, there is no IPC implemented in ECMAscript out of the box.
But you actually answered you question already. If you try to communicate with Javascript that runs in a browser, you indeed should use (web-)sockets connections to pipe date in either direction. Of course you could write a simple HTTP server in C++, but I guess that is overkill and does not have the capabilitys of bi-directional sockets.
It's still some work to implement a web-socket connection in C++ from the scratch (the specs were in flux for a long time), but I guess there are some librarys out already.
If you're trying to communicate with node.js, this is an almost trivial task using real sockets/pipes.
I have found a solution that meets my needs. It isn't exactly perfect but I think it works well enough.
Some people suggested using HTTP and ajax. That turned out to be a useful idea and after some prototyping I think it solves my rather basic needs.
To be more specific I am using the Mongoose HTTP server embedded in my C++ application and I am using the jQuery ajax function to pull data from the server. The jQuery client polls the server continously for new data, not particularly efficient but I think it will do the job good enough for me.
Once my implementation is complete I'll write an article explaining how to do this in detail and then I'll update this answer.
You could try DBus, it has very simple mechanism to define, query and use interfaces, and there are some components for XPCOM and webkit based browsers (for example http://sandbox.movial.com/wiki/index.php/Browser_DBus_Bridge and http://code.google.com/p/v8-dbus/). Also DBus is opensource and cross platform.
For a server side or non-browser implementation how about named pipes?
Yes it's vintage technology and the usage depends which OS you use, but as long as your server side js environment has ability to read and write files it may work, and it fits the description 'high-level' inter-process communication.

Do I need to learn Javascript before AJAX or does AJAX not require Javascript knowledge?

I was wondering if it is worth learning javascript first? Does AJAX require Javascript in anyway or is it just similarities in the markup language?
You should absolutely learn javascript. And because AJAX is achieved with javascript, by learning javascript you will also learn AJAX. AJAX is not a different language. It's a pattern that you could use to develop asynchronous web applications using javascript.
Also note that javascript is not a markup language.
First, learn the basics of JavaScript. It's a programming language, not a markup language. You don't need to become an expert immediately, but learn the basics — what it is, the basic structures (functions, control flow statements, variables, objects, etc.), that sort of thing.
Ajax is a technique for retrieving data in a web page without refreshing the full content of the page (or indeed, any of it if you don't want to). You perform Ajax operations (sending a request, interpreting the response) using JavaScript and some other things, such as the XMLHttpRequest object. Ajax isn't a part of JavaScript. They're just used together in the web environment.
(Side note: Although Ajax stands for "Asynchronous JavaScript and XML", the XML part of that is optional; you can do "Ajax" without using XML and in fact, many if not most people do. Ajax lets you send and retrieve all kinds of data, including XML but also including HTML, JSON, plain text, and lots of other stuff.)
Some references that may be useful:
JavaScript:
The Mozilla JavaScript pages
JavaScript: The Definitive Guide by David Flanagan (yes, an old-fashioned paper book)
Crockford's articles on JavaScript (a bit advanced, wait 'till you're ready). Crockford is smart and knowledgeable, but not everyone agrees with all of his conclusions. (I don't.) But it's good to read and understand his points, and make your own decisions. He's mostly right, most of the time.
My own anemic little blog (start with the oldest entries and work forward)
The ECMAScript specification (PDF | handy HTML version)
The DOM
DOM2 Core
DOM2 HTML
DOM3 Core
HTML5 Web Application APIs
(Speaking of which) The HTML5 specification. Parts of it are just codifying what web browsers actually do right now; other parts of it specify new stuff. Mostly you can tell which is which by checking whether the thing in question is part of HTML4. If it is, then likely the HTML5 spec tells you what browsers mostly do today. If it isn't, then it's new and browser support may be perfect, or may be non-existant. :-)
The API docs for the library you choose. There are several good ones: jQuery, Prototype, YUI, Closure, or any of several others. (jQuery is the most widely-used at present.)
Late answer, but here's an analogy if it helps...
Learning JavaScript is like learning to ride a motorcycle.
Learning AJAX is like learning a technique or trick you can do on that motorcycle, like pop a wheelie (though AJAX is more practical than that).
Learning jQuery is like getting some gear to (perhaps) make your motorcycle ride safer or more enjoyable, like a helmet and leather chaps and jacket, or a more comfortable seat and better shocks, or maybe some saddlebags.
So the base of everything is JavaScript. AJAX is just a term to describe something you do in JavaScript, and jQuery is a code library that you may enjoy using when developing in JavaScript, but isn't at all required.
To be more specific, AJAX is a technology that uses javascript for 'part of the work' (it stands for Asyncronous JavaScript and XML), and handling it properly requires knowing at least something about javascript. Also, using a javascript library such as jQuery or Prototype make it much easier to work with AJAX.
JavaScript is a language, AJAX is a technology performed using JavaScript (and usually a web server).
AJAX is 98% Javascript and 2% other. Even the JSON(Javascript Object Notation) you would use for the response data type format, if you choose to, is Javascript. I think this answers your question.

What are some architectural reasons to use node.js aside from scalability?

The most common theme I read about why to use node.js is for high scalability due to it's evented, non-blocking I/O model. I'm trying to understand other non-scalability uses cases (and aside from being used as a general server-side javascript engine).
Does node.js have other use cases if scalability isn't a concern of mine?
If yes to #1, what are they?
Is node.js usage appropriate for any particular type of application architectures? E.g. similar to how some key/value (nosql - ugh I hate that term) databases are useful other than for scalability reasons.
My reason for trying out node is the fact that it is incredibly easy to send JSON data between the server and the client for ajax requests.
If you use something like MongoDB, which stores data as JSON object too, you never have to worry about translating or parsing your data.
If your site uses a lot of ajax, and you're sending your data as JSON objects (rather than XML or plain text) then node.js will save you a fair bit of effort.
I think this blog posts sums it up quite well:
http://debuggable.com/posts/understanding-node-js:4bd98440-45e4-4a9a-8ef7-0f7ecbdd56cb
In short (pro node.js):
Speed
Javascript (especially if you know it already)
Efficiency
node.js is really great. Give it a try! :)
I can think of one reason, but its not very deep. Basically, If you are developing an RIA, your entire stack can be javascript. That might have some value.
But Ill question my own answer, namely the thought is, even if it makes the server side code more accessible to client side developers, they still need to understand how their server stack works. So there is still some learning to.
To be accurate, I think the general server-side JavaScript engine in your question would be V8, while according to its creator Node was built for "scripting network programs."
Based on many of his comments I don't believe he views it as broadly as many of us do, but recognizes where it can go. [I can't speak for anyone else--that's just my interpretation based on the writings and presentations I've seen.]
So it approaches things from a somewhat lower level, makes HTTP a first-class citizen and just happens to be really cool, which I think makes it enough of a "use case" for most of us. ;)
It does have a learning curve and isn't the most stable platform to build on due to its rapid development. I believe time will tell where it's most useful.
For now people are using it for "real-time" apps due to its lightweight, asynchronous nature, as well as general Web development, though IMO its sweet spot remains with its originally stated purpose.
What I like about node.js aside from non-blocking I/O model, scalability and all that "primary reasons" stuff:
Lightweight nature of it's framework. Basics are easy to learn.
Developer community building tons of useful modules and libraries on github which are expanding node.js lightweight core and it's capabilities.
It's really easy and fast to build server side and real-time systems (for example http or socket based) without the knowledge of complex libraries.
I like to use NodeJS to write testing harness because you can write a stub/server/client really quickly. And you can drive your application, with ease. I can easily script a third party back-end server to do performance testing on my application. I also use it to drive my application. I can perform complex client server scenarios using setTimout to cause multiple events to be trigger based on any logic I want and test them at scale.

Ajax - Library or Plain Javascript

I've been doing a lot of reading about AJAX, and wanted to know which is the better way to approach things: by using a library such as jQuery using their built-in methods or creating JavaScript without a library for AJAX?
Ajax has a lot of quirks when working with the XMLHttpRequest Object. When you start to work with it, you will not see it, but when it is out in a production environment, it will bite you in the butt. Browsers, browser version, user settings, the type of server, type of request, and much more can affect what needs to be coded. Libraries tend to solve most of the problems, but they all are not perfect.
I always tell people it is great to work with a tutorial to see how the XMLHttpRequest works. After you have learned how to do it naked, work with a library that fits your needs.
Eric Pascarello
Why create a library when plenty already exists? If you create a library it is going to take time and effort and you'll end up going through the same hurdles others already have. And unless your company is trying to sell an Ajax library then stay away from writting your own plumbing code.
I am currently using both JQuery and Microsoft's Ajax in my site and have found that they are both feature complete with plenty of options of different ways you can set up the communication.
If you ask this question on comp.lang.javascript you'll get lots of different answers, many of which disdain the commonly-used libraries (one quote sometimes taken slightly out of context is Richard Cornford's post on c.l.js in 2007: "Prototype.js was written by people who don't know javascript for people
who don't know javascript. People who don't know javascript are not the
best source of advice on designing systems that use javascript.")
The argument for libraries is they abstract away most of the differences between browsers and allow for cross-browser scripting. The argument against libraries is that they are bloated code with quirks of their own, so you'd have to learn just as much to use them well as you would to use cross-browser techniques in raw javascript. If you are writing lots of Javascript that you're going to reuse in multiple places, and you're trying to make websites that load quickly and use a minimum of excess bandwidth (e.g. if you have pay-per-use webhosting like via Amazon S3 or nearlyfreespeech.net), then it's probably worth stripping whatever you're going to use out of a good library, tweaking it, and using that.
I was all psyched about Prototype for a while, but then decided I just need a few simple building blocks. I tend to use Doug Crockford's simple JSON library, and then some of Fork Javascript's minimalist libraries as needed (primarily FORK.Ajax), and do the rest myself from scratch or reusing routines from an earlier project that I've honed to something that works well for me.
why wouldn't you use library if it meets your needs. you're using .net framework, or java JRE, or php built-in functions...
you can create your own javascript for the purpose of learning, or to do something libraries don't offer. but for regular development, you are much quicker with library and you get cross-browser compatible JS without having to code cross-browser support manually, it's already built-in into the library

Should I use Google Web Toolkit for my new webapp?

I would like to create a database backed interactive AJAX webapp which has a custom (specific kind of events, editing) calendaring system. This would involve quite a lot of JavaScript and AJAX, and I thought about Google Web Toolkit for the interface and Ruby on Rails for server side.
Is Google Web Toolkit reliable and good? What hidden risks might be if I choose Google Web Toolkit? Can one easily combine it with Ruby on Rails on server side? Or should I try to use directly a JavaScript library like jQuery?
I have no experience in web development except some HTML, but I am an experienced programmer (c++, java, c#), and I would like to use only free tools for this project.
RoR is actually one of the things the GWT is made to work well with, as long as you're using REST properly. It's in the Google Web Toolkit Applications book, and you can see a demo from the book using this kind of idea here. That's not to say that you won't have any problems, but I think the support is definitely out there for it.
There's a neat project for making RoR/GWT easy that you can find here (MIT license). I haven't had a chance to try it out yet, but it looks like a good amount of thought has been put into it. One catch is that it looks like it hasn't been fully tested with 2.1 Rails yet, just 2.0, so you may run into a few (probably minor and fixable) errors.
If you are looking to integrate GWT with non-Java backends such as ROR, PHP etc., you should bear in mind that GWT 1.5 now supports JavaScript Overlay types. This feature lets you write classes that can be mapped over the top of native JavaScript objects to easily provide accessor methods for properties of those objects and other extended functionality.
See this link for more details:
JavaScript Overlay Types
So you could return JSON encoded data from your backend via AJAX calls, parse it into a JavaScript Object and then access the data through your GWT Java code using the overlay classes you've created. Or when you render your page you can render static config data as JavaScript Objects and read it in via this mechanism, rather than having to do an AJAX call to grab the data.
If you know JAVA, and have somewhere you can host it (like a tomcat or glassfish container) I would recommend that much more than using Ruby for the back end. The main reason is that then you can share all of your objects, and use the built in RPC mechanism. I've done this for quite a lot of our projects and it's a huge timesaver, not to mention that the code is less error prone, because you don't convert your java objects to anything and then back again.
I have linked my GWT with Rails before, using the to_json function in Rails and then reading the JSON in GWT. It's all supported, but it is far more annoying than just doing the back end in JAVA.
Of course if you have cheap hosting, then Java containers are pretty much out of the question, in which case I would think Rails would be the next best thing.
GWT is very high quality with a great community. However you do need to know CSS if you want to adjust the look of things (you will) - CSS can do a lot of the layout, just like regular web if you want it to. Libraries like GWT-ext or ExtGWT can help a bit as they have stunning "out of the box" looks but for a price (extra size to your app).
You can code everything in Java using GWT, and you can integrate existing 3rd party javascript libraries with it. It's very good. I've never used RoR much though, so can't say anything about that.
If you're experienced in Java but not in Javascript/CSS, then GWT is going to be a lifesaver (unless you want to learn them, of course). CSS has so many little fiddly details. It is not uncommon to spend half a day fixing a 2 pixel misalignment that only occurs in IE6.
I am not sure about how easy it would be to use ROR for the back end... It is possible, I am sure, since GWT ajax communication is just servlets. But they provide some really nice functionality for passing Java objects back and forth which you won't be able to utilize if your server isn't also using Java.
I wrote about some of the disadvantages of GWT recently. Mainly, the disadvantages are: long deployment cycle for changes to some parts of the application and a rather steep learning curve. As a seasoned Java programmer, the second should be less of a problem and if you use a seperate backend, the first is also mitigated (as a complete redeploy is primarily required when you change the 'server' part of the application).
GWT is a wonderful framework with lots of potential. Keep in mind that it's still quite new, though. There are some unresolved bugs that can really annoy you, and they usually require ugly workarounds to get past. The community is great but you'll probably end up with a few problems sooner or later that Google can't answer yet.
But hey, I say go for it. The potential for GWT is awesome, and I bet it's future will be bright.
You should definitely use GWT for a new project (it's pretty easy to use in an old project too).
I my experience it's very fast to learn and use. The compiled javascript code is much better than anything you could ever write by hand and it works fast too.
Another benefit is the ability to debug you're code (which is hell with javascript alone)
This blog has inputs from many experienced users of GWT and have some great discussion points. I personally have huge experience with varied UI Frameworks. I will add my two cents. Lets look at fundamental advantages and disadvantages of GWT
Fundamental Advantage
GWT takes the web layer programming to JAVA. So, the obvious advantages of Java start getting into play. It will provide Object Oriented programming. It will also provide great debugging and compile time checks. Since it generates HTML and Javascript, it will also have ability to hide some complexity within its generator.
Fundamental Disadvantage
The disadvantage starts from the same statement. GWT takes the web layer programming to JAVA. If you know JAVA, probably you will never look out for an alternative language to write your business logic. It's self sufficient and great. But when it comes to writing configurations for a JAVA application. We use property files, database, XML etc. We never store configurations in a JAVA class file. Think hard, why is that?
This is because configuration is a static data. It often require hierarchy. It is supposed to be readable. It never requires compilation. It doesn't require knowledge of JAVA programming language. In short, it is a different ball game. Now the question is, how it relates to our discussion?
Now, lets think about a web page. Do you think when we write a web page we write a business logic? Absolutely not. Web page is just a configuration. It is a configuration of hierarchical containers and fields. We need to write business logic for the data that will be captured from and displayed on the web page and not to create the web page itself.
Previous paragraph makes a very very strong statement. This will explain why HTML and XML based web pages are still the most popular ones. XML is the best in business to write configurations. A framework must allow a clear separation of web page from business logic (the goal of MVC framework). By doing this a web designer will be able to apply his skills of visualization and artistry to create brilliant looking web pages just by configuring XMLs and without being bothered about the intricacies of a programming language. Developers will be able to use their best in business JAVA for writing business logic.
Finally, lets talk about the repercussions in direct terms. GWT breaks this principal so it is bound to fail. The cost for developing GWT application will be very high because you will need multiskill programmers to write web pages. The required look and feel will be very hard to achieve. The turn around time of modifying the web page will be very high because of unnecessary compilation. And lastly, since you are writing web pages in JAVA it is very easy to corrupt it with business logic. Unknowingly you will introduce complexities that must be avoided.
You could also consider Grails ("Groovy on Rails") which gives you the benefits of a Rails framework and the use of the Java VM.
Our team recently asked the same question, and we chose to go with GWT, especially since the designer plugin made working with GWT more accessible to non-java experts on the team. Whoever makes this choice, just beware you DON'T use the GWT Designer plugin !! It has not been updated (in at least a year, apparently) to create a GWT application that is compatible with IE8.
Our team had almost completed our application layouts, which were working perfectly in Chrome, FF and Safari. Then they blew up in IE. IE 7 would load partial pages (but not composite includes), and IE8 was not even able to load up the application. It just hung.
The designer plugin has buttons that allow the user to add CellTable widgets that are not IE compatible (CellTable, DeckPanel, Horizontal Panel, Vertical Panel, among others). These will cause intense pain when the layouts have to be re-done in java without assistance from the designer.
Experienced GWT users love it, but the designer plugin will kill you.

Categories