I want to show address in my database to an autocomplete aui input field.Everything seems working fine.But im not able to retrive the address number of the record.How to use the on change event of autocomple-list or how can i access the selected item's json object
#Override
public void serveResource( ResourceRequest resourceRequest, ResourceResponse resourceResponse ) throws IOException,
PortletException
{
String cmd = ParamUtil.getString(resourceRequest, "get_address");
String myInputNode = ParamUtil.getString(resourceRequest, "addressAutocomplete");
System.out.println("addressAutocomplete"+myInputNode);
if (cmd.equals("get_address")) {
getUsers(resourceRequest, resourceResponse,myInputNode);
}
}
private void getUsers(ResourceRequest resourceRequest, ResourceResponse resourceResponse, String myInputNode) throws IOException, PortletException {
JSONArray usersJSONArray = JSONFactoryUtil.createJSONArray();
ThemeDisplay themeDisplay = (ThemeDisplay)resourceRequest.getAttribute(WebKeys.THEME_DISPLAY);
JSONObject userJSON=null;
try {
List<AddressMaster> userList=AddressMasterLocalServiceUtil.getAllAddressBySearchKey( myInputNode );
for(AddressMaster addressMaster:userList){
userJSON=JSONFactoryUtil.createJSONObject();
userJSON.put("addressNumber",addressMaster.getAdrNummer());
userJSON.put( "address", addressMaster.getAddress())
);
usersJSONArray.put(userJSON);
}
} catch (Exception e) {
}
PrintWriter out=resourceResponse.getWriter();
out.println(usersJSONArray.toString());
System.out.println("usersJSONArray"+usersJSONArray.toString());
}
Jsp File
<portlet:resourceURL var="getAddress">
<portlet:param name="get_address" value="get_address" />
</portlet:resourceURL>
<aui:input id="addressAutocomplete" name="addressAutocomplete" label="group_choose_address" style="width:700px"/>
<aui:script>
AUI().use('autocomplete-list','aui-base','aui-io-request','autocomplete-filters','autocomplete-highlighters',function (A) {
A.io.request('<%=getAddress%>',{
dataType: 'json',
method: 'GET',
on: {
success: function() {
//continents=this.get('responseData');
//alert(continents[0].name);
new A.AutoCompleteList(
{
allowBrowserAutocomplete: 'true',
activateFirstItem: 'true',
inputNode: '#<portlet:namespace/>addressAutocomplete',
resultTextLocator: 'address',
resultHighlighter:['phraseMatch'],
resultFilters:['phraseMatch'],
render: 'true',
source:this.get('responseData'),
});
}}
});
});
</aui:script>
It's a bit tricky to see exactly what'll be coming, but I think you could do:
var address_ac = new A.AutoCompleteList({... as you have it...});
address_ac.on('select', function (e) {
var selected_node = e.itemNode,
selected_data = e.result;
});
Docs here: http://alloyui.com/versions/1.5.x/api/classes/AutoCompleteList.html#events
Related
I am trying to filter datatable by select.
I can see the data in select but don't know how to filter it.
Here's my code.
Thanks
function getSearchList() {
$.post('#(Url.Action("GetSearchList", "ESR"))')
.success(function (data) {
if (data.length > 0) {
$.each(data, function () {
$('#Search_Id').append($('<option>', {
value: this.ID,
text: this.S_ID
}));
});
}
$(window).unblock();
})
}
and
$(document).ready(function () {
$('#Search_Id').select2({
placeholder: "Search",
allowClear: true,
});
});
and
<div class="col-sm-2">
<select class="select" id="Search_Id"></select>
</div>
following are whole backend side of codes
following are whole backend side of codes
following are whole backend side of codes
following are whole backend side of codes
following are whole backend side of codes
following are whole backend side of codes
public List<SearchId> GetSearchIdData()
{
string strSQL = string.Format(#"SELECT ID, S_ID FROM TBR");
using (var conn = SqlUtility.GetDBConnection())
{
conn.Open();
return conn.Query<SearchId>(strSQL).ToList();
}
}
and
public ActionResult GetSearchIdList()
{
JsonResult result;
List<SearchId> List = service.GetSearchIdList();
result = Json(List);
result.MaxJsonLength = int.MaxValue;
return result;
}
and
public class SearchId
{
public int ID { get; set; }
public string S_ID{ get; set; }
}
and
public List<SearchId> GetSearchIdList()
{
return repo.GetSearchIdData();
}
I have a function in c# that builds dictionary ,I need to pass this dictionary to my java-script function.
This is what I have tried
My server function
public partial class login : System.Web.UI.Page
{
protected Dictionary<string, string> GetTradingTypeToSelect()
{
Dictionary<string, string> dict = new Dictionary<string, string>();
try {
string Types =GetString("some text);
var items = Types.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
.Select(s => s.Split(new[] { '=' }));
foreach (var item in items)
{
dict.Add(item[1], item[0]);
}
//this working 100%
}
catch (Exception ex)
{
}
return dict;
}
}
My client:
$(document).ready(function () {
$("#Account").keyup(function () {
var TradingTypeToSelect = '<%=GetTradingTypeToSelect();%>';
//TradingTypeToSelect is equals to string '<%=GetTradingTypeToSelect();%>'
var test = TradingTypeToSelect[0].key;
var test2 = TradingTypeToSelect[0].value;
});
});
What am I missing here?
You can create a [WebMethod] in the code behind and call it from javascript using $.ajax.Below is a complete example:
Code behind:
[System.Web.Services.WebMethod]
public static Dictionary<string, string> GetTradingTypeToSelect()
{
var dict = new Dictionary<string, string>();
dict.Add("1", "Item 1");
dict.Add("2", "Item 2");
return dict;
}
.ASPX:
<head runat="server">
<title></title>
<script src="//code.jquery.com/jquery-1.12.3.min.js"></script>
<script type="text/javascript">
$(function () {
$("#Account").keyup(function () {
$.ajax({
type: "POST",
url: "AjaxCallExample.aspx/GetTradingTypeToSelect",
contentType: "application/json;charset=utf-8",
success: function (data) {
alert(data.d["1"]);
alert(data.d["2"]);
},
error: function (errordata) {
console.log(errordata);
}
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<input id="Account" type="text" />
</form>
</body>
How about exposing the dictionary in the view model:
public Dictionary<string, string> TradingTypesToSelect { get; set; }
And iterate over the dictionary inside the <script> block, creating a JavaScript associative array, like so:
<script>
var tradingTypesToSelect = {};
<% foreach (var tradingType in Model.TradingTypesToSelect) { %>
tradingTypesToSelect["<%= tradingType.Key %>"] = "<%= tradingType.Value %>";
<% } %>
</script>
At least this way you don't have to make another call (via AJAX) to retrieve additional data.
I believe you need to make a WebMethod to enable the server function to be called from the client side. Here is an example:
Calling ASP.Net WebMethod using jQuery AJAX
Here i am trying to display html content stored in database.When i try it to display in js it gives me "Uncaught ReferenceError: VAR_1 is not defined" in console.
Database:
<div id="dashboard-greeting" class="museo">
<div class="dashboard-greeting-instructions">
<span>Track Progress</span>
<div class="dashboard-greeting-counter round">
<div class="dashboard-counter-label">Courses Completed</div>
<div class="dashboard-counter-value">VAR_1</div>
</div>
<div class="dashboard-greeting-counter round">
<div class="dashboard-counter-label">Courses Needed</div>
<div id="subNeeded" class="dashboard-counter-value"></div>
<script>
var subNeedVar = VAR_2 - VAR_1;
$("#subNeeded").html(subNeedVar);
</script>
</div>
</div>
</div>
.js
<div class="tool-button-container">
<input type="submit" name="View" value="LookUp" id="campaignSubmit" class="buOrange large" onClick="validateConfigValues('configKeyName');"/> </div>
function validateConfigValues(id1){
$.ajax({
type: 'POST',
url: '<%=request.getContextPath()%>/adminConfigTest',
data: ({configKeyName:configKeyName, clientId :clientId ,batchId : batchId, languageId : languageId}),
cache: false,
success: function(data) {
var deleteCachingBtn = $('<br><div id="deleteBtn"><Button id="deleteCaching" name="deleteCaching" class="buOrange large" onClick=deleteFromCaching(\'' + configKeyName + '\')> Remove from Cache </div>');
var displayStringAppData = "";
var obj = JSON.parse(data);
$.each(obj, function(index,value) {
displayStringAppData = displayStringAppData+"<br>"+value+"<br>";
alert("displayStringAppData"+displayStringAppData);
});
$("#dbModelWindow").html(displayStringAppData);
if(~data.indexOf("Config is not found in DB also.")) {
} else {
$("#dbModelWindow").append(deleteCachingBtn);
}
$('#dbModelWindow').modal({
"escClose": true,
"overlayClose": true,
"onShow": function() { $.modal.setContainerDimensions();},
});
},
error: function(xhr, textStatus, error){
alert("Error occured. Please try after some time.");
}
});
}
}
.java
#RequestMapping(value="/adminConfigTest", method= RequestMethod.POST)
#PreAuthorize("hasPermission(#adminConfigTest,'ADMIN_TEXT_CONFIG')")
#ResponseBody
public String getAdminConfigTestPost(HttpServletRequest request) throws Exception {
String configKeyName = request.getParameter("configKeyName");
String clientId = request.getParameter("clientId");
String batchId = request.getParameter("batchId");
String language = request.getParameter("languageId");
List<String> arrList = new ArrayList<String>();
try{
Number languageId = null;
if(StringUtils.isBlank(language)){
languageId = RCConstants.ENGLISH_LANGUAGE_ID;
} else {
languageId = Long.parseLong(language);
}
if(StringUtils.isBlank(clientId)){
configManager.getConfigValue(configKeyName, null, "", false, true, languageId, arrList);
}
if(!StringUtils.isBlank(clientId) && StringUtils.isBlank(batchId)){
configManager.getConfigValue(configKeyName, Long.parseLong(clientId), "", false, true, languageId, arrList);
}
if(!StringUtils.isBlank(batchId)){
configManager.getConfigValue(configKeyName, Long.parseLong(batchId), languageId, arrList);
}
} catch (Exception e) {
logger.error(e ,e);
throw e;
}
return JSONSerializer.toJSON(arrList).toString();
}
public String getConfigValue(String configKey, Number batchId, Number languageId, List<String> arrList)throws Exception{
if(arrList != null){
arrList.add("Get config value for : "+ configKey);
arrList.add("batch Id : "+ batchId);
arrList.add("Language : "+ StringUtils.getLanguageCode(languageId));
}
try{
String configKeyValue = null;
String localConfigKeyWithBatchId = batchId+"-"+configKey+"-"+StringUtils.getLanguageCode(languageId);
String queryString = "from Config as model where model.configKeyName = ? and model.batchMetaDataId = ? and model.languageId = ? and model.isDeleted = 0" ;
List<Config> configList = getHibernateTemplate().find(queryString, configKey , batchId ,languageId);
if(!configList.isEmpty()) {
for (Config config : configList) {
configKeyValue = config.getConfigKeyValue();
}
CacheUtil.put(RCConstants.LOCAL_CACHE_WITH_BATCH,localConfigKeyWithBatchId, configKeyValue);
logger.debug("Returning value from db : "+configKey+" - "+configKeyValue);
if(arrList != null){
arrList.add("Db: returning batch and language specific value : " + configKeyValue );
}
}
return configKeyValue;
} catch (RuntimeException re) {
log.error(re, re);
throw re;
}
}
CacheUtil.java
public static Cache localEhCache = null;
public static Cache localEhCacheWithBatchId = null;
public static void put(int cacheNumber, Object key, Object value) {
if (cacheNumber == RCConstants.LOCAL_CACHE) {
localEhCache.put(new Element(key, value));
} else if (cacheNumber == RCConstants.LOCAL_CACHE_WITH_BATCH) {
localEhCacheWithBatchId.put(new Element(key, value));
}
}
But if i rewrite VAR_1 again by erasing VAR_1. It wont show this error.
I googled about this topic but didn't find any solution.
Please help me or suggest me what is going wrong here.
I am displaying data using auto-complete successfully, I am separating each data by using ',' delimiter.
Now I have a requirement to implement the auto-complete like Liferay Tags for the fields as shown below:
the below is my code :
<aui:script>
AUI().use('autocomplete-list', 'aui-base', 'aui-io-request', 'autocomplete-filters', 'autocomplete-highlighters',
function (A) {
A.io.request('<%=getEntities%>',{
dataType: 'json',
method: 'GET',
on: {
success: function(event, id, obj) {
try {
new A.AutoCompleteList({
allowBrowserAutocomplete: 'false',
activateFirstItem: 'true',
inputNode: '#<portlet:namespace />entitiesNames',
resultTextLocator: 'entityName',
render: 'true',
resultHighlighter: 'phraseMatch',
resultFilters:['phraseMatch'],
maxResults: 10,
queryDelimiter : ',',
source:this.get('responseData'),
autoLoad:false,
});
} catch(e) {
alert('not working sudheer: ' + e);
}
}
}
});
});
</aui:script>
Also posted in Liferay forum: https://www.liferay.com/community/forums/-/message_boards/message/47095147
In jsp page:
<portlet:resourceURL var="resourceURL"></portlet:resourceURL>
<aui:layout>
<aui:column columnWidth="20" cssClass="lableAlignMent">
<label class="nameLable">Role names</label>
</aui:column>
<aui:column columnWidth="65" cssClass="auto-fields-text-field">
<aui:input name="ListOfRoles" id="ListOfRoles" label="" type="hidden"/>
<aui:input name="ListOfRolesNames" id="ListOfRolesNames" label="" type="hidden"/>
<div id="<portlet:namespace/>rolesDiv" style="">
<aui:input name="roleNames" id="roleNames" title="Enter role names" placeholder="Role name"/>
</div>
</aui:column>
</aui:layout>
<aui:script>
var flag = true ;
var rolesBoxList;
AUI().ready('aui-textboxlist-deprecated', function(A) {
try{
var roles = selectRoles();
rolesBoxList = new A.TextboxList({
contentBox: '#<portlet:namespace />rolesDiv',
input:'#<portlet:namespace />roleNames',
dataSource: roles,
matchKey: 'name',
schema: {
resultFields: ['key', 'name']
},
queryMatchContains:true
}).render();
}catch(e){
//alert('roles'+e);
}
function selectRoles(){
var jsonArray = [];
try{
var url = '<%=resourceURL%>';
jQuery.ajax({
type: 'POST',
url:'<%=resourceURL%>',
data: {
<portlet:namespace />cmd:'roles',
},
dataType:'json',
method:'post',
success: function(msg) {
try{
var jsonArrayTemp=msg.objJsonArray;
for(var i=0;i < jsonArrayTemp.length ;i++ ){
jsonArray.push([jsonArrayTemp[i][0],jsonArrayTemp[i][1]]);
}
}catch(exception){
alert(exception);
}
}
});
}catch(exception){
//alert(exception);
}
return jsonArray ;
}
</aui:script>
In Controller serveResource() method:
Role roleObj=null;
if (cmd.equals("roles")) {
JSONObject objJsonObject = JSONFactoryUtil.createJSONObject();
JSONArray objJsonArray = JSONFactoryUtil.createJSONArray();
System.out.println("IN serve resource roles...");
ThemeDisplay themeDisplay = (ThemeDisplay) resourceRequest
.getAttribute(WebKeys.THEME_DISPLAY);
List orgTypeRoleCategoriesList = null;
try {
orgTypeRoleCategoriesList = AttributeLocalServiceUtil
.getOrganizationTypeRoleCategories(themeDisplay
.getLayout().getGroup().getOrganizationId());
} catch (Exception e) {
System.out.println("Exception raised while getting org roles:"
+ e.getMessage());
}
Iterator orgTypeRoleCategoriesObjList = orgTypeRoleCategoriesList
.iterator();
while (orgTypeRoleCategoriesObjList.hasNext()) {
Object[] objectArray = (Object[]) orgTypeRoleCategoriesObjList
.next();
JSONArray childJsonArray = JSONFactoryUtil.createJSONArray();
try {
roleObj=RoleLocalServiceUtil.getRole(Long.valueOf((String) objectArray[0]));
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (PortalException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SystemException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
childJsonArray.put(roleObj.getRoleId());
childJsonArray.put(roleObj.getTitle(themeDisplay.getLocale()));
objJsonArray.put(childJsonArray);
}
objJsonObject.put("objJsonArray", objJsonArray);
System.out.println("objJsonObject:...." + objJsonObject);
resourceResponse.getWriter().print(objJsonObject.toString());
}
i have a controller in extjs application, from where i have to call a servlet. But i am unable to call that servlet from controller here is my controller code .....
when i am running the application always failure part is showing "server-side failure with status code" this is the problem:
Ext.define('Gamma.controller.ControlFile', {
extend : 'Ext.app.Controller',
//define the stores
stores : ['BarColumn',
'RadarView',
'VoiceCallStore',
'SMSCallStore',
'MMSCallStore',
'GPRSUsageStore'],
//define the models
models : ['BarCol',
'radar',
'VoiceCallModel',
'SMSCallModel',
'MMSCallModel',
'GPRSUsageModel'],
//define the views
views : ['BarColumnChart',
'LineChart',
'RadarChart',
'VoicePie',
'SMSPie',
'MMSPie',
'GPRSPie'],
initializedEvents: false,
init: function() {
this.control({
'#barColumnChart': {
afterlayout: this.afterChartLayout
}
});
},
afterChartLayout: function(){
var me=this;
if(this.initializedEvents==true) return;
this.initializedEvents=true;
Ext.getCmp('barColumnChart').series.items[0].on('itemmousedown',function(obj){
// alert(obj.storeItem.data['source']+ ' &' + obj.storeItem.data['count']);
var barData=obj.storeItem.data['source']+ ' &' + obj.storeItem.data['count'];
me.dataBaseCall(obj.storeItem.data['source'],obj.storeItem.data['count']);
});
},
dataBaseCall: function(source,count){
//alert(barData);
Ext.Ajax.request({
url: "CallRatiosAnalysis",
success: function(response, opts){
//do what you want with the response here
console.log("hiiiiiiiiiiii");
},
failure: function(response, opts) {
alert("server-side failure with status code " + response.status);
},
params: {
source: source,
count: count
}
});
}
});
and this is my Servlet:
public class CallRatiosAnalysis extends HttpServlet {
public CallRatiosAnalysis() {
super();
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String start = request.getParameter("start");
String limit = request.getParameter("limit");
PrintWriter out = response.getWriter();
response.setContentType("text/html");
ArrayList<IndCallType> ratios = new ArrayList<IndCallType>();
ratios.add(new IndCallType("Voice", "40"));
ratios.add(new IndCallType("SMS", "30"));
ratios.add(new IndCallType("MMS", "5"));
ratios.add(new IndCallType("GPRS", "20"));
ratios.add(new IndCallType("Others", "5"));
Gson gson = new Gson();
JsonArray arrayObj = new JsonArray();
for (int i = 0; i < ratios.size(); i++) {
IndCallType count = ratios.get(i);
JsonElement linObj = gson.toJsonTree(count);
arrayObj.add(linObj);
}
JsonObject myObj = new JsonObject();
myObj.addProperty("success", true);
myObj.add("allCalls", arrayObj);
myObj.addProperty("allCallsRatio", ratios.size());
out.println(myObj.toString());
out.close();
}
}
This is the servlet where I have some dummy data and made json object to that data