Fórum

AUI - Need AutoComplete example that fetches json data through ajax/sjax

thumbnail
Thomas Berg, modificado 13 Anos atrás.

AUI - Need AutoComplete example that fetches json data through ajax/sjax

Regular Member Postagens: 131 Data de Entrada: 07/09/09 Postagens Recentes
The example at http://alloy.liferay.com/demos.php?demo=autocomplete is good but uses a local variable as the datasource. I've been looking for an example that shows how to use AUI.AutoComplete that fetches (json) data from a database through ajax but no luck so far...

So, now I'm turning to the great Liferay community emoticon


My code (which doesn't work for browsers other than Firefox):

    window.AC = new A.AutoComplete(
        {
            dataSource: function(request) {
                var items = null;
                resUrl.setResourceId("depositSearch");
                resUrl.setParameter('search',A.one('#<portlet:namespace />_searchField').get('value'));
                A.io.request(resUrl.toString(), {
                    cache: true,
                    sync: true,
                    timeout: 1000,
                    dataType: 'json',
                    method: 'get',
                    on: {
                        success: function() {
                            items = this.get('responseData');
                        },
                        failure: function() {
                        }
                    }
                });

                return items;
            },
            dataSourceType: 'Function',
            schema:  {
                metaFields: {javaClass:"javaClass"},
                resultListLocator: "list",
                resultFields: ['id', 'name']
            },
            schemaType: 'json',
            forceSelection: true,
            autoHighlight: false,
            matchKey: 'id',
            queryDelay: 0.5,
            typeAhead: true,
            contentBox: '#myContainer',
            input: '#<portlet:namespace />_searchField'
        }
    );


The above works in Firefox. For other browsers, I can see in the logs that calls are made and the results are properly created at the server-side. Internet Explorer 8 fetches and displays the results if I leave the searchbox empty ...

I created a jira ticket for this but am not sure if it's really a bug or just me doing something wrong.

I seem to recall reading something about YUI and problems with synchronous calls sync: true. Maybe this is the reason? But with sync:false, the above fails since items (returned by the datasource function) will be null if not waiting for the data to arrive.

Hopefully, someone has got a solution to this, perhaps using some predefined datasource rather than a function.

Any insight on this would be great!
thumbnail
Tanweer Ahmed ., modificado 1 Ano atrás.

RE: AUI - Need AutoComplete example that fetches json data through ajax/sja

Expert Postagens: 322 Data de Entrada: 11/03/10 Postagens Recentes
Has anyone implemented the Alloy UI AutoComplete functionality.I went through the Alloy UI website but not of much help.
Mauricio Saglietto, modificado 13 Anos atrás.

RE: AUI - Need AutoComplete example that fetches json data through ajax/sja

New Member Postagens: 3 Data de Entrada: 05/07/10 Postagens Recentes
Im looking for the same .. if u find a way ... let us know ...
thumbnail
Tanweer Ahmed ., modificado 1 Ano atrás.

RE: AUI - Need AutoComplete example that fetches json data through ajax/sja

Expert Postagens: 322 Data de Entrada: 11/03/10 Postagens Recentes
The following alloy autocomplete code works fine.But instead of associating autocomplete with the div element,I want to associate with my input text field.
<div id="myAutoComplete"></div>
<script type="text/javascript" charset="utf-8">
AUI().use('aui-autocomplete', function(A) {

	var cities = [
	        ['AH', 'Ahmedabad', 'The Land of IIM'],
            ['AM', 'Amritsar', 'City of golden Temple'],
	        ['BL', 'Bangalore', 'Silicon Valley of India'],
	        ['CA', 'Calcutta', 'City of Joy'],
	        ['DL', 'Delhi', 'Land of Hearts'],
	        ['JA', 'Jaipur', 'The Pink City'],
            ['JP', 'Jodhpur', 'The Blue City'],
	        ['SU', 'surat', '.Diamond City']
 ];

	window.AC = new A.AutoComplete(
		{
			dataSource: cities,
			schema: {
				resultFields: ['key', 'name', 'description']
			},
			matchKey: 'name',
			delimChar: ',',
			typeAhead: true,
			contentBox: '#myAutoComplete'
		}
	);
       AC.render();
});
</script>


Any help will be much appreciated
thumbnail
Tanweer Ahmed ., modificado 1 Ano atrás.

RE: AUI - Need AutoComplete example that fetches json data through ajax/sja

Expert Postagens: 322 Data de Entrada: 11/03/10 Postagens Recentes
Hello every1,

Still waiting for the implemented code....
thumbnail
Scott Lee, modificado 13 Anos atrás.

RE: AUI - Need AutoComplete example that fetches json data through ajax/sja

Junior Member Postagens: 55 Data de Entrada: 26/09/06 Postagens Recentes
to hook it onto an input text field, just add the "input: '#<portlet:namespace/>to" option like Thomas had posted.

<div id="<portlet:namespace />autoCompleteContainer">
	<aui:input name="to" value="<%= to %>" />
</div>

Hope that helps
thumbnail
Henk Schipper, modificado 13 Anos atrás.

RE: AUI - Need AutoComplete example that fetches json data through ajax/sja

New Member Postagens: 10 Data de Entrada: 26/01/07 Postagens Recentes
@Scott

Please don't understand me wrong, but I am still getting a bit used to alloy. What should be the correct code when using a datasource in ajax. I tried several things and I know my servlet is working (excuse the language) to retrieve the words/products, and my ajax call is correct, because I see my data which is being transfered, but the last part. I cannot get the data in the autocomplete field.

I used the example of Thomas. But please extend the source.

Henk
thumbnail
Tanweer Ahmed ., modificado 1 Ano atrás.

RE: AUI - Need AutoComplete example that fetches json data through ajax/sja

Expert Postagens: 322 Data de Entrada: 11/03/10 Postagens Recentes
THnx Scott ,

Sooper...
thumbnail
Corné Aussems, modificado 13 Anos atrás.

RE: AUI - Need AutoComplete example that fetches json data through ajax/sja

Liferay Legend Postagens: 1313 Data de Entrada: 03/10/06 Postagens Recentes
Hi all,
I managed to get the ajax call return this JSON string [{"id":"1","name":"testname 1"},{"id":"2","name":"testname 2"}] but i get a yellow Icon and no autocomplete.

Could someone help me out here?

<div id="myContainer">
  <aui:input name="searchField" value="" />
</div>



<aui:script use="aui-dialog,liferay-portlet-url">
AUI().use('aui-autocomplete', function(A) {
    window.AC = new A.AutoComplete( 
        { 
            dataSource: function(request) { 
                var items = null; 
 		var urlS = '<portlet:resourceurl id="search" />'+'&amp;search='+A.one('#<portlet:namespace />searchField').get('value');
                A.io.request(urlS, { 
                    cache: true, 
                    sync: true, 
                    timeout: 1000, 
                    dataType: 'json', 
                    method: 'get', 
                    on: { 
                        success: function() { 
                            items = this.get('responseData'); 
                        }, 
                        failure: function() { 
                        } 
                    } 
                }); 

                return items; 
            }, 
            dataSourceType: 'Function', 
            schema: { 
                metaFields: {javaClass:"javaClass"}, 
                resultListLocator: "list", 
                resultFields: ['id', 'name'] 
            }, 
            schemaType: 'json', 
            forceSelection: true, 
            autoHighlight: false, 
            matchKey: 'id', 
            queryDelay: 0.5, 
            typeAhead: true, 
            contentBox: '#myContainer', 
            input: '#<portlet:namespace />searchField' 
        } 
    ); 

    AC.resultTypeList = false; 
    AC.formatResult = function(oResultData, sQuery, sResultMatch) { 
        return ('<span style="color:#191970;">' + sResultMatch + "</span>, " + oResultData.name); 
    }; 

    AC.render();
});
</aui:script> 




	public void serveResource(ResourceRequest request, ResourceResponse response) throws IOException, PortletException {
try {
	String searchFor = ParamUtil.getString(request, "search");
			
	JSONArray jsonResult = com.liferay.portal.kernel.json.JSONFactoryUtil.createJSONArray();
				
	JSONObject jsonRow = com.liferay.portal.kernel.json.JSONFactoryUtil.createJSONObject();
		jsonRow.put("id", "1");
		jsonRow.put("name", "testname 1");
		jsonResult.put(jsonRow);

	JSONObject jsonRow2 = com.liferay.portal.kernel.json.JSONFactoryUtil.createJSONObject();
		jsonRow2.put("id", "2");
		jsonRow2.put("name", "testname 2");
		jsonResult.put(jsonRow2);

				
	_log.debug("serveResource() jsonResult.toString()="+ jsonResult.toString());
				
				response.getWriter().append(jsonResult.toString());

			} catch (Exception e) {
				e.printStackTrace();
			}

		super.serveResource(request, response);
	}
thumbnail
Corné Aussems, modificado 13 Anos atrás.

RE: AUI - Need AutoComplete example that fetches json data through ajax/sja

Liferay Legend Postagens: 1313 Data de Entrada: 03/10/06 Postagens Recentes
Just some more considerations it must be the json data that is bugging me because a simple dataset is working fine;

window.AC = new A.AutoComplete( 
        { 
            dataSource: function(request) { 
                var items = null; 
				var urlS = '<portlet:resourceurl id="search" />'+'&amp;search='+A.one('#<portlet:namespace />searchwords').get('value');
                A.io.request(urlS, { 
                    cache: true, 
                    sync: true, 
                    timeout: 1000, 
                    method: 'get', 
                    on: { 
                        success: function() { 
                            items =  eval(this.get('responseData')); // the evil eval 
                        }, 
                        failure: function() { 
                        } 
                    } 
                }); 

                return items; 
            }, 
            dataSourceType: 'Function', 
			schema: {
				resultFields: ['name']
			}, 
            matchKey: 'name',
            delimChar: '',
            typeAhead: true, 
            contentBox: '#myContainer',
            input: '#<portlet:namespace />searchwords'            

        } 
    ); 
    AC.render();
thumbnail
jelmer kuperus, modificado 13 Anos atrás.

RE: AUI - Need AutoComplete example that fetches json data through ajax/sja

Liferay Legend Postagens: 1191 Data de Entrada: 10/03/10 Postagens Recentes
I was playing around with this tonight. attached you will find an example portlet that demonstrates the use of the AutoComplete component.

it includes both a plain javascript and ajax example.

I hope this helps
thumbnail
Corné Aussems, modificado 13 Anos atrás.

RE: AUI - Need AutoComplete example that fetches json data through ajax/sja

Liferay Legend Postagens: 1313 Data de Entrada: 03/10/06 Postagens Recentes
Thanks for your help again Jelmer;

My problem was as stupid as ever;
 resultListLocator: "list", 

I didn't understand that i had to wrap my JsonArray into a JsonObject mapped with the key 'list'.

Cheers
thumbnail
Thomas Berg, modificado 13 Anos atrás.

RE: AUI - Need AutoComplete example that fetches json data through ajax/sja

Regular Member Postagens: 131 Data de Entrada: 07/09/09 Postagens Recentes
Thanks Jelmer! Got the missing piece (defining a datasource)!

Your example works in Firefox but I I cannot get it to work correctly in IE8. When searching, the warning symbol is displayed (see attached image).

I noticed that there's a semicolon (;) missing in view.jsp and thought that might be the reason but it makes no difference:

autocomplete.generateRequest = function(query) {
    return {
        request: '&amp;q=' + query
    };
}[color=#F31919];[/color]
thumbnail
jelmer kuperus, modificado 13 Anos atrás.

RE: AUI - Need AutoComplete example that fetches json data through ajax/sja

Liferay Legend Postagens: 1191 Data de Entrada: 10/03/10 Postagens Recentes
tested it with liferay 6.0.5 on ie 8.0.7600.16385 on windows 7 and i do not have this problem

oh and the missing semi colon is actually not a bug as it is allowed per spec

http://bclary.com/2004/11/07/#a-7.9
thumbnail
Thomas Berg, modificado 13 Anos atrás.

RE: AUI - Need AutoComplete example that fetches json data through ajax/sja

Regular Member Postagens: 131 Data de Entrada: 07/09/09 Postagens Recentes
Hello Jelmer,

Sorry for wasting your time, as it turned out, it wasn't working in Firefox either... Due to the fact that I mixed up which server was currently running!

I have one 6.0.5 server and one 6.0.10. On the latter I escape all URLS by default so by adding

var dataSource = new A.DataSource.IO(
    {
        source: '<portlet:resourceurl [color="#1F22E6]escapeXml=&quot;false&quot;[/color]" />'
    }
);


It works in both IE and Firefox...

Thanks again

Regards Thomas
Rakesh Goswami, modificado 11 Anos atrás.

RE: AUI - Need AutoComplete example that fetches json data through ajax/sja

New Member Postagens: 15 Data de Entrada: 21/02/12 Postagens Recentes
please check this..I am facing problem on ajax call with alloy UI.
allou ui and ajax
thumbnail
Mazhar Alam, modificado 11 Anos atrás.

RE: AUI - Need AutoComplete example that fetches json data through ajax/sja

Regular Member Postagens: 191 Data de Entrada: 25/11/11 Postagens Recentes
Helpful post
thumbnail
Akash Patil, modificado 11 Anos atrás.

RE: AUI - Need AutoComplete example that fetches json data through ajax/sja

Junior Member Postagens: 75 Data de Entrada: 13/12/10 Postagens Recentes
jelmer kuperus:
I was playing around with this tonight. attached you will find an example portlet that demonstrates the use of the AutoComplete component.

it includes both a plain javascript and ajax example.

I hope this helps



HI, Thanks, gr8 war file. easy to understand and customize
thumbnail
Aneesha Rao, modificado 11 Anos atrás.

RE: AUI - Need AutoComplete example that fetches json data through ajax/sja

New Member Postagens: 14 Data de Entrada: 24/02/12 Postagens Recentes
Hi,

How can i use the same code for directory portlet?
I am not able to include it in a hook.
Please help.

--Regards,
Aneesha
thumbnail
Antonio Musarra, modificado 11 Anos atrás.

RE: AUI - Need AutoComplete example that fetches json data through ajax/sja

Junior Member Postagens: 66 Data de Entrada: 09/08/11 Postagens Recentes
Hi,
Try to see the complete example at Alloy UI AutoComplete Ajax Example
Instead the repository https://github.com/amusarra/liferay-aui-autocomplete-ajax-example find the complete project format maven.

Bye,
Antonio.emoticon
thumbnail
mohammad azaruddin, modificado 10 Anos atrás.

RE: AUI - Need AutoComplete example that fetches json data through ajax/sja

Expert Postagens: 492 Data de Entrada: 17/09/12 Postagens Recentes
Hi Jelmer Kuperus
I implemented autocomplete which takes multiple inputs seperated by comma,which include duplicate as well.so how can i avoid duplicates

HTH
thumbnail
mohammad azaruddin, modificado 10 Anos atrás.

RE: AUI - Need AutoComplete example that fetches json data through ajax/sja

Expert Postagens: 492 Data de Entrada: 17/09/12 Postagens Recentes
Hi all

here input field should not accept duplicate data..there are two electronics.so if user select electronics for the second time it should not accept.Any solution
Henry K, modificado 13 Anos atrás.

RE: AUI - Need AutoComplete example that fetches json data through ajax/sja

Junior Member Postagens: 40 Data de Entrada: 27/01/10 Postagens Recentes
I can't get remote data to work with autocomplete. What am I doing wrong? Thanks for any help you can provide.

drop-down-1 will work just fine, but drop-down-2 returns the exclamation mark.

http://localhost:8080/c/journal/get_template?groupId=10165&templateId=11803 is simply a template that has ["Chicago","Charlotte","New York","New Brunswick"] as its content.


<h1>No ajax</h1>

<div id="<portlet:namespace />drop-down-1"></div>

<aui:script use="aui-autocomplete">

var cities = ["Chicago","Charlotte","New York","New Brunswick"];

new A.AutoComplete(
{
dataSource: cities,
schema: {
resultFields: ['name']
},
matchKey: 'name',
delimChar: ',',
typeAhead: true,
contentBox: '#<portlet:namespace />drop-down-1'
}
).render();

</aui:script>


<h1>Ajax</h1>
<div id="<portlet:namespace />drop-down-2"></div>


<aui:script use="aui-autocomplete">

var remoteCities = new A.DataSource.IO( { source: 'http://localhost:8080/c/journal/get_template?groupId=10165&templateId=11803'} );

var autocomplete = new A.AutoComplete(
{
dataSource: remoteCities,
schema: {
resultFields: ['name']
},
matchKey: 'name',
delimChar: ',',
typeAhead: true,
contentBox: '#<portlet:namespace />drop-down-2'
}
).render();


autocomplete.generateRequest = function(query) {
return {
request: '&q=' + query
};
}

autocomplete.render();

</aui:script>
thumbnail
Reigo Reinmets, modificado 9 Anos atrás.

RE: AUI - Need AutoComplete example that fetches json data through ajax/sja

New Member Postagens: 4 Data de Entrada: 29/07/10 Postagens Recentes
Since I didn't find a good tutorial for how to use Autocomplete with Service Builder JSON service I decided to make one myself.
It uses service builder based "contact" service to find contacts by name and demonstrates how to build custom query template and result parsing.
I've implemented a sample datasource, query template, result list locator, result formatter and even the result text locator.

You can check out the tutorial here: AUI Autocomplete with Service Builder JSON/