留言板

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

thumbnail
Thomas Berg,修改在13 年前。

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

Regular Member 帖子: 131 加入日期: 09-9-7 最近的帖子
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 .,修改在1 年前。

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

Expert 帖子: 322 加入日期: 10-3-11 最近的帖子
Has anyone implemented the Alloy UI AutoComplete functionality.I went through the Alloy UI website but not of much help.
Mauricio Saglietto,修改在13 年前。

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

New Member 帖子: 3 加入日期: 10-7-5 最近的帖子
Im looking for the same .. if u find a way ... let us know ...
thumbnail
Tanweer Ahmed .,修改在1 年前。

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

Expert 帖子: 322 加入日期: 10-3-11 最近的帖子
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 .,修改在1 年前。

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

Expert 帖子: 322 加入日期: 10-3-11 最近的帖子
Hello every1,

Still waiting for the implemented code....
thumbnail
Scott Lee,修改在13 年前。

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

Junior Member 帖子: 55 加入日期: 06-9-26 最近的帖子
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,修改在13 年前。

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

New Member 帖子: 10 加入日期: 07-1-26 最近的帖子
@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 .,修改在1 年前。

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

Expert 帖子: 322 加入日期: 10-3-11 最近的帖子
THnx Scott ,

Sooper...
thumbnail
Corné Aussems,修改在13 年前。

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

Liferay Legend 帖子: 1313 加入日期: 06-10-3 最近的帖子
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,修改在13 年前。

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

Liferay Legend 帖子: 1313 加入日期: 06-10-3 最近的帖子
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,修改在13 年前。

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

Liferay Legend 帖子: 1191 加入日期: 10-3-10 最近的帖子
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,修改在13 年前。

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

Liferay Legend 帖子: 1313 加入日期: 06-10-3 最近的帖子
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,修改在13 年前。

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

Regular Member 帖子: 131 加入日期: 09-9-7 最近的帖子
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,修改在13 年前。

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

Liferay Legend 帖子: 1191 加入日期: 10-3-10 最近的帖子
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,修改在13 年前。

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

Regular Member 帖子: 131 加入日期: 09-9-7 最近的帖子
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,修改在11 年前。

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

New Member 帖子: 15 加入日期: 12-2-21 最近的帖子
please check this..I am facing problem on ajax call with alloy UI.
allou ui and ajax
thumbnail
Mazhar Alam,修改在11 年前。

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

Regular Member 帖子: 191 加入日期: 11-11-25 最近的帖子
Helpful post
thumbnail
Akash Patil,修改在11 年前。

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

Junior Member 帖子: 75 加入日期: 10-12-13 最近的帖子
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,修改在11 年前。

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

New Member 帖子: 14 加入日期: 12-2-24 最近的帖子
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,修改在11 年前。

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

Junior Member 帖子: 66 加入日期: 11-8-9 最近的帖子
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,修改在10 年前。

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

Expert 帖子: 492 加入日期: 12-9-17 最近的帖子
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,修改在10 年前。

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

Expert 帖子: 492 加入日期: 12-9-17 最近的帖子
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,修改在13 年前。

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

Junior Member 帖子: 40 加入日期: 10-1-27 最近的帖子
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,修改在9 年前。

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

New Member 帖子: 4 加入日期: 10-7-29 最近的帖子
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/