Lift session-valid ajax callback from a static javascript - javascript

I am currently implementing a graph visualisation tool using lift on the server side and d3 ( a javascript visualisation framework) for all the visualisation. The problem I have is that in the script I want to get session dependent data from the server.
So basically, my objective is to write lift-valid ajax callbacks in a static js script.
What I have tried so far
If you feel that the best solution is one that I already tried feel free to post a detailed answer telling me how to use it exactly and how it completely solves my problem.
Write the ajax callback in another script using lift and call it from the main script
This solution, which is similar to a hidden text input is probably the more likely to work. However it is not elegant and it would mean that I would have to load a lot of scripts on load, which is not really conveniant.
This seems to be one of the prefered solutions in the lift community as explained in this discussion on the mailing list.
REST interface
Usually what one would do to get data from a javascript function in lift is to create a REST interface. However this interface will not be linked to any session. This is the solution I got from my previous question: Get json data in d3 from lift snippet
Give function as argument of script
Another solution would be to give the ajaxcallback as an argument of the main script called to generate my graph. However I expect to have a lot of callbacks and I don't want to have to mess with the arguments of my script.
Write the whole script in lift and then serve it to the client
This solution can be elegant, however my script is very long and I would really prefer that it remainss static.
What I want
On client side
While reviewing the source code of my webpage I found that the callback for an ajaxSelect is:
<select onchange="liftAjax.lift_ajaxHandler('F966066257023LYKF4=' + encodeURIComponent(this.value), null, null, null)" name="F96606625703QXTSWU" id="node_delete" class="input">
Moreover, there is a variable containing the state of the page in the end of the webpage:
var lift_page = "F96606625700QRXLDO";
So, I am wondering if it is possible to simulate that my ajaxcall is valid using this liftAjax.lift_ajaxHandler function. However I don't know the exact synthax to use.
On server side
Since I "forged" a request on client side, I would now like to get the request on client side and to dispatch it to the correct function. This is where the LiftRules.dispatch object seems the best solution: when it is called, all the session management has been made (the request is authentified and linked to a session), however I don't know how to write the correct piece of code in the append function.
Remark
In lift all names of variables are changed to a random string in order to increase the security, I would like to have the same behavior in my application even if that will probably mean that I will have to "give" the javascript these values. However an array of 15 string values is still a better tradeoff than 15 functions as argument of a javascript function.
Edit
While following my research I found this page : Mapping server functions to client actions which somehow explains the goal of named functions even if it stil didn't lead me to a working solution.

Quick Answer
Rest in Lift does not have to be stateless. If you register your RestHelper with LiftRules.dispatch.append, then it will be handled statefully and Session information will be available through the S object as usual.
Long Answer
Since you seem interested, and it's come up on SO before, here's a more detailed explanation of how server-side functions are registered and called in Lift. If you haven't worked with Lift for some time, look away. What follows should not in any way be used to evaluate Lift or its complexity. This is purely library developer level stuff and a majority of Lift users go about their development blissfully unaware of it.
How it works
When you create stateful callbacks, typically by using the methods within the SHtml object, what you are really doing is registering objects of type S.AFuncHolder within the context of the users session, each with a unique ID. The unique ID that was generated during this process is what you're seeing when you come across a pattern like F96606625700QRXLDO. When data is submitted, via form post, ajax, or whatever, Lift will check the request for these function ids and execute the associated function if they exist. There are several helpers that provide more specific types of AFuncHolder, like S.SFuncHolder (accepts a single string query parameter) and S.BinFuncHolder (parameter is multipart form data) but they all return Any and behind the scenes Lift will collect those return values to create the proper type of response. A JsCmd, for instance, will result in a JavaScriptResponse that executes the command. You can also return a LiftResponse directly.
How to use it
AFuncHolders are registered using the S.fmapFunc method. You'd call it like this
S.fmapFunc(SFuncHolder({ (str: String) =>
doSomethingAwesomeWithAString(str)
}))(id => <input type="text" name={id} value=""/>)
The first parameter is your function, wrapped in the proper *FuncHolder type and the second parameter is a function that takes the generated id and outputs something. The something that gets output is what you will include on the page. It should somehow result in the id being sent to the server as a query parameter so that your function is executed.
Putting it all together
You could use the above to make your own Ajax calls, but when Lift makes an ajax call there are a few other considerations:
1) Most browsers only allow so many simultaneous connections to a given domain. Three seems to be the magic number.
2) AFuncHolders will often close over the scope of the snippet they are contained within and if multiple ajax requests are handled at once, each in its own thread, bad things can happen.
To combat these issues, the liftAjax.lift_ajaxHandler function queues each ajax request, ensuring that only one at a time is sent to the server.
The drawback to this approach is that it can make it difficult to make an Ajax call where the result needs to be passed to a callback. JQuery autocomplete, for instance, provides a callback function when input changes that accepts a list of matches. If you are manually calling LiftAjax.lift_ajaxHandler though, you can provide your own callback functions for success & error and I would recommend that you look at the source of those functions in your browser for more information on how they work.
There's actually more to it, like how Lift restores RequestVars on ajax callbacks (which is where the lift_page comes in, but that's about all I'm prepared to explain over coffee on a Saturday morning :)
Good luck with your app!

Related

REST API Ajax simultaneously requests

Is it wrong to make multiple ajax simultaneously requests to different endpoints of a REST API that end up modifying the same resource?
Note: each endpoint will modify different properties.
For example, let's assume that one endpoint modifies some properties for an order, like order_date and amount and another endpoint set's the link between the same order and a customer by changing the customer_id value from the orders table (I know that maybe this is not the best example, all these updates can be done with one endpoint).
Thanks in advance!
This is totally a requirements based question. It is generally a bad idea to have a single resource be changed by multiple processes, but this ONLY matters if there is a consistency relationship between the data. Consider some of the following questions:
If one or more of the AJAX calls fails does will that break your application? If it will, then yes, this is a bad idea. Will your application carry on regardless of what data you have at any given time? If so, then no this doesn't matter.
Take some time to figure out what dependencies you have between your data calls and you will get your answer.
what you are describing is not a shared resource even if it is stored in the same object because you are modifying different properties however take great care when using same object. if your requests to the server depends on the properties that are modified by the other request.
in general its not a good idea to use the same object to store data that is modified by more than one asynchronous function even if the properties are different. it makes your code confusing and harder to maintain since you have to manually coordinate your function calls to prevent race condition.
there are better ways to manage your asynchronous code using Promises or Observables
It's a bad idea in general. But if your code is small and you can manage it then you can do it though its not recommended.
In the long run, it will cause you many problems confusion, maintaining code, consistency etc.
And if in any case another developer has to manage your code, It will be more confusing and tough for him.
In programming always keep things flexible and think in long run. Your requirements can change in future , what will you do then? write the whole program again? This is one thing , you also want to avoid.

When making multiple ajax requests, is there a "good pattern" for tracking which data the responses line up with?

I build a lot of client-side js apps and have worked mostly with Backbone. Backbone always expects your api to return a copy of the created/changed/deleted model when such ajax actions are completed, allowing it to easily determine which "model" just got updated.
I'm working in a new scenario (new framework, freshly built API) in which all I get back from the API are success/error status codes. The whole "return the entire model" seems like a crutch...but the more I work trying to keep track of these async actions the more it feels like a necessary one.
Is there some kind of convention (outside of the Backbone world, perhaps) for more easily handling this kind of thing?
Edit: I may want to point out I'm using FLUX so the uni-directional flow is preventing me from just cross-wiring everything on either side of the dispatcher.
Your question title is more clear to me than the description, so I'll go with that.
If you are having difficulties in keeping track of multiple ajax requests results, you should use Promises.
For example, with the Q library you can do something like this:
Q.all([AjaxModel1(), AjaxModel2(), AjaxModel3()])
.spread(function(resultModel1, resultModel2, resultModel3) {
});
If what you need to know is how to get a model every time you make a change to them, I would need more details about your framework/server/code.

JavaScript Request/Operation Framework or Toolkit?

I'm building a complex application in JavaScript which needs to make several requests to the server. Sometimes that request cannot be completed as sent, and addition information is needed. I would like the ability to have the server inform the application in the request's response that more information is needed and to describe how to retrieve that information.
For example, say a user tries to perform an operation that his current permissions level does not allow. The server needs to ask the application for an override authorization code, basically meaning the application needs to pop up with a dialog asking for an admin passcode.
I'd like to have some kind of framework that abstracts all this. Possible a main "Request" or "Operation" class, which I can define sub-Request classes that define possible interpretations of requests. I'm not sure if something like this exists already or not.
So I guess my questions are: 1) Does a framework like this exists? and 2) Are there any articles on this topic (platform and language agnostic, I can learn how they work from any source). I know frameworks like Dojo and ExtJS use something like it for their data stores, but I'm not sure if it's exactly what i'm needing, or how it even works for that matter.
Any help leading me in the right direction is appreciated, Thank You.
EDIT:
A point should be made I am looking for something that is abstract from the technology used to actually send that data to the server. That way I could utilize the same framework on different ajax technologies.
Basically I'm looking for a framework or article that can help me figure out how to create a custom "Application Protocol". An example of this would be:
{
type: 512,
success: true,
data: { some: "data" }
}
I know I have to design the protocol itself, but what I need help with is creating a "class" or something that interprets this protocol automatically instead of just making redundant onSuccess callbacks
I have worked on an open source project named Pomegranate Framework which does what you want (to some extent). Perhaps you can extend it in order to meet your needs. It comes with an application layer close to want you asked for but you need to implement your protocol as it fits. Here's its address:
Pomegranate Framework
I haven't found the time to document it yet but it comes with a bunch of examples that may be useful to you. You may also want to take a look at its example page:
Pomegranate Framework Examples
I think you would like to see the 021 example titled "Handling server errors in client". I hope it's what you are looking for.
Use Dojo and jQuery's Deferred object for callbacks. It is an implementation of the Promise design pattern. Every action has a success callback chain and a failure callback chain and both chains can diverge or merge at various points along the chains and chains can branch off to create sub-deferreds.
If you know the state of your application on the client (and there are only a few error causes and you do not need detailed information from the server), you can and should use HTTP status codes. As far as I know 200 is the only one with a body, so you can't (or shouldn't, there's always adding headers, but I'd stay clear of that path) transmit anything else - but every framework should provide you with the means to pass an error handler on sending a request. In the callback function you pass as an error handler, you just have to do whatever the respective status calls for.
It's supported by the protocol, independent of whether you pass HTML, JSON or anything else and error callbacks based on the status code are supported by every library worth using.
Since you're basically talking about "server-sided push events", you need some technique that allows your server script to send data to your clients.
There are some well knowns methods like COMET, Flash Sockets and the latest guy in town WebSockets around.
Since WebSockets is probably the most sophisticated stuff from all of these, you should aim for that. Unfortunately, its browser support is limited to the "latest version" for most browsers, if you're good with that, just use them right away. If you want some fallbacks for older browsers, the most used framework for that should be socket.IO.
But even socketIO only abstracts all the different communication techniques away for you. Anyway, it should be fairly easy to build a solid management framework around that by yourself. So my answer on that part is, I'm not aware of any library or framework which deals with that kind of stuff.
There are various ways to achieve this using ExtJs.
The most bare-bone one is to use Ext.Ajax.request() providing url, params, method. Then in your success handler, check for the server response and if it requires an additional data from the user - display an extra credentials dialog, and send another request with the extra credentials details that will unlock the server side script.
Notice that the success hander of the request method gives you back the config object of the request in its options parameter, so you can quite easily call the same request again, only adding the extra credentials this time around.
Here's a jsfiddle code demonstrating this concept (I've shown both using success and a global handler for all calls - I hope you'll be able to work out how to take it from here). And a similar one, which I believe is more what you're after exactly.
I'll be happy to help further, just ask the questions.
If abstraction and testability is what you want, I highly recommend AngularJS. angular $q which is an implementation of Kris Kowal's Q. You can create services that will hide away how you call the server and will allow you to change server implentations in future will little grief.
It will look like problem of server push i.e. wherever change occured data will be pushed to client There are following options
reverse AJAX by DWR Framework.
Ajax Push Engine http://www.ape-project.org/
Commercial
WebSync
You can use long polling mechanism like this
(
function poll(){
$.ajax({ url: "server", success: function(data){
myobject.setValue(data.value);
}, dataType: "json", complete: poll, timeout: 30000 });
})();
You will get more info at ajax push server

Should ajax calls go through as few as possible entry points to an application or many specific methods

I'm building a web app with a lot of ajax calls to be made.
Should I be trying to keep a small number of methods, and just pass in information about what type of request it is, and then switch based on that type inside the method
or
Many smaller methods, so don't have to pass in type, but more code to write setting up each method.
Currently I'm passing type from the id of the element being interacted with in the html, and then this tells me what I'm trying to do
row-action-data-id (I then split this in the functions, to work out what needs doing)
Are there any best practices for patterns like this?
its a judgement call. you always want to refactor out any duplicate code as much as possible but its important that your code is readable and maintainable.

Connecting a form to a Javascript Object (and other best practice advice)

I've been using javascript to do lightweight functionality on sites for years - DOM manipulation etc - but just now im beginning to investigate using it to do a lot more of the heavy lifting (in combo with PHP). I've only just started getting into OO JS, and im still trying to get my head around the best-practices and design patterns that work well with it.
To be more specific - my question is, can anyone here suggest techniques for connecting a form to a javascript object?
In my current implementation I have an JS object that can be edited by a (fairly large) form. When I instantiate the object I attach an onchange observer to the form, whose callback syncs the form fields with the object parameters. I'm handling the form submitting through AJAX - there is also a periodic request that saves a temporary version of the form info to a mySQL DB. One thing I wonder is whether it is possible to easily handle syncing in the other direction - onchange of the object the form fields update (on form reset for instance).
I am interested to know if this approach is a correct/sensible one, and more generally I would be very interested to hear advice with regard to OOJS form handling.
Cheers in advance :)
(Im using Prototype btw)
You can use $("form").serialize(true);
http://www.prototypejs.org/api/form/serialize
You dont need the onchange event, you can just call the serialize() method every time you need to get the form data.
Why not create a method in you object that resyncs the object with the form? And call that on every change of the object? You could create a special change function to assure that it gets called on every change.
It's a perfectly reasonable approach. JS doesn't entirely encourage this sort of thing due to its curious object system and in particular the way bound methods are not first-class objects, but with a bit of suitable metaclass and callback glue it's eminently possible.
You might also want to look at a widget library if you'd like to get more of this kind of low-level form handling stuff for free. Haven't tried the ones built on top of Prototype; other possibilities include YUI's one.
Updating the model from the server can be pretty simple. Generally you'd poll an AJAX request and have the server pass back either diffs, if it knows them, or else just timestamp each object update, send the new object details to the client side on each update, and have the client decide how to merge that with any changes the user has made in the meantime.

Categories

Resources