How do I pass headers in an enyo.ajax call ?
enyo.kind({
name: "enyo.sample.AjaxSample",
kind: "FittableRows",
classes: "enyo-fit ajax-sample",
components: [
{kind: "FittableColumns", classes:"onyx-toolbar-inline", components: [
{content: "YQL: "},
{kind: "onyx.Input", name:"query", fit:true, value:'select * from weather.forecast where woeid in (select woeid from geo.places where text="san francisco, ca")'},
{kind: "onyx.Button", content:"Fetch", ontap:"fetch"}
]},
{kind: "FittableColumns", classes:"onyx-toolbar-inline", components: [
{content: "URL: "},
{kind: "onyx.Input", name:"baseUrl", fit:true, value:'http://query.yahooapis.com/v1/public/yql?format=json'}
]},
{kind: "onyx.TextArea", fit:true, classes:"ajax-sample-source"},
{name: "basicPopup", kind: "onyx.Popup", centered: true, floating: true, classes:"onyx-sample-popup", style: "padding: 10px;", content: "Popup..."}
],
fetch: function() {
var ajax = new enyo.Ajax({
url: this.$.baseUrl.getValue(),
headers: [{
"user-username" : "testuser",
"user-pwd" : "tester"
}]
});
// send parameters the remote service using the 'go()' method
ajax.go({
q: this.$.query.getValue()
});
// attach responders to the transaction object
ajax.response(this, "processResponse");
// handle error
ajax.error(this, "processError");
},
processResponse: function(inSender, inResponse) {
// do something with it
this.$.textArea.setValue(JSON.stringify(inResponse, null, 2));
},
processError: function(inSender, inResponse) {
var errorLog = "Error" + ": " + inResponse + "! " + (JSON.parse(inSender.xhrResponse.body)).error.description;
this.$.textArea.setValue(JSON.stringify(inSender.xhrResponse, null, 2));
this.$.basicPopup.setContent(errorLog);
this.$.basicPopup.show();
}
});
You're really close here. What you want to do is the following:
var ajax = new enyo.Ajax({
url: this.$.baseUrl.getValue(),
headers: {
"user-username" : "testuser",
"user-pwd" : "tester"
}
});
headers is an object, not an array.
Related
I'm developing a Slack bot using Glitch and Bolt for Javascript.
I'm opening a Model with two button (Approve and Reject), everything works up to where the user clicks on Approve and the app.action is reached but client is null and I need to send it to the next method...What can be missing?
This is the message I'm sending to a user after selecting everything in a dialog
async function sendSlackMessageToLead(requesterUsername, requesterSlackId, submittedValues, client, logger, leadUsername, leadId){
try {
await client.chat.postMessage({
channel: leadId,
text: "New PTO Request from " + requesterUsername,
blocks: [
{
type: "header",
text: {
type: "plain_text",
text: "You have requested a new PTO",
},
},
{
type: "section",
fields: [
{
type: "mrkdwn",
text:
"*Type:*\n" +
submittedValues.type_block.type.selected_option.text !=
null
? submittedValues.type_block.type.selected_option.text.text
: "N/A",
},
{
type: "mrkdwn",
text: "*Created by:*\n<#" + requesterUsername + ">",
},
],
},
{
type: "section",
fields: [
{
type: "mrkdwn",
text:
"*When:*\n" +
"From " +
submittedValues.startdate.datepicker_action_start_date
.selected_date +
" \nTo " +
submittedValues.enddate.datepicker_action_end_date
.selected_date,
},
],
},
{
type: "section",
fields: [
{
type: "mrkdwn",
text:
submittedValues.allDayBlock["checkboxes-action"]
.selected_options == ""
? "All Day? No"
: "All Day? Yes",
},
],
},
{
type: "section",
fields: [
{
type: "mrkdwn",
text:
"*Hours:*\n" +
submittedValues.starttime.timepicker_action_start_time
.selected_time +
" - " +
+submittedValues.endtime.timepicker_action_end_time
.selected_time,
},
{
type: "mrkdwn",
text: "*Remaining balance:*\n32.0 hours (4 days)",
},
],
},
{
type: "actions",
block_id: "approved_by_firstone_block",
elements: [
{
type: "button",
text: {
type: "plain_text",
emoji: true,
text: "Approve",
},
style: "primary",
value: JSON.stringify(submittedValues),
action_id: "approved_by_firstone_click"
},
{
type: "button",
text: {
type: "plain_text",
emoji: true,
text: "Deny",
},
style: "danger",
value: JSON.stringify(submittedValues),
action_id: "rejected_by_firstone_click"
},
],
},
],
});
} catch (error) {
logger.error("Error while sending message to lead: " + error);
}
}
Here clientSlack is undefined, the rest of the parameter have values in them
app.action({ action_id: 'approved_by_firstone_click', block_id: 'approved_by_firstone_block' }, async ({ body, clientSlack, ack, logger }) => {
// Acknowledge the action
await ack();
console.log ("approved_by_firstone_click");
console.log ("body: " + JSON.stringify(body));
console.log ("ack: " + ack);
console.log ("clientSlack: " + JSON.stringify(clientSlack));
console.log ("logger: " + JSON.stringify(logger));
var submittedValues = JSON.parse(body.actions[0].value);
await sendSlackMessageToNextPerson(body.user.username, submittedValues, clientSlack, logger, "name.surname", "SlackId");
});
Thanks in advance. Guillermo.
Checking the reference for the listener function, clientSlack isn't passed as an argument to the listener, but client is.
So changing clientSlack to client should work:
app.action({ action_id: 'approved_by_firstone_click', block_id: 'approved_by_firstone_block' }, async ({ body, client, ack, logger }) => {
// Acknowledge the action
await ack();
console.log ("approved_by_firstone_click");
console.log ("body: " + JSON.stringify(body));
console.log ("ack: " + ack);
console.log ("clientSlack: " + JSON.stringify(client));
console.log ("logger: " + JSON.stringify(logger));
var submittedValues = JSON.parse(body.actions[0].value);
await sendSlackMessageToNextPerson(body.user.username, submittedValues, client, logger, "name.surname", "SlackId");
});
Pay attention to the fact that your listener function receives an object with properties, so you need to keep their exact name while unpacking the object. It is possible to also assign the property value under a different name, like this:
async ({ body, client: clientSlack, ack, logger }) => {
console.log(clientSlack); // originally named `client`
//...
}
working for one id not for two
var kendoEditorFields = '#ApplicationGlobals.SELECTED_COMPANY_CODE' != '#CompanyCode.RICHMOND' ?
"#txArNcrLineDispositionsDisposition,#txArNcrLineDispositionsCorrectiveAction" : "#txArNcrLineDispositionsDisposition";
var kendoEditorFields = '#ApplicationGlobals.SELECTED_COMPANY_CODE' != '#CompanyCode.RICHMOND' ?
"#txArNcrLineDispositionsCorrectiveAction,#txArNcrLineDispositionsDisposition" : "#txArNcrLineDispositionsDisposition";
$(kendoEditorFields).kendoEditor({
encoded: false,
paste: function (e) {
if ((/^<img src="data:image/i).test(e.html)) {
e.html = "";
}
},
imageBrowser: {
transport: {
read: "ImageBrowser/Read",
destroy: { url: "ImageBrowser/Destroy", type: "POST" },
uploadUrl: "ImageBrowser/Upload",
thumbnailUrl: "ImageBrowser/Thumbnail",
imageUrl: baseUrl + $.cookie("IMAGEBROWSERFILEPATH") + "/{0}"
}
},
tools: [
"bold",
"italic",
"underline",
"strikethrough",
"justifyLeft",
"justifyCenter",
"justifyRight",
"justifyFull",
"insertUnorderedList",
"insertOrderedList",
"indent",
"outdent",
"createLink",
"unlink",
"insertImage",
"insertFile",
"subscript",
"superscript",
"tableWizard",
"createTable",
"addRowAbove",
"addRowBelow",
"addColumnLeft",
"addColumnRight",
"deleteRow",
"deleteColumn",
"viewHtml",
"formatting",
"cleanFormatting",
"fontName",
"fontSize",
"foreColor",
"backColor",
"print",
{
name: "fullscreen",
template: '<a class="toggle-button" onclick="toggleFullScreen()" title="#ResourceStrings.Text_Toggle_Screen"> <span class="k-icon k-i-maximize k-tool-icon" /></a>'
}
]
});
I need to send the start and end dates via ajax to the server to save them to the database. I am trying to do an ajax call after the unselect method by the ajax call does not fire. I am not sure what the problem is. Please help.
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: ''
},
defaultDate: '<?php echo date("Y-m-d") ?>',
defaultView: 'agendaWeek',
selectable: true,
selectHelper: true,
select: function(start, end) {
//var title = prompt('Event Title:');
var title = $("#gym_mbr_name").val();
var eventData;
if (title) {
eventData = { title: title, start: start, end: end };
var calendar_datetime = $('#calendar').fullCalendar('renderEvent', eventData, true); // stick? = true
}
$('#calendar').fullCalendar('unselect');
$.ajax({
url: '<?php echo BASE_URL; ?>ajax/add_membership_schedule.php',
type: 'POST',
data: { start: start, end: end },
beforeSend: function(){ },
complete: function(){ }
}).done(function(resp){
alert(resp);
});
},
editable: true,
eventLimit: true, // allow "more" link when too many events
events: []
});
When I try to alert the resp, it does not give any output, in fact the ajax call does not fire itself. Please help.
It seems to work for me.
Note that start and end are FCMoments (strange creatures derived from Moments) and you want to convert them to strings or something before using them in your ajax call.
Also, try using 'success' instead of 'done'.
See an example here: http://jsfiddle.net/3E8nk/507/
$("#calendar").fullCalendar({
header: {
left: "prev,next today",
center: "title",
right: "month,agendaWeek,agendaDay"
},
defaultDate: "2014-06-12",
editable: true,
selectable: true,
selectHelper: true,
select: function(a, b) {
alert("selected from: " + a.format() + ", to: " + b.format());
$("#calendar").fullCalendar("unselect");
$.ajax({
url: "http://www.google.com",
type: "GET",
data: {
q: "test"
},
dataType: "html",
success: function(a) {
alert("Data: " + a);
},
error: function(a, b) {
alert("Request: " + JSON.stringify(a));
}
});
},
unselect: function() {
alert("unseleted");
},
events: [ {
title: "All Day Event",
start: "2014-06-01"
}, {
title: "Long Event",
start: "2014-06-07",
end: "2014-06-10"
}, {
id: 999,
title: "Repeating Event",
start: "2014-06-09T16:00:00"
}, {
id: 999,
title: "Repeating Event",
start: "2014-06-16T16:00:00"
}, {
title: "Meeting",
start: "2014-06-12T10:30:00",
end: "2014-06-12T12:30:00"
}, {
title: "Lunch",
start: "2014-06-12T12:00:00"
}, {
title: "Birthday Party",
start: "2014-06-13T07:00:00"
}, {
title: "Click for Google",
url: "http://google.com/",
start: "2014-06-28"
} ]
});
If looking at that doesn't help then try posting what the php produces.
In the latest version of FullCalendar, We have to catch the MOMENT DATE an format on yyyy-mm-dd or same. So, for me this code is working:
start = $.fullCalendar.moment(start).format("YYYY-MM-DD HH:mm:ss");
end = $.fullCalendar.moment(end).format("YYYY-MM-DD HH:mm:ss");
My CKEDITOR plugin needs to create <select size="15"><option ...></select>, but the size attribute is not directly supported by the creation mechanism. I have tried various ways of adding the size attribute after creation, but so far no joy. Here is what I have; the select is created but it does not get the size attribute.
CKEDITOR.dialog.add('macrosDialog', function(editor) {
return {
// Basic properties of the dialog window: title, minimum size.
title: 'Cadenza Macros',
resizable: CKEDITOR.DIALOG_RESIZE_BOTH,
minWidth: 400,
minHeight: 200,
// Dialog window contents definition.
contents: [
{
// Definition of the Basic Settings dialog tab (page).
id: 'tab-basic',
label: 'Basic Settings',
// The tab contents.
elements: [
{
type: 'select',
id: 'groups',
name: 'groups',
label: 'Groups',
style: "height: 300",
items: [ [ 'Core Scala' ], [ 'Create Courses with Micronautics Cadenza' ], [ 'Java / Scala Interoperability' ], [ 'Play Framework' ] ],
'default': 'Play Framework'
},
{
// Text input field for the macro title (explanation).
type: 'text',
id: 'macroComment',
label: 'Comment',
validate: CKEDITOR.dialog.validate.notEmpty("Explanation field cannot be empty")
}
]
}
],
onLoad: function(e) {
var groups = editor.document.getElement("groups");
groups.setAttribute("size", 15);
//$("#groups").setAttr("size", 15);
},
onChange: function(e) {
alert('Group: ' + this.getValue());
},
// This method is invoked once a user clicks the OK button, confirming the dialog.
onOk: function() {
// The context of this function is the dialog object itself.
// http://docs.ckeditor.com/#!/api/CKEDITOR.dialog
var dialog = this;
// Creates a new <abbr> element.
var abbr = editor.document.createElement('abbr');
// Set element attribute and text, by getting the defined field values.
abbr.setAttribute('title', dialog.getValueOf('tab-basic', 'title'));
abbr.setText(dialog.getValueOf('tab-basic', 'abbr'));
// Finally, inserts the element at the editor caret position.
editor.insertElement(abbr);
}
};
});
I used the html element to insert whatever I wanted:
contents: [
{
id: 'macrosDialog',
label: 'Basic Settings',
// The tab contents.
elements: [
{
type: 'hbox',
id: 'lists',
//style: "vertical-align: top",
widths: [ '25%', '25%', '25%', '25%' ],
children: [
{
type: 'html',
id: 'groups',
name: 'groups',
html: '<select size="15"></select>'
},{
type: 'html',
id: 'courses',
name: 'courses',
html: '<select size="15"></select>'
},{
type: 'html',
id: 'sections',
name: 'sections',
html: '<select size="15"></select>'
},{
type: 'html',
id: 'lectures',
name: 'lectures',
html: '<select size="15"></select>'
},
],
onLoad: function(data) {
var dialog = this.getDialog();
var groups = dialog.getContentElement('macrosDialog', 'lists', 'groups');
console.log(groups);
var courses = dialog.getContentElement('macrosDialog', 'lists', 'courses');
console.log(courses);
var sections = dialog.getContentElement('macrosDialog', 'lists', 'sections');
console.log(sections);
var lectures = dialog.getContentElement('macrosDialog', 'lists', 'lectures');
console.log(lectures);
}
}
]
}
]
My main view is
Ext.define("casta.view.Main", {
extend: 'Ext.tab.Panel',
apitoken:'NULL',
callbackdata:'NULL',
requires: [
'Ext.TitleBar',
'Ext.Video',
'casta.view.Intro'
],
config: {
tabBarPosition: 'top',
items: [
//intro.js actually need json rendering
{ title:'Intro',
xclass: 'casta.view.Intro' ,
iconCls:'user',
renderTo: document.body,
}
]
}
});
I have called json from external url like below in intro.js
Ext.define('User', {
extend: 'Ext.data.Model',
fields: ['id', 'username']
})
Ext.define('casta.view.Intro', {
extend: 'Ext.tab.Panel',
alias: 'widget.Intro',
requires: ['Ext.data.Store'],
itemTpl: '{id} - {username}',
initComponent: function(){
this.store = new Ext.data.Store({
autoLoad: true,
model: 'User',
proxy: {
type: 'ajax',
url: 'http://localhost:8000/api/casta/user/?format=json',
reader: {
type: 'json',
root: 'objects'
}
}
});
this.callParent();
}
});
Ext.onReady(function(){
Ext.create('Ext.tab.Panel', {
width: 400,
height: 400,
renderTo: document.body,
items: [{
title: 'My View',
xtype: 'Intro'
}]
})
});
The json i got from response is as follows
{"meta": {"limit": 20, "next": null, "offset": 0, "previous": null, "total_count": 2}, "objects": [{"date_joined": "2012-05-18T15:44:54", "first_name": "", "id": 1, "last_login": "2012-05-18T15:44:54", "last_name": "", "resource_uri": "/api/casta/user/1/", "username": "admin"}, {"date_joined": "2012-05-21T12:05:00", "first_name": "", "id": 29, "last_login": "2012-05-21T12:05:00", "last_name": "", "resource_uri": "/api/casta/user/29/", "username": "sumit"}]}
Whenever i keep static string , the template is updated , else the template is not updated . can anybody tell me what i have to do .. also is there any function like onload instead of initcomponent as i want to call ajax only when this panel is called
You're going about this totally the wrong way. Instead of trying to fix up your example, look at this:
Ext.define('User', {
extend: 'Ext.data.Model',
fields: ['id', 'username']
})
Ext.define('MyView', {
extend: 'Ext.view.View',
alias: 'widget.myview',
requires: ['Ext.data.Store'],
itemTpl: '{id} - {username}',
initComponent: function(){
this.store = new Ext.data.Store({
autoLoad: true,
model: 'User',
proxy: {
type: 'ajax',
url: 'data.json',
reader: {
type: 'json',
root: 'objects'
}
}
});
this.callParent();
}
});
Ext.onReady(function(){
Ext.create('Ext.tab.Panel', {
width: 400,
height: 400,
renderTo: document.body,
items: [{
title: 'My View',
xtype: 'myview'
}]
})
});