How to pass selected value as extra parameter to ajax call - javascript

my coding part
$("#demo-input").tokenInput("data/autosuggest-search-city.php",
{
searchDelay: 2000,
minChars: 3,
tokenLimit: 10
});
I want to send the selected values as extra parameter to "data/autosuggest-search-city.php".
For example,
Initially I search and select one value from list
then again searching, this time I want to send the 1st selected value to server.
How to do this?

TokenInput plugin doesn't support that natively.
You can however make a simple workaround to update "AJAX url" whenever a token is added or removed from selection.
Use onAdd and onDelete callbacks to trigger "AJAX url" changes;
Get selected tokens using selector.tokenInput("get") method;
Set the new "AJAX url" by updating .data("settings").url of the element;
// cache the original url:
var token_url = "data/autosuggest-search-city.php";
$("#demo-input").tokenInput(token_url, {
searchDelay : 2000,
minChars : 3,
tokenLimit : 10,
onAdd : function(){
urlChange.call(this);
},
onDelete : function(){
urlChange.call(this);
}
});
function urlChange(){
var tokens = '', token_list = $(this).tokenInput("get");
// proceed if any token/s are selected:
if(token_list.length){
// loop through the selected tokens (if more than one is selected)
$.each(token_list, function(i, token){
// use token "id" (or "name" if you wish) and separate them with comma:
tokens += token.id + ',';
});
// update url:
$(this).data("settings").url = token_url + '?selected_tokens='+tokens.replace(/,+$/,'');
}else{
// leave original url if no tokens are selected:
$(this).data("settings").url = token_url;
}
};

Related

NetSuite is entirely new to me and I'm trying to create a suitelet that needs to reflect my active roles. How shall I execute it in codes?

I know that there already is a 'View My Roles' under my account but I just need that page to reflect on a suitelet.
You will want to use the Suitelet Script Type, and methods available in the N/runtime Module (to get current user and role) and N/ui/serverWidget Module (to create the custom page). You can use methods in either the N/record Module or N/search Module (to gather user role data).
Here's a good start to how to outline your script. Once deployed as a Suitelet you will see a url provided. This will be the url to use to trigger the script. I do not know of a way to make the link attached to a Custom Center Tab, but minimally you can have users save the link to their NetSuite shortcuts, or browser shortcuts.
/**
* #NApiVersion 2.x
* #NScriptType Suitelet
*/
define(['N/ui/serverWidget', 'N/runtime', 'N/record'], function(serverWidget, runtime, record) {
function onRequest(context){
if(context.request.method === 'GET'){ //GET is the request method when clicking on the url, POST or ELSE logic can be entered if you want to add for example a "submit button"
//create list w/2 columnms to display results in
var list = serverWidget.createList({
title: 'Available User Roles'
});
list.style = serverWidget.ListStyle.REPORT;
list.addColumn({
id: 'column1',
type: serverWidget.FieldType.TEXT,
label: 'Active Role?',
align: serverWidget.LayoutJustification.LEFT
});
list.addColumn({
id: 'column2',
type: serverWidget.FieldType.TEXT,
label: 'Role Name',
align: serverWidget.LayoutJustification.LEFT
});
//get current user role
var curUser = runtime.getCurrentUser(); //returns User (likely Employee) internal id
var curUserRoleId = curUserRole.role; //returns current role internal id
//empty array to keep all available roles
var availRoles = new Array();
//get all available roles using search or record module
//push each result to the array
availRoles.push(XXX);
//use ids to identify which result found above is the current role
var curRolePosition = availRoles.indexOf(curUserRoleId);
//add data to the list using addRow or addRows
//can also use a for loop for each result found when getting all available roles using search or record module
list.addRow({
row : { columnid1 : 'value1', columnid2 : 'value2' }
});
list.addRows({
rows : [{columnid1 : 'value1', columnid2 : 'value2'},
{columnid1 : 'value2', columnid2 : 'value3'}]
});
//display list to the user
context.response.writePage(list);
} else { //code that is exectuted i.e. after user presses "Submit button" (if created above in the GET area)
}
}
return {
onRequest: onRequest
}
});

How can ajax based Select2 pre-population be formatted?

We've found several examples of pre-populating selected option for Select2, however none of them we could find deal with formatted list and selection options. We have a JS fiddle at https://jsfiddle.net/gpsx62de/26/ that illustrates the issue. In that fiddle, you can type and L or whatever into the select search and the data is returned, the list is formatted, and if you select something, the selection is formatted.
However if you click the button in that JS Fiddle which is intended to simulate pre-population per https://select2.org/programmatic-control/add-select-clear-items#preselecting-options-in-an-remotely-sourced-ajax-select2 the data is returned (you can uncomment the console.log to see it), but the formatted selection shows undefined for the intended values. Does anyone know of a way to get the formatted values for pre-populated data to display correctly?
// Set up the Select2 control
$('#mySelect2').select2({
ajax: {
url: '/api/students'
}
});
// Fetch the preselected item, and add to the control
var studentSelect = $('#mySelect2');
$.ajax({
type: 'GET',
url: '/api/students/s/' + studentId
}).then(function (data) {
// create the option and append to Select2
var option = new Option(data.full_name, data.id, true, true); //**** DOES IT MATTER WHAT IS PASSED HERE BECAUSE WE ARE NOT DISPLAY THE OPTION TEXT?? ***
studentSelect.append(option).trigger('change');
// manually trigger the `select2:select` event
studentSelect.trigger({
type: 'select2:select',
params: {
data: data //**** THIS DOES NOT SEEM TO SUPPORT FORMATTED SELECTIONS, SO HOW CAN THIS BE DONE? ***
}
});
});
The problem is in format_selection function. The format of the object it receives depends on how it was created. When you use new Option(text, value) it receives only the properties of this Option object, not your original object containing all user info.
A workaround is to check of either possible values in the fuction:
function format_selection(obj) {
let name = obj.name || obj.element.text;
let email = obj.email || obj.element.email;
return $(`<div><b>${name}</b></div><div>(${email})</div>`);
}
For this to work you should append the de property on you Option object:
var option = new Option(data.name, data.id, true, true);
option.email = data.email;
$('#sel').append(option).trigger('change');
The problem, in https://jsfiddle.net/gpsx62de/26/ is with the
function format_selection(obj) {
// Just add this to see the obj
console.log(obj);
return $(`<div><b>${obj.text}</b></div><div>(${obj.id})</div>`);
}
The obj object just contains the Option class data, so:
id: "1",
selected: true,
text: "Leanne Graham",
title: ""
So you have to find a way to pass "data.email" to the "format_selection" method
EDIT
This could be a solution
$('#btn').on('click', function() {
$.ajax({
type: 'GET',
url: 'https://jsonplaceholder.typicode.com/users/1'
})
.then(function(data) {
console.log(data)
// create the option and append to Select2
$('#sel').append($('<option />') // Create new <option> element
.val(data.id) // Set value
.text(data.name) // Set textContent
.prop('selected', true)
.attr('data-name', data.name) // Don't know why the .data(key, value) isn't working...
.attr('data-email', data.email))
.trigger('change');
}); //then
}); //click
And
function format_selection(obj) {
return $(`<div><b>${obj.element.dataset.name}</b></div><div>(${obj.element.dataset.email})</div>`);
}
This is the fiddle https://jsfiddle.net/947jngtu/

Liferay Alloy UI - Clearing cache of dependent AutoCompleteList

I need to have two dependent AutoCompleteList in my Liferay portlet page. When I select some value from first AutoCompleteList then based on it's selected value I need to change the second AutoCompleteList source data. Based on information available, I have done coding and it is working fine except one issue.
When I select item in first AutoCompleteList then second AutoCompleteList gets populated with certain values based on my first list's selected item. Then if I change my selection again in first list, second AutoCompleteList gets updated with new possible values. But it appends the new possible values in the existing list or can say keep caching of data from both cases. But I need to show only possible values in list based on current selection of first list. For example, for selected value 1 in first list, if initially it was showing [A, B] in second list, after changing selection in first list from 1 to 2, it is showing [[A,B]+[C,D]].
Below here is part of that code. I tried setting "enableCache: 'false' " in second AutoComepleteList but not working.
<aui:script>
AUI().use('autocomplete-list','aui-base','aui-io-request','autocomplete-filters','autocomplete-highlighters',
function (A)
{
A.io.request('<%=getUrl %>',{
dataType: 'json',
method: 'GET',
on: {
success: function() {
new A.AutoCompleteList(
{
allowBrowserAutocomplete: 'false',
activateFirstItem: 'true',
inputNode: '#<portlet:namespace />name',
resultTextLocator: 'name',
render: 'true',
resultHighlighter: 'phraseMatch',
resultFilters:['phraseMatch'],
source:this.get('responseData'),
on: {
select: function(event) {
var result = event.result.raw;
A.one('#<portlet:namespace/>pk').val(result.id)
}
},
})
}}
});
});
</aui:script>
<aui:input id="pk" name="pk" label="Primary Id"
onChange='<%= renderResponse.getNamespace() + "fetchDisplayValues();"%
/>
Liferay.provide(
window,
'<portlet:namespace />fetchDisplayValues',
function() {
var A = AUI();
var pk = A.one("#<portlet:namespace/>pk");
var id = pk.get("value");
var url = '<%=getValues %>';
url = url+"&<portlet:namespace/>id="+id;
var datasource = new A.io.request(url,{
dataType: 'json',
method: 'GET',
on: {
success: function(){
var data = this.get('responseData');
new A.AutoCompleteList(
{
allowBrowserAutocomplete: 'false',
enableCache: 'false',
activateFirstItem: 'true',
inputNode: '#<portlet:namespace />displayName',
resultTextLocator: 'name',
render: 'true',
resultHighlighter: 'phraseMatch',
resultFilters:['phraseMatch'],
source:this.get('responseData'),
on: {
select: function(event) {
var result = event.result.raw;
A.one('#<portlet:namespace/>displayId').val(result.id);
}
},
})
}
}
});
})
</aui:script>
Please help me to resolve this issue. Thanks in advance.

Meteor easy search and iron-router

I'm using this easy serach for my project https://github.com/matteodem/meteor-easy-search
my search Index
EasySearch.createSearchIndex('searchIndex', {
'collection' : blog,
'field' : ['title', 'tags'],
'limit' : 20,
"use":"mongo-db",
'query' : function (searchString) {
// Default query that will be used for searching
var query = EasySearch.getSearcher(this.use).defaultQuery(this, searchString);
return query;
}
});
and now I have search box and when User enters something and click on enter I want to route to search page
this.route("search",{
path:'/search/:slug',
waitOn:function(){
//here I want the search data to be sent to search page
var query=this.params.slug;
EasySearch.search('searchIndex', query, function (err, data) {
console.log(data);
});
},
data:function(){
}
});
In this router I want the searchIndex data to be sent to search page, how to do this
my click event
'submit .search':function(e){
e.preventDefault();
var quer=$("#query").val();
// Router.go('search');
}
UPDATE
My main question is in the router waiton function how we get the data in callback and send it to the search page?
In your click event handler, you have commented out the line: Router.go('search').
If you write
Router.go('search', {slug: quer})
That would route you to the search page with the query data collected from the page, if that is what you want.

adding element with duplicate id 'FileULoader' FileUploader

createContent : function(oController) {
var oFileUploader = new sap.ui.commons.FileUploader({
id: "FileULoader",
//uploadUrl : "UploadFileServelet", // URL to submit the form to
name: "simpleUploader", // name of the input type=file element within the form
// uploadOnChange: true, // immediately upload the file after selection
buttonOnly: false,
buttonText: "Upload"
}).addStyleClass("downloadBtn");
oFileUploader.attachUploadComplete(oController.doFileLoadComplete);
//var uploadBtn=new sap.ui.commons.buttons{this.creatId("upLoadFile"),}
var oMatrix = new sap.ui.commons.layout.MatrixLayout({
layoutFixed : true,
width : '400px',
columns : 1 });
var text = new sap.ui.commons.TextView({text:"Confirm that the data will be wiped out once you upload new data file."});
oMatrix.createRow(oFileUploader);
oMatrix.createRow(text);
var oDialog = new sap.ui.commons.Dialog({
title:"FileUpload",
resizable:false,
modal:true,
showCloseButton:true,
contentBorderDesign:"Box",
content:[
oMatrix
],
buttons:[
new sap.ui.commons.Button({text:"Confirm", tooltip:"Confirm",press:function(e){oController.doFileUpload();oDialog.close();}}),
new sap.ui.commons.Button({text:"Cancel", tooltip:"Cancle",press:function(e){oDialog.close();}}),
]
});
return oDialog;
i used in two views . when i call the fileUploader the error turns out。
i have to use the id to identify the fileloder controller. to get the input file information .
update:
_uploadCourse:function(){
if (!this.dialogUploadFile) {
this.dialogUploadFile = sap.ui.jsfragment("courseUP",
"adminView.dialogUploadFile", this);
}
this.dialogUploadFile.open();
},
_uploadCourse : function() {
if (!this.dialogUploadFile) {
this.dialogUploadFile = sap.ui.jsfragment("certiUploadFile",
"adminView.dialogUploadFile", this);
}
this.dialogUploadFile.open();
},
this is how i use the fragment. but is still go wrong with thew same error;
#Allen Zhang
You mentioned you used the code in two views. You can't create a dialog twice with the same id of Fileupload control. Use different id for different views.
Updated:
Define id for your fragment usage:
<core:Fragment id="myFrag" fragmentName='my.frag' type='JS' />
Define fileupload id by calling createId:
var oFileUploader = new sap.ui.commons.FileUploader({
id: this.createId("FileULoader"),
//uploadUrl : "UploadFileServelet", // URL to submit the form to
name: "simpleUploader", // name of the input type=file element within the form
// uploadOnChange: true, // immediately upload the file after selection
buttonOnly: false,
buttonText: "Upload"
}).addStyleClass("downloadBtn");
Also see my answers about fragment usage and get control inside fragment.
Is an option that you do not use id for the file uploader control, and do it like this?
createContent : function(oController) {
this.oFileUploader = new sap.ui.commons.FileUploader({
To access it, you do
view.oFileUploader
where view is the javascript handle of one of your two views.
-D

Categories