HTTP Request Methods and AJAX. What is going on? - javascript

So I'm working on a function that makes it easier to send XMLHttpRequest's.^
It's set up like this..
XHR(url, method, data);
..where data is an object that get's turned into a query string like..
XHR('Hey.xml', 'get', { hi: 'hey' });
..would request "Hey.xml?hi=hey".
The thing is, different request methods want the query to be sent in different ways.
GET and HEAD expect the query to be part of the url.
POST expects the query to be sent with..
request.send(query);
I know there are other methods, and I was wondering which way the other methods use, or if other methods use yet another way.
^ Yes I know 50 of these already exist. Yes I know jQuery is one of them. Don't even think about suggesting it.

Reading on AJAXPatterns.org, there isn't any differences when using the "other" request methods with XHR.
Take a look at http://ajaxpatterns.org/XMLHttpRequest_Call#Handling_POSTs_and_Other_Request_Types

No, there are more. You got at least PUT and DELETE, although they are used much less frequent than GET and POST (as in: hardly ever). I believe GET is the only one that works cross domain. The others only work in your own domain, so it is your own decision whether to use POST, PUT or DELETE.

Related

Wait for AJAX to return success before continuing Javascript code?

A similar question has been asked many other times, I'm aware, but my case is rather specific and has, to my knowledge, never been touched on before. At least from what I can find.
What I'm doing is building objects using a UID. Everything that the object is built with requires this UID and it requires it to be verified as unique before anything can be done with it.
I'm randomly generating the UID in javascript and I'm checking it against all other entries in a SQL database. I'm posting to the database using PHP and Ajax.
The core issue I'm having is that Javascript doesn't wait for the Ajax response and instead just keeps rolling. Ajax has to use a success handler. This is strictly not possible for me to use because I cannot do anything until I know for certain that the UID is verified.
Are there any workarounds or solutions to this? Promises won't work because, as I stated before, the UID is integral in building the object in and of itself, so using placeholders won't work.
Thanks in advance!
You can just send a synchronous Ajax request, like that:
var response = $.ajax({ url : "http://api.jquery.com/jquery.ajax/", async : false });
(though that is not a very good practice)
Ok. One possible solution, if your UID is generated on the server randomly, you may supply it directly to your index.html with the script tag.
<head>
<script src="path_to_url_that_provides_generated_script"></script>
<script .... other scripts></script>
</head>
And this generated script would be something like:
var UID = "xxxx-xxxx-xxxx-xxxx";
That way you don't even need to do an ajax request, since your uid will known before any other script is processed.
The best method, I have discovered, was to rewrite my code to not begin object creation until I had the UID in the first place. While this does take up a considerable amount of time to complete and ensure that no unwieldy bugs are present, there's no other real solution that's both simple and effective.
As it turns out, foresight is something that always seems to keep good programmers from writing and rewriting their work again.
Special thanks to #Vladimir M for the solution.

Ember-Data: Intended usage pattern of DS.EmbeddedRecordsMixin

I've got a backend, that let's me read data asynchronously, but enforces embedding of certain child data (in lieu of transactions).
When using DS.EmbeddedRecordsMixin with ...
{
serialize: 'records',
deserialize: 'ids'
}
... (which should be the right thing to do given this backend) I've still got two questions.
(1) http://emberjs.com/api/data/classes/DS.EmbeddedRecordsMixin.html is very explicit, that DS.EmbeddedRecordsMixin shouldn't be mixed with async:true. From what I understand, the problem would be mixing async:true with embedded reading, not writing. On the other hand the documentation doesn't differentiate. Am I good with mixing async:true with above configuration (and is the documantion missing this case), or what is it that I am missing about async:true and writing?
(2) In my backend when deleting the parent, all children are delete as well. Deleting should be just one call for the parent. How do I do this on the ember end? I want to delete the parent and all children in the store, send one REST request and the success/failure of this request should be authoritative for all those records. Yet, the DS.EmbeddedRecordsMixin doesn't seem to help me in any way in that direction. Am I on my own, or what am I missing?
As far as your first question goes, I think you are good with mixing async:true and the EmbeddedRecordsMixin for your case. See this blog post and my example js-bin
As for 2, EmbeddedRecordsMixin leaves you on your own for that. But if you look at the code, all it does is push the records into the store when extracting them, so to reverse it all you should have to do is unload those records from the store. I'd keep a reference to the child records, then on a successful delete of the parent, clean up the children with record.unload(). Same example js-bin
To answer number (1) for anybody who may stumble upon this question later on: Encouraged by Kori John Roys' answer I've submitted a pull request to ember data to clearify the documentation. It was accepted, therefore now on the documentation only warns to mix async: true with embedded reading.

Can I make Rails' CookieStore use JSON under the hood?

I feel like it should be obvious doing this from reading the documentation, but maybe somebody can save me some time. We are using Ruby's CookieStore, and we want to share the cookie with another server that is part of our website which is using WCF. We're already b64-decoding the cookie and we are able to validate the signature (by means of sharing the secret token), all of that is great... but of course the session object is marshalled as a Ruby object, and it's not clear what is the best way to proceed. We could probably have the WCF application make a call to Ruby and have it unmarshal the object and write it out as JSON, but that seems like it will add an unnecessary layer of complexity to the WCF server.
What I'd really like to do is maybe subclass CookieStore, so that instead of just b64 encoding the session object, it writes the object to JSON and then b64's it. (And does the reverse on the way back in, of course) That way, the session token is completely portable, I don't have to worry about Ruby version mismatches, etc. But I'm having trouble figuring out where to do that. I thought it would be obvious if I pulled up the source for cookie_store.rb, but it's not (at least not to me). Anybody want to point me in the right direction?
(Anticipating a related objection: Why the hell do we have two separate servers that need to be so intimately coordinated that they share the session cookie? The short answer: Deadlines.)
Update: So from reading the code, I found that when the MessageVerifier class gets initialized, it looks to see if there is an option for :serializer, and if not it uses Marshal by default. There is already a class called JSON that fulfills the same contract, so if I could just pass that in, I'd be golden.
Unfortunately, the initialize function for CookieStore very specifically only grabs the :digest option to pass along as the options to MessageVerifier. I don't see an easy way around this... If I could get it to just pass along that :serializer option to the verifier_for call, then achieving what I want would literally be as simple as adding :serializer => JSON to my session_store.rb.
Update 2: A co-worker found this, which appears to be exactly what I want. I haven't gotten it to work yet, though... getting a (bah-dump) stack overflow. Will update once again if I find anything worthy of note, but I think that link solves my problem.

What's a clean way to handle ajax success callbacks through a chain of object methods?

So, I'm trying to improve my javascript skills and get into using objects more (and correctly), so please bear with me, here.
So, take this example: http://jsfiddle.net/rootyb/mhYbw/
Here, I have a separate method for each of the following:
Loading the ajax data
Using the loaded ajax data
Obviously, I have to wait until the load is completed before I use the data, so I'm accessing it as a callback.
As I have it now, it works. I don't like adding the initData callback directly into the loadData method, though. What if I want to load data and do something to it before I use it? What if I have more methods to run when processing the data? Chaining this way would get unreadable pretty quickly, IMO.
What's a better, more modular way of doing this?
I'd prefer something that doesn't rely on jQuery (if there even is a magical jQuery way), for the sake of learning.
(Also, I'm sure I'm doing some other things horribly in this example. Please feel free to point out other mistakes I'm making, too. I'm going through Douglas Crockford's Javascript - The Good Parts, and even for a rank amateur, it's made a lot of sense, but I still haven't wrapped my head around it all)
Thanks!
I don't see a lot that should be different. I made an updated version of the fiddle here.
A few points I have changed though:
Use the var keyword for local variables e.g., self.
Don't add a temporary state as an object's state e.g., ajaxData, since you are likely to use it only once.
Encapsulate as much as possible: Instead of calling loadData with the object ajaxURL, let the object decide from which URL it should load its data.
One last remark: Don't try to meet requirements you don't have yet, even if they might come up in the future (I'm referring to your "What if...?" questions). If you try, you will most likely find out that you either don't need that functionality, or the requirements are slightly different from what you expected them to be in the past. If you have a new requirement, you can always refactor your model to meet them. So, design for change, but not for potential change.

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

Categories

Resources