How to add items to selectize field - javascript

Could you please help me cause I'm stuck :/ I have a snippet where I want to add data from API to my selectize field. I prepared this selectize field manually in the system cause I have to. Here I just want to pass this data. Here is my snippet:
function getCarriersData() {
const queryType = "GET";
const funcName = "getcarriersdata";
const queryUrl = globalDataObject.appRootPath + "api/extension/" + funcName;
$.ajax({
url: queryUrl,
type: queryType,
success: function(result) {
const przewoznik = $('span[data-inputattrname="KZ_Kurier_DP_przewoznik"]').find('select')[0].selectize;
if (Object.keys(przewoznik.options).length == 0) {
console.log('That part works')
$.each(JSON.parse(result), function(i, item) {
przewoznik.addOption({ value: item.Name, text: item.Name });
przewoznik.setValue(item.Name, false)
});
}
}
});
}
I receive data from API and I parse it to multiple objects (JSON.parse), but still doesn't work.

Related

jQuery autocomplete ajax not working for autocorrection when wrong input is given

I'm trying to make a project similar to Google's search bar using Flask, Elasticsearch and jQuery that will automatically suggest based on input given and also automatically give correct suggestions when a wrong input is given. I've had success with the autosuggestion with correct spellings but when giving a wrong input, the correct suggestion data from Elasticsearch comes up in browser console but doesn't appear in the autocomplete drop-down. I inserted data into Elasticsearch using PySpark. I think the problem is related to the JS file but don't know if it's my JS file or the jquery-ui file. What am I doing wrong?
JS:
$(document).ready(function () {
const $source = document.querySelector('#source');
const $result = document.querySelector('#result');
const typeHandler = function (e) {
$result.innerHTML = e.target.value;
console.log(e.target.value);
$.ajax({
url: "/ajax_call",
type: 'POST',
dataType: 'json',
data: { 'data': e.target.value },
success: function (html) {
var data = html.aggregations.auto.buckets
var bucket = []
$.each(data, (index, value) => {
bucket.push(value.key)
});
console.log(bucket)
$("#source").autocomplete({
source: bucket
});
}
});
}
$source.addEventListener('input', typeHandler)
});
Correct Input:
Incorrect Input:
Correct data for Incorrect Input
Consider the following example.
$(function() {
const $source = $('#source');
const $result = $('#result');
$source.autocomplete({
source: function(request, response) {
$.ajax({
url: "/ajax_call",
type: 'POST',
dataType: 'json',
data: {
'data': request.term
},
success: function(html) {
var data = html.aggregations.auto.buckets;
var bucket = [];
$.each(data, (index, value) => {
bucket.push(value.key);
});
console.log(bucket);
response(bucket);
}
});
}
});
});
See More:
https://jqueryui.com/autocomplete/#remote-jsonp
https://api.jqueryui.com/autocomplete/#option-source

How do i use a custom button to send to the JQGrid's editurl?

I have the below custom button added to my navigation pager, but i want it to look at what i multi selected and send it to the JQGrid's editurl for processing which is a ASHX.CS page
But i can't make sense of the documentation when it comes to custom button
I can get it call a local function with onClickButton: customButtonClicked but it doesn't send the data like the EDIT button does
In the end what i want to do it select multiple rows and press a button on the navbar and approve all the selected records
// add first custom button
$('#jQGrid').navButtonAdd('#jQGridPager',
{
buttonicon: "ui-icon-mail-closed",
title: "Send Mail",
caption: "Send Mail",
position: "last",
editData: {
WrkId: function () {
var sel_id = $('#jQGrid').jqGrid('getGridParam', 'selarrrow');
var value = "";
for (var a = 0; a < sel_id.length; a++) {
value = value + $('#jQGrid').jqGrid('getCell', sel_id[a], 'wrkid') + ',';
}
return value;
},
CurrentUser: function () {
return '<% =System.Web.HttpContext.Current.User.Identity.Name %>';
}
},
afterSubmit: function (response, postdata) {
if (response.responseText == "") {
$("#jQGrid").trigger("reloadGrid", [{ current: true }]);
return [false, response.responseText]
}
else {
$(this).jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid')
return [true, response.responseText]
}
}
}
);
using a few different words (how to manually post data to server json) i was able to find a snippet of an ajax code that made more sense (i'm sure i came across this before but as someone who has no jquery experience i didn't recognize it)
but the below sends to the C# handler page the data in a JSON string that was processable, had to use dynamic to read it in but it worked, couldn't get it to not return an error even though there was no error, so i used the complete: instead of success: and then called the trigger to reload the JQGrid
Final Code:
$('#jQGrid').navButtonAdd('#jQGridPager',
{
buttonicon: "ui-icon-check",
title: "Approve all selected entries",
caption: "Approve",
position: "last",
onClickButton: function () {
var sel_id = $('#jQGrid').jqGrid('getGridParam', 'selarrrow');
var value = "";
for (var a = 0; a < sel_id.length; a++) {
value = value + $('#jQGrid').jqGrid('getCell', sel_id[a], 'wrkid') + ',';
};
$.ajax({
type: "POST",
url: "AdministrationHandler.ashx?oper=approve",
data: JSON.stringify({
WrkId: value,
CurrentUser: "<% =System.Web.HttpContext.Current.User.Identity.Name %>"
}),
dataType: "json",
contentType: "application/json; charsset=utf-8",
complete: function (xhr, x) {
if (xhr.responseText.toUpperCase().indexOf("SUCCESS") >= 0) {
alert('Success!\n' + xhr.responseText);
}
else {
alert('Failed!\n' + xhr.responseText + '\n' + x);
};
$("#jQGrid").jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid');
}
})
}
});
C# Code
try
{
String postData = new System.IO.StreamReader(context.Request.InputStream).ReadToEnd();
var data = JsonConvert.DeserializeObject<dynamic>(postData);
Approve(data.WrkId.ToString(), data.CurrentUser.ToString());
strResponse = "Employee records successfully approved";
}
catch
{
strResponse = "Employee records not approved";
}
context.Response.Write(strResponse);

select2 predefined rendered item with ajax

I can easily retrieve and format AJAX data to work with Select2, like this
function formatItem (item) {
if (!item.id) {
return item.text;
}
var _item = '<span class="' + item.deleted +'"><i class="fa fa-user"></i> ' + item.doctor + ', <small>' + item.sex + ' (' + item.user + ')</small></span>';
return $(_item);
}
var tabSelect = $('#t');
tabSelect.select2({
ajax: {
url: '../ajax/results.php',
data: function (params) {
return {
search: params.term,
page: params.page || 1
};
}
},
templateResult: formatItem,
templateSelection: formatItem
});
So far so good: <select> items are rendered correctly as HTML, with the nice Font-Awesome icon and the <small> tag.
User now selects an item and submits the (search) form. Of course I'd like to mark the current item as selected, and here comes the trouble.
Select2 docs have a way to predefine an AJAX retrieved item, but this works for simple text and not for rendered items with all the HTML bells and whistles
So, when adapting the provided example:
$.ajax({
type: 'GET',
url: '../ajax/results-selected.php', // url to retrieve a single item
data: {
iData: [here goes the ID for retrieving single item]
}
}).then(function (data) {
// create the option and append to Select2
var item = data.results[0];
console.log(item);
var option = new Option(item, item.id, true, true);
tabSelect.append(option).trigger('change');
// manually trigger the `select2:select` event
tabSelect.trigger({
type: 'select2:select',
params: {
data: data
}
});
});
I get the HTML rendered item, but with a series of undefined (please notice that console.log(item) returns the expected result: in other words, I have the fields but have no idea how to render them)
I tried lot of things, but none of them work, i.e.:
var option = new Option(formatItem(item), item.id, true, true);
I read around but could not find a valid solution working: please, any help?
I managed it to work by returning the whole HTML snippet in the JSON response (as text item)
// the JSON response
{
"results": [
{
"id": "1234",
"text": "<span class=\"\"><i class=\"fa fa-user\"></i> Doe John, <small>Mr. (Site Owner)</small></span>"
}
]
}
// the updated snippet
$.ajax({
type: 'GET',
url: '../ajax/results-selected.php', // url to retrieve a single item
data: {
iData: [here goes the ID for retrieving single item]
}
}).then(function (data) {
// create the option and append to Select2
var item = data.results[0];
console.log(item);
var option = new Option(item.text, item.id, true, true);
tabSelect.append(option).trigger('change');
// manually trigger the `select2:select` event
tabSelect.trigger({
type: 'select2:select',
params: {
data: data
}
});
});

POST with Ext.Ajax.request?

I am new to ExtJS and I am trying to implement a combo box and 'Save' button that will save the "boxStatus" for all of the records selected in my grid (there is a little checkbox column for selecting records, and a combo box for the status). I have tried with the following ajax call:
saveBulkBoxComments : function(){
var formObj = this.getPositionPanel().getForm();
var fieldValues = formObj.getFieldValues();
Ext.Ajax.request({
url: SAVE_BULK_BOX_COMMENTS_URL,
method: 'POST',
params: {
positionDate: this.parentRecordData.data.positionDate,
groupIds: this.parentRecordData.data.groupId,
boxStatus: fieldValues.boxStatus,
csrComment: fieldValues.csrComment
},
success : function(response) {
//how do I update box status for all records selected?
this.loadPositions();
},
scope: this
});
}
Here is the Java:
return getReturnValue(new Runnable() {
public void run() {
String groupIdList[] = groupIds.split(",");
String user = mercuryUserScreenNameGetter.getValue(request);
Date date = Utils.parseDate(positionDate, DATE_FORMAT);
Stream.of(groupIdList)
.forEach(groupId ->
positionsDataMediator.addBoxAnnotation(date,user, groupId, csrComment, boxStatus));
}
});
I am not really sure how to post all of the boxStatus for all of the records selected. Would I have to write a method that iterates over all of the records when I hit Save? That seems wrong...Thanks for the help.
After some fiddling, I got it working. The trick was to iterate over each groupID, for all of the selected records...this way I was able to update the boxStatus for each of those records at once:
saveBulkBoxComments : function(){
grid = this.getPositionPanel();
var store = grid.getStore();
formObj = this.getBoxCommentsFormPanel().getForm();
var fieldValues = formObj.getFieldValues();
var value='';
selectedRecords = grid.getSelectionModel().getSelection();
Ext.each(selectedRecords, function(item) {
value +=item.get('groupId') +',';
}
);
Ext.Ajax.request({
url: SAVE_BULK_BOX_COMMENTS_URL,
method: 'POST',
params: {
groupIds :value,
positionDate: this.parentRecordData.data.positionDate,
boxStatus: fieldValues.boxStatus,
csrComment: fieldValues.csrComment
},
success: function(result, action, response) {
var jsonData = Ext.decode(result.responseText);
var jsonRecords = jsonData.records;
Ext.getCmp('boxCommentsWindow').close();
this.loadPositions();
},
scope: this
});
}
});

Use JavaScript to get SharePoint task associated with item without using Related Items

I have a bit of an unusual environment, where the client does not want to support SharePoint components, and as such I have an O365 SharePoint site that I can only do things programmatically through workflows or JavaScript.
I have workflows that are starting tasks, except for some reason I occasionally get a task that does not get the "Related Items" populated. Because of this, my lookup to find the items with a task associated with them failed, because I was looking for the Related Item to be the ID I was working with. I can still follow from the list item, to the workflow, to the task. Is there another way, using something like WorkflowItemId, that I can associate the tasks to these items?
Here is some code I have to find the tasks by a item Id, it either deletes the tasks (when the list item is deleted), or populates taskId to display in a form, this is used in O365 SharePoint online. Give it the ID of the list item, and change the list title to your task list title. Let me know if any other questions.
$.fn.get_taskIds = function (param) {
var itemTitle, taskId, curID = param.ItemId, foundAction = param.action;
get_listData(appWebUrl + "/_api/web/lists/getbytitle('ExpirationTaskList')/items?$select=RelatedItems,Id,Title").done(
function (data) {
var itemJSON;
$.each(data.d.results, function (index, item) {
itemJSON = $.parseJSON(item.RelatedItems);
itemTitle = item.Title;
taskId = item.Id;
$(itemJSON).each(function (i, val) {
$.each(val, function (k, v) {
if (k == 'ItemId') {
if (v == curID) {
switch (foundAction) {
case 'view':
if (itemTitle == 'Warranty Expiration') { $('#WTaskId').val(taskId); $('#wTaskRadio').attr('disabled', false); }
if (itemTitle == 'Lease Expiration') { $('#LTaskId').val(taskId); $('#lTaskRadio').attr('disabled', false); }
break;
case 'delete':
delete_Task(taskId);
break;
}
}
}
})
})
});
}).fail(function (arg) {
$('#jsError').html('Fail in Async Query to Retrieve task data: <br />');
var jsonResp = $.parseJSON(arg.responseText);
$('#jsError').append(jsonResp.error.message.value);
});
}
function get_listData(aurl) {
var dfrd = $.Deferred(function (dfrd) {
$.ajax({
url: aurl,
type: "Get",
contentType: "application/json;odata=verbose",
headers: {
"Accept": "application/json;odata=verbose"
},
success: function (data) {
dfrd.resolve(data);
},
error: function (args) {
dfrd.reject(args);
}
});
});
return dfrd.promise();
}

Categories

Resources