need help in flow of ajax - ajax

http://www.ibm.com/developerworks/library/j-ajax1/ajax.gif
I came across this flow, i would like to know certain things over this.
What does Raise - > DOM Event do?
After creating an XMLHTTPRequest why do we create a callback function?
Register callback... what does it do?
Parse response into XML DOM?
Interogate response DOM?
Finally a basic question...
What does DOM contain and What does it do actually?

The DOM is an object representation of the HTML code. HTML documents are just simple text files, but it is often useful to consider one like it is a tree of elements. So, if your html contains <body><div>hello</div><div>world</div></body> then the DOM will have a "body" object that contains two "div" objects as children. It lets you examine and modify an HTML document in a program without having to do text parsing of the HTML code.
A DOM event is raised when the user interacts with an element of the DOM, so it's something like an "onclick" or "onkeypress" event. It will have an event handler, which is a function containing code to execute when the event occurs.
Because the XmlHttpRequest is asynchronous. After the request is sent, the page will not wait for the response but instead will continue executing the rest of your code. The callback function waits for the response from the server and then executes. So your code to request data from the server should go in the event handler, and the code to process the data goes in the callback.
This just tells the system that the callback function is to be called when the XmlHttpRequest gets data back from the server. If you had multiple XmlHttpRequests with different callbacks you would need to make sure each callback is registered to the right XmlHttpRequest.
This is the text processing that is involved in turning the HTML code into a DOM tree. It is often done automatically by the browser, so your javascript should not need to worry too much about it.
This just means the data processing you are doing with the data you received from the server. It will depend on what data you are getting and what you want to do with it.

Related

displaying the data in UI that received via ajax call

I m having 6 ajax calls on my page where i need to get data based on a query from server for each call. So, though we are getting data asynchronously from server, will the data get displayed on HTML page asynchronously or div by div in sequence?
Ajax is asynchronous and it does not guarantee ordered execution. It might happen that the first request responds last, so no, it will not be in ordered sequence.
If you need ordered requests, you can nest your callbacks or use promises like described in this thread.

Triggering Ajax event when an object changes its state

I have a small university project in which I have to show how certain algorithms work. Decided to use JSF for a simple webapp and save all the algorithm generated data into a database.
I thought to myself 'hey, it would be cool if I can show the user how the algorithm works step by step, nothing fancy, just plain formatted text that changes when the algorithm does its thing. An output text field with Ajax should get the work done!', but I can't quite get my head around a certain problem. Ajax triggers when a certain event occurs, like 'click' or 'keyup', but is there a way to make it trigger when an object in my ManagedBean class changes?
Don't know if I explained well enough, so here's an example of what I want to do:
An ArrayList in the ManagedBean is empty, the outputtext prints out nothing
After a certain amount of time, a new object is saved in the ArrayList, Ajax triggers and the outputtext prints out its onString()
After a certain amount of time again, the same object that was printed out before changes, Ajax triggers and the outputtext changes accordingly
I'm sorry if the problem isn't quite clear, tried describing it to the best of my ability.
What you describe isn't classic, client-triggered AJAX anymore but known as server-sent events (SSE). They're usually implemented using long-polling (periodic client requests that only get an answer if there's a server-side event).
Your favorite JSF toolkit probably supports it under the name "Push". Here's a Primefaces example.
However, for your simple use case I'd suggest using polling instead. See this example. The main difference is that your server side logic switches to keep a list of "to be displayed" strings/ids/objects. When your browser client polls the server (the listener method gets called), assign the first item to a String field in a backing bean and have your client re-render an area where this String is shown.
Note that you can do this in plain JSF-2, there's no need for Primefaces.

ajax request per div

I have 10 divs on my page and each div will render its own ajax request when the page loads. I know i can make max 2 ajax requests and then i have to wait (based on the browser) before the next request gets fired. I was wondering what will be the best way to design such a page.
Should i create ajax request inside the divs so that i can pass the div as a context to the ajax reponse? something like this:
<div id="request1">
make an ajax request
</div>
<div id="request2">
make an ajax request
</div>
and so on......
is there any chance that result may get mixed up and wrong div will render the result from the different request?
--Edit--
I cannot make a single call as they all make calls to separate service and that service may or may not be available.
AJAX is Asynchronous, that way, if you call 10 AJAX requests using either $.get, $.post or $.ajax, those requests will fire independently without waiting for the previous ones. So unless you have a special requirements that need to avoid that, just go ahead
Why don't you send only one ajax request when the page loads, and let your server side script return the data needed for the 10 divs in form of json? That would reduce the number of requests sent to the server and the work would be a lot cleaner as well.
Edit : ok since this is no longer and option. You can queue the requests one after another, if each request you are sending, depends on each other (for eg: you might set a flag in the first request, which again gets check in a later request) you can queue them. I have been using this plugin for quite a while now, and it has come in handy)
You might be able to use in your case so check it out.
http://www.protofunc.com/scripts/jquery/ajaxManager/

ExtJS 4 - How to check if all current ajax requests are completed and then perform an action?

I have a page which fires Ajax requests for validations at server side. I need to perform an action when all the ajax requests have finished loading or are completed.
For this, I am using Ext.Ajax.isLoading() in a recursive function in following way:
function chechValid(){
if(Ext.Ajax.isLoading()){
checkValid();
}else{
//Code for Action 1
}
}//EOF
checkValid();
//Code for Action 2
The problem is that when I do this, browsers give the following errors:
Mozill FF - too much recursions
IE - Stack overflow at line:18134
If this recursion is a heavy thing for the browsers, then how to perform a task when all the Ajax requests have finished loading?
Using delay is not what I want as, if delay is used then browser begins executing the other code (like 'Code for Action 2' as shared above) which is not what is expected.
The main aim is that the browser shouldn't execute anything unless all the Ajax requests are complete and once completed then it should perform a particular action.
Any suggestions/help on this one?
Thanks in Advance.
PS: Using ExtJs 4.0.7
(Updated)More Detail about the actual situation:-
Here is brief description of the situtaion being faced - There is a form, in which I need to perform server side validations on various fields. I am doing so by firing an ajax request on blur event. Depending upon the server response of validation Ajax fired on blur, fields are marked invalid and form submission is not allowed. (Avoiding 'change' event as that causes alot of overhead on server due to high number of Ajas requests and also leads to fluctuating effects on a field when response from various such Ajax requests are received).
Things are working fine except in one case - when user modifies the value of a field and instead of 'tab'bing out from the field she directly clicks at the save button. In such a case, though, the blur event gets fired but the processing of 'Save' doesn't wait for Ajax Validation response and submits the form. Thus, I somehow need to check if Ajax requests have finihed loading and the process the saving of form. requestComplete would unfortunately not serve the purpose here. And if try using the recursion, then of course, the browser is hung due to high usage of resources. Same case occurs if I try using a pause script work around ( as shared here - Javascript Sleep).
Any possible workaround for this one?
TIA
Your method will lead to infinite recursion.
A better way is to register a callback function in Ext.Ajax.requestcomplete, something like this (not tested):
Ext.Ajax.on('requestcomplete', function(conn, response, options) {
if (!Ext.Ajax.isLoading()) {
//your action...
}
}
};
Unless I am misunderstanding the issue couldn't you create a couple of globals. I know globals are bad, but in this case it will save you quite a bit of headache. One global would be "formReady" and initially set it to false, the other would be "ajaxActive" and set to false. You would also add an onSubmit method that would validate that "formReady" was true and if not alert the user that validation was occurring (or you could set a timeout for form submission again and have a second validation that checks to see if "ajaxActive" is true). When the AJAX call is made it would set the variable "ajaxActive" to true and once complete would set formReady to true. You could also potentially resubmit the form automatically if the response from the AJAX was that the form was good.
Ext.Ajax.request() returns a transaction object when you call it, which is unique and allows you to recognise and abort specific Ajax requests.
By just calling Ext.Ajax.isLoading() without a specified transaction object, it defaults to the last request, which is why you have to call it recursively at the moment.
If it were me, I'd create an array of these transaction objects as you fire them off, and pass each of those in as optional parameters to the Ext.Ajax.isLoading() function to check if a particular request has finished. If it has, you can remove that transaction object from the array, and only progress with the save when your array is empty.
This would get round your recursion problem, since you've always got a finite number of requests that you're waiting on.
if (Object.keys(Ext.Ajax.requests).length === 0) console.log("No active requests");

Best practice for combining requests with possible different return types

Background
I'm working on a web application utilizing AJAX to fetch content/data and what have you - nothing out of the ordinary.
On the server-side certain events can happen that the client-side JavaScript framework needs to be notified about and vice versa. These events are not always related to the users immediate actions. It is not an option to wait for the next page refresh to include them in the document or to stick them in some hidden fields because the user might never submit a form.
Right now it is design in such a way that events to and from the server are riding a long with the users requests. For instance if the user clicks a 'view details' link this would fire a request to the server to fetch some HTML or JSON with details about the clicked item. Along with this request or rather the response, a server-side (invoked) event will return with the content.
Question/issue 1:
I'm unsure how to control the queue of events going to the server. They can ride along with user invoked events, but what if these does not occur, the events will get lost. I imagine having a timer setup up to send these events to the server in the case the user does not perform some action. What do you think?
Question/issue 2:
With regards to the responds, some being requested as HTML some as JSON it is a bit tricky as I would have to somehow wrap al this data for allow for both formalized (and unrelated) events and perhaps HTML content, depending on the request, to return to the client. Any suggestions? anything I should be away about, for instance returning HTML content wrapped in a JSON bundle?
Update:
Do you know of any framework that uses an approach like this, that I can look at for inspiration (that is a framework that wraps events/requests in a package along with data)?
I am tackling a similar problem to yours at the moment. On your first question, I was thinking of implementing some sort of timer on the client side that makes an asycnhronous call for the content on expiry.
On your second question, I normaly just return JSON representing the data I need, and then present it by manipulating the Document model. I prefer to keep things consistent.
As for best practices, I cant say for sure that what I am doing is or complies to any best practice, but it works for our present requirement.
You might want to also consider the performance impact of having multiple clients making asynchrounous calls to your web server at regular intervals.

Resources