« Back

AlloyUI - Working with Ajax

Company Blogs March 17, 2010 By Nate Cavanaugh Staff

Ajax is one of those patterns that are a must have with a UI framework, so let's go ahead and jump right into doing some Ajax requests, and then we'll dive into the more complex cases.
 
Let's prep our sandbox, but this time, the module we're going to use is called "aui-io-request".
 
AUI().use('aui-io-request', function(A){
 // Our code will run here
});
 
The simple of the simple, let's assume we're just going to be making a simple ajax request to a plain html file, called "test.html".
 
A.io.request('test.html');
 
That's all there is to it. However, that's not very interesting because it doesn't do anything.
 
Let's say want to send a POST request to the server:
 
A.io.request('test.html', {
   method: 'POST',
   data: {
     key1: 'value'
   }
});
 
How about responding to the server? There are 5 possible callbacks: start, complete, success (or) failure, and end.
 
If I wanted to alert the response from the server, here's what I would do: 
A.io.request('test.html', {
  on: {
   success: function() {
     alert(this.get('responseData'));
   }
  }
});

What is this.get('responseData')? It's basically a normalized property of what is returned from the server. It's useful because A.io.request supports having different types of data returned by the server and automatically handled.
For instance, if your server returns JSON like {"myProperty": 2}, you could do something like:
 
A.io.request('test.html', {
  dataType: 'json',
  on: {
   success: function() {
     alert(this.get('responseData').myProperty); //alerts 2
   }
  }
});
 
You can also work with XML that way. Assuming your server returns something like: <name>AlloyUI</name> you could do:
A.io.request('test.html', {
  dataType: 'xml',
  on: {
    success: function() {
     alert(A.all(this.get('responseData')).all('name').text()); // alerts AlloyUI
    }
  }
});

You can also submit all of the data in a form via ajax as well. Here's the simplest version: 
A.io.request('test.html', {
  form: {

      id: 'myFormId'

  }
});
 
That will serialize all of the data in the form, and send it to "test.html".
 
One other handy feature of this is that you can define an ajax connection once, and reuse it multiple times, and start and stop it later on.
Here's an example: 
var myAjaxRequest = A.io.request('test.html', {
    method: 'POST',
    data: {
      key1: 'value1'

    }

});

Now later on, if I want to make that same ajax call again, all I have to do is call:
 
myAjaxRequest.start();
 
But what if I want to just define the call, but not execute it the first time (for instance, you know you want to run it later, but you don't want to update the server), you can do:
 
var myAjaxRequest = A.io.request('test.html', {
 autoLoad: false,
 ...
});
 
What's cool about this is that if later on, you want to change one of the properties before you send the request, you can do that as well. For instance, let's say you want to disable caching before you start the connection again:
 
myAjaxRequest.set('cache', false);
 
Or if you wanted to change from POST to GET
 
myAjaxRequest.set('method', 'GET');
 
Or change the dataType to JSON:
 
myAjaxRequest.set('dataType', 'json');
 
Or even change the URI at the last moment:
 
myAjaxRequest.set('uri', 'new_test.html');
 
Then when you're ready you would call:
 
myAjaxRequest.start();
 
And if at any time after you have started the request, you want to stop the whole request, you can call:
 
myAjaxRequest.stop();
 
And that's most of it right there. There are some cool plugins that we have that make working with ajax easier, but since the next topic is on plugins, I'll cover those in the next blog post, and they'll be a nice segue between topics.
 
One of those plugins is called A.Plugin.IO, and it's incredibly awesome, because it simplifies the extremely common task of not only loading content into a node or a widget, but adding a loading indicator to that node and automatically parsing the javascript for you.
 
I'll go into more details in the Plugins post, but it's really handy.
 
See you then!
Threaded Replies Author Date
Thank You :) . Looking forward for Plugins Post :) Bavithra Rajendran March 18, 2010 2:47 AM
Cool! Thank you, Nate. Jonas Yuan March 18, 2010 8:59 AM
Really nice Nate! I do like these posts, I find... Julio Camarero March 22, 2010 1:56 AM
Hi Nate, Was wondering if its possible to wait... Sandeep Nair December 8, 2010 7:35 AM
Hi Nate and thanks for the post. Got a... Andrey Filippov March 25, 2011 8:36 AM
Hi to Learn More on Liferay Check out this... Rohit Salecha April 28, 2011 11:42 PM
This is good that we have got the client side... Muhammad Asif June 5, 2011 8:01 AM
Ok I have got it. You need to use serveResource... Muhammad Asif June 5, 2011 9:22 AM
how should I use AJAX call in EXT, for example... Aamir Khan June 22, 2011 3:26 AM
I'm not even sure I'm in the right place here: ... Brent Jensen August 17, 2011 9:39 PM
Hi Brent, that certainly is odd. I'd try the... Nate Cavanaugh August 18, 2011 9:17 AM
Hi Nate, thank you very much this is a good... Rubén García Tamayo February 7, 2012 4:10 AM
Thanku for providing cool approach to start... kiran kumar April 9, 2012 11:50 PM
But this calls is it working for Guest users? k venkatesh May 7, 2012 9:43 PM
Hi everybody I have a data for example <data>... Mahdi Lashkari October 10, 2012 4:33 AM
Hi Mahdi, this one is pretty simple. You can... Nate Cavanaugh October 11, 2012 9:23 AM
Thanks nate! but as I said, I want to fetch... Mahdi Lashkari October 12, 2012 10:52 PM
Hi nate, another thing is that " var x =... Mahdi Lashkari October 13, 2012 11:27 PM
Any Idea?:( I really need to solve this problem:( Mahdi Lashkari October 16, 2012 4:32 AM
[...] What we have done so far , Eclipse... Anonymous April 29, 2014 1:23 AM

Thank You emoticon . Looking forward for Plugins Post emoticon
Posted on 3/18/10 2:47 AM.
Cool! Thank you, Nate.
Posted on 3/18/10 8:59 AM.
Really nice Nate! I do like these posts, I find them very useful. Can't wait for the next one! emoticon
Posted on 3/22/10 1:56 AM.
Hi Nate,

Was wondering if its possible to wait till the request comes from the server and then process the next block of code. For example i have something like following

var msg="some mesg";
if(true){
msg = msg+someother_msg;
}else{
var test= doAjaxcallhere;
if(test = true){
msg = msg+new message;
}else{
msg = msg + else message
}
}
if(someother condition){
msg= msg+some other condition;
}

Is it possible that i can wait for ajax call response and then move on to further blocks
Posted on 12/8/10 7:35 AM.
Hi Nate and thanks for the post. Got a question.. Not long ago I ran into the problem with ajax call. I have a popup dialog with a form that is being submitted in ajax manner. After it I have something like this:

complete: function(id, resp, args) { console.log('complete'); ­ va­r templatePanel = A.one('#portlet:namespace/>prefsPanel'); ­ templatePanel.plug(A.Plugin.IO, { uri: '<%= refreshURL%>', method: 'GET' }­); ­ dialog.close();
},

And my div block is being refreshed only once - after it silence. It is cached somewhere. Although I added cache:false property it would not help... Do you happen to know the way to improve it?

Thanks in advance.
Posted on 3/25/11 8:36 AM.
Hi to Learn More on Liferay Check out this blog ,

http://liferaydemystified.blogspot.com/
Posted on 4/28/11 11:42 PM in reply to Andrey Filippov.
This is good that we have got the client side of ajax calls. If it is easy still its not clear to me how to handle the ajax request on the server side. I am using MVCPortlet with plain jsp. I would like to know how can I handle ajax request in this architecture on the server side. Thanks.
Posted on 6/5/11 8:01 AM.
Ok I have got it. You need to use serveResource method of MVCPortlet. You need to put your business logic in it and then you can return any data type and write out any data in your response. Perhaps there are more things to add. Exploring.
Posted on 6/5/11 9:22 AM.
how should I use AJAX call in EXT, for example I am modifieng community portlet, whare I need to put serveResource method
Posted on 6/22/11 3:26 AM in reply to Muhammad Asif.
I'm not even sure I'm in the right place here:
My superior is having me learn Liferay for web development. I'm only just now sort getting the hang of themes & designing them. However we have run into a "mystery @ symbol" located above the wrench in the tool icons, where the @ actually takes on the attributes of portet body text but I for the life of me cannot seem to get rid of it or find it within the code. I have a screen shot of the mystery symbol, not sure where/how I can attach it for all to see - at the very least I need some assistance as my superior is breathing down my neck. And if I'm in the wrong place could someone direct me to where I should be. Thanks, Brent
Posted on 8/17/11 9:39 PM.
Hi Brent, that certainly is odd. I'd try the forums with perhaps your version info and browser that you're seeing it in (you can link to the forum thread on my wall if you like). For the screenshot, I'd recommend something like Skitch (if you're on a mac) or Dropbox or even one of the the veritable array of options with free image hosts.

I hope that helps emoticon
Posted on 8/18/11 9:17 AM in reply to Brent Jensen.
Hi Nate, thank you very much this is a good post to start with aui-ajax!! very good work!!
Posted on 2/7/12 4:10 AM in reply to Nate Cavanaugh.
Thanku for providing cool approach to start with ajax. I am working with struts2 portlet in liferay 6 .My portlet class in portlet.xml is Jsr168Dispatcher. i tried using ajax ,request was going fine to my action class but iam unable to retrive proper responseData . I am getting some redundant javascript as my response data . Can u plz guide me where iam going wrong..
Posted on 4/9/12 11:50 PM in reply to Rubén García Tamayo.
But this calls is it working for Guest users?
Posted on 5/7/12 9:43 PM.
Hi everybody
I have a data for example
<data>
<x> .. </x>
<y> <z> .... </z> </y>
</data>
and I want to fetch <x> data. what should I do?
and I want to fetch <y> data with its inner tag (I want to fetch <z>..</z>). what should I do?
Thanks a lot
Posted on 10/10/12 4:33 AM in reply to k venkatesh.
Hi Mahdi, this one is pretty simple. You can pass in a config option called "selector" that will give you a NodeList of the items you want to work with.
So you could do:
A.io.request('path/to/file.xml', {
selector: 'data',
dataType: 'xml',
on: {
success: function(){
var data = this.get('responseData');
var x = data.one('x');
var z = data.one('y z');

console.log(x.text(), z.text()); // prints out values of x and z
}
}
});
Posted on 10/11/12 9:23 AM in reply to Mahdi Lashkari.
Thanks nate!
but as I said, I want to fetch all things in <y> tag. I mean I want to fetch "<z>..</z>".
My problem is that I pass html data in xml tags and I want to fetch html data with all of their tags. for example
<data>
<y>
<body> <div="align=center"> Liferay Is the Best </p> </body>
</y> </data>
I want to fetch <body> "<div="align=center"> Liferay Is the Best </p> </body>". what should I do?
Thanks a lot!
Posted on 10/12/12 10:52 PM in reply to Nate Cavanaugh.
Hi nate,
another thing is that " var x = data.one('x');" return null and doesn't fetch data emoticon
My code :
AUI().use('aui-io-request','datatype-xml',function(A) {
A.io.request("<%=ajaxActionUrl%>", {
data : {'rId' : A.one('#<portlet:namespace />rd').get('value')
},
selector: 'data',
dataType : 'xml',
on : {
success : function() {
if(this.get('responseData')==null) {
goToStartUrl()
}
else
{
var data = this.get('responseData');
alert(data.one('z));
}
}
}
­ });

});
it alerts null.
Posted on 10/13/12 11:27 PM in reply to Mahdi Lashkari.
Any Idea?emoticon I really need to solve this problememoticon
Posted on 10/16/12 4:32 AM in reply to Mahdi Lashkari.
[...] What we have done so far , Eclipse Installation Directory Structure Service Builder – I Service Builder – II and continuing to the last part . The MVC Framework and Alloy UI Every Portlet on a... [...] Read More
Posted on 4/29/14 1:23 AM.