Fórumok

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

thumbnail
Thomas Berg, módosítva 13 év-val korábban

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

Regular Member Bejegyzések: 131 Csatlakozás dátuma: 2009.09.07. Legújabb bejegyzések
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 ., módosítva 1 év-val korábban

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

Expert Bejegyzések: 322 Csatlakozás dátuma: 2010.03.11. Legújabb bejegyzések
Has anyone implemented the Alloy UI AutoComplete functionality.I went through the Alloy UI website but not of much help.
Mauricio Saglietto, módosítva 13 év-val korábban

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

New Member Bejegyzések: 3 Csatlakozás dátuma: 2010.07.05. Legújabb bejegyzések
Im looking for the same .. if u find a way ... let us know ...
thumbnail
Tanweer Ahmed ., módosítva 1 év-val korábban

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

Expert Bejegyzések: 322 Csatlakozás dátuma: 2010.03.11. Legújabb bejegyzések
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 ., módosítva 1 év-val korábban

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

Expert Bejegyzések: 322 Csatlakozás dátuma: 2010.03.11. Legújabb bejegyzések
Hello every1,

Still waiting for the implemented code....
thumbnail
Scott Lee, módosítva 13 év-val korábban

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

Junior Member Bejegyzések: 55 Csatlakozás dátuma: 2006.09.26. Legújabb bejegyzések
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, módosítva 13 év-val korábban

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

New Member Bejegyzések: 10 Csatlakozás dátuma: 2007.01.26. Legújabb bejegyzések
@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 ., módosítva 1 év-val korábban

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

Expert Bejegyzések: 322 Csatlakozás dátuma: 2010.03.11. Legújabb bejegyzések
THnx Scott ,

Sooper...
thumbnail
Corné Aussems, módosítva 13 év-val korábban

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

Liferay Legend Bejegyzések: 1313 Csatlakozás dátuma: 2006.10.03. Legújabb bejegyzések
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, módosítva 13 év-val korábban

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

Liferay Legend Bejegyzések: 1313 Csatlakozás dátuma: 2006.10.03. Legújabb bejegyzések
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, módosítva 13 év-val korábban

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

Liferay Legend Bejegyzések: 1191 Csatlakozás dátuma: 2010.03.10. Legújabb bejegyzések
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, módosítva 13 év-val korábban

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

Liferay Legend Bejegyzések: 1313 Csatlakozás dátuma: 2006.10.03. Legújabb bejegyzések
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, módosítva 13 év-val korábban

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

Regular Member Bejegyzések: 131 Csatlakozás dátuma: 2009.09.07. Legújabb bejegyzések
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, módosítva 13 év-val korábban

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

Liferay Legend Bejegyzések: 1191 Csatlakozás dátuma: 2010.03.10. Legújabb bejegyzések
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, módosítva 13 év-val korábban

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

Regular Member Bejegyzések: 131 Csatlakozás dátuma: 2009.09.07. Legújabb bejegyzések
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, módosítva 11 év-val korábban

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

New Member Bejegyzések: 15 Csatlakozás dátuma: 2012.02.21. Legújabb bejegyzések
please check this..I am facing problem on ajax call with alloy UI.
allou ui and ajax
thumbnail
Mazhar Alam, módosítva 11 év-val korábban

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

Regular Member Bejegyzések: 191 Csatlakozás dátuma: 2011.11.25. Legújabb bejegyzések
Helpful post
thumbnail
Akash Patil, módosítva 11 év-val korábban

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

Junior Member Bejegyzések: 75 Csatlakozás dátuma: 2010.12.13. Legújabb bejegyzések
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, módosítva 11 év-val korábban

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

New Member Bejegyzések: 14 Csatlakozás dátuma: 2012.02.24. Legújabb bejegyzések
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, módosítva 11 év-val korábban

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

Junior Member Bejegyzések: 66 Csatlakozás dátuma: 2011.08.09. Legújabb bejegyzések
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, módosítva 10 év-val korábban

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

Expert Bejegyzések: 492 Csatlakozás dátuma: 2012.09.17. Legújabb bejegyzések
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, módosítva 10 év-val korábban

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

Expert Bejegyzések: 492 Csatlakozás dátuma: 2012.09.17. Legújabb bejegyzések
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, módosítva 13 év-val korábban

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

Junior Member Bejegyzések: 40 Csatlakozás dátuma: 2010.01.27. Legújabb bejegyzések
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, módosítva 9 év-val korábban

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

New Member Bejegyzések: 4 Csatlakozás dátuma: 2010.07.29. Legújabb bejegyzések
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/