Forums de discussion

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

thumbnail
Thomas Berg, modifié il y a 13 années.

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

Regular Member Publications: 131 Date d'inscription: 07/09/09 Publications récentes
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 ., modifié il y a 1 année.

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

Expert Publications: 322 Date d'inscription: 11/03/10 Publications récentes
Has anyone implemented the Alloy UI AutoComplete functionality.I went through the Alloy UI website but not of much help.
Mauricio Saglietto, modifié il y a 13 années.

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

New Member Publications: 3 Date d'inscription: 05/07/10 Publications récentes
Im looking for the same .. if u find a way ... let us know ...
thumbnail
Tanweer Ahmed ., modifié il y a 1 année.

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

Expert Publications: 322 Date d'inscription: 11/03/10 Publications récentes
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 ., modifié il y a 1 année.

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

Expert Publications: 322 Date d'inscription: 11/03/10 Publications récentes
Hello every1,

Still waiting for the implemented code....
thumbnail
Scott Lee, modifié il y a 13 années.

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

Junior Member Publications: 55 Date d'inscription: 26/09/06 Publications récentes
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, modifié il y a 13 années.

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

New Member Publications: 10 Date d'inscription: 26/01/07 Publications récentes
@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 ., modifié il y a 1 année.

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

Expert Publications: 322 Date d'inscription: 11/03/10 Publications récentes
THnx Scott ,

Sooper...
thumbnail
Corné Aussems, modifié il y a 13 années.

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

Liferay Legend Publications: 1313 Date d'inscription: 03/10/06 Publications récentes
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, modifié il y a 13 années.

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

Liferay Legend Publications: 1313 Date d'inscription: 03/10/06 Publications récentes
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, modifié il y a 13 années.

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

Liferay Legend Publications: 1191 Date d'inscription: 10/03/10 Publications récentes
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, modifié il y a 13 années.

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

Liferay Legend Publications: 1313 Date d'inscription: 03/10/06 Publications récentes
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, modifié il y a 13 années.

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

Regular Member Publications: 131 Date d'inscription: 07/09/09 Publications récentes
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, modifié il y a 13 années.

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

Liferay Legend Publications: 1191 Date d'inscription: 10/03/10 Publications récentes
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, modifié il y a 13 années.

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

Regular Member Publications: 131 Date d'inscription: 07/09/09 Publications récentes
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, modifié il y a 11 années.

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

New Member Publications: 15 Date d'inscription: 21/02/12 Publications récentes
please check this..I am facing problem on ajax call with alloy UI.
allou ui and ajax
thumbnail
Mazhar Alam, modifié il y a 11 années.

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

Regular Member Publications: 191 Date d'inscription: 25/11/11 Publications récentes
Helpful post
thumbnail
Akash Patil, modifié il y a 11 années.

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

Junior Member Publications: 75 Date d'inscription: 13/12/10 Publications récentes
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, modifié il y a 11 années.

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

New Member Publications: 14 Date d'inscription: 24/02/12 Publications récentes
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, modifié il y a 11 années.

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

Junior Member Publications: 66 Date d'inscription: 09/08/11 Publications récentes
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, modifié il y a 10 années.

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

Expert Publications: 492 Date d'inscription: 17/09/12 Publications récentes
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, modifié il y a 10 années.

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

Expert Publications: 492 Date d'inscription: 17/09/12 Publications récentes
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

Pièces jointes:

Henry K, modifié il y a 13 années.

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

Junior Member Publications: 40 Date d'inscription: 27/01/10 Publications récentes
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, modifié il y a 9 années.

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

New Member Publications: 4 Date d'inscription: 29/07/10 Publications récentes
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/