I am hoping that somebody can help me I have a jquery function which is getting values from a php form and I need to create variable for an ajax call. Is it possible to add a loop within a var
Here is my code so hopefully will explain better what I am trying to do
...
var teacher_ids = $( '#teacher_ids' ).val();
var status = 'pending';
var array = teacher_ids.split(',');
var data = {
name: title,
short_description: excerpt,
description: content,
status: status,
type: 'variable',
variations : [
This is where I am having the issue, I have multiple values which I want to be able to loop though
$.each(array,function (i, item) {
variation_type = item.split('_');
{
regular_price: half_hour,
attributes: [{
id:3,
slug: 'pa_lessonduration',
//name: 'lessonduration',
option: '1-hour'
},{
id: 1,
slug: 'pa_weekday',
// name: 'weekday',
option: variation_type[0]
},{
id: 2,
slug: 'pa_daytime',
//name: 'daytime',
option: variation_type[1],
}]
//"expected an assignment or function call and instead saw an expression?"
}
//"expected ( saw { "
})
$.ajax({
method: "PUT",
url: POST_SUBMITTER.root + 'wc/v1/products/'+ product_id +'',
data: data,
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'X-WP-Nonce', POST_SUBMITTER.nonce );
},
success : function( response ) {
console.log( response );
alert( POST_SUBMITTER.success );
},
fail : function( response ) {
console.log( response );
alert( POST_SUBMITTER.failure );
}
});
Any suggestion on how to get this to work please. This should print the following but I get errors
var data = {
name: title,
short_description: excerpt,
description: content,
status: status,
type: 'variable',
variations: [{
regular_price: '19.99',
attributes: [{
id: 3,
name: 'pa_lessonduration',
option: '1-hour'
}, {
name: 'pa_daytime',
option: '0900'
}, {
name: 'weekday',
option: 'monday'
}]
},
{
regular_price: '19.99',
attributes: [{
id: 3,
name: 'pa_lessonduration',
option: '1-hour'
}, {
name: 'pa_daytime',
option: '1100'
}, {
name: 'weekday',
option: 'wednesday'
}]
}]
}
etc etc...
I hope that makes sense, if not ask and I will try to make it more clear
The code below defines the array variation to be later used in data.
var teacher_ids = $( '#teacher_ids' ).val();
var status = 'pending';
var array = teacher_ids.split(',');
variation=[]; // Declare an empty array
// Then define it
for(i=0;i<array.length;i++){
variation_type = array[i].split('_');
variation[i] = {
regular_price: half_hour,
attributes: [{
id:3,
slug: 'pa_lessonduration',
//name: 'lessonduration',
option: '1-hour'
},{
id: 1,
slug: 'pa_weekday',
// name: 'weekday',
option: variation_type[0]
},{
id: 2,
slug: 'pa_daytime',
//name: 'daytime',
option: variation_type[1]
}]
}
}
var data = { // Define data
name: title,
short_description: excerpt,
description: content,
status: status,
type: 'variable',
variations : variation // This is the array defined in the loop above
}
$.ajax({
method: "PUT",
url: POST_SUBMITTER.root + 'wc/v1/products/'+ product_id +'',
data: data,
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'X-WP-Nonce', POST_SUBMITTER.nonce );
},
success : function( response ) {
console.log( response );
alert( POST_SUBMITTER.success );
},
fail : function( response ) {
console.log( response );
alert( POST_SUBMITTER.failure );
}
});
Related
let object=
[
{
id:`01`,
name:`fish`,
type:null,
care:'owner',
},
{
id:`02`,
name:`fish`,
type:'fresh',
care:'peter',
},
{
id:`03`,
name:`fish`,
type:`fresh`,
care:'amy',
},
{
id:`04`,
name:`fish`,
type:`tank`,
care:'abc',
},
{
id:`05`,
name:`animal`,
type:`pet`,
care:'teen',
},,
{
id:`06`,
name:`animal`,
type:`pet`,
care:'ran',
},
{
id:`07`,
name:`animal`,
type:null,
care:'roh',
},
{
id:`08`,
name:`food`,
type:`veg`,
care:'test',
},
{
id:`09`,
name:`food`,
type:null,
care:'dop',
}
]
object.map((value)=>{
console.log(value.name)
// i am calling function here by passing value.name as a parameter
let gotValue = functionName(value.name);
// using type also
if(typeof value.type!=="string"){
// Do some task here with gotValue
}
})
I have this object and i am getting some value from it for ex getting name from it as i want to pass this name to function but the problem is due to repeat of data the function calling again and again is there any possibility i can run function inside map but with unique value any help ?
as my output is getting like this
fish
fish
fish
animal
animal
animal
and this value.name is passing inside my function so its repeating like this
functionName(fish);
functionName(fish);
functionName(fish);
functionName(animal);
functionName(animal);
functionName(animal);
multiple time function is running with same name and getting duplicate values
just need my function run with unique name
functionName(fish)
functionName(animal);
functionName(food);
as i want to stay inside map function because i am performing some task which can only be possible inside map that's why i need unique value
You can use Set which can be used to test if the object with value already exists or not. It will only call the function only once.
let object = [
{
id: `01`,
name: `fish`,
type: null,
},
{
id: `02`,
name: `fish`,
type: `fresh`,
},
{
id: `03`,
name: `fish`,
type: `tank`,
},
{
id: `04`,
name: `animal`,
type: `pet`,
},
{
id: `05`,
name: `animal`,
type: `wild`,
},
{
id: `06`,
name: `animal`,
type: null,
},
{
id: `07`,
name: `food`,
type: `veg`,
},
{
id: `08`,
name: `food`,
type: null,
},
];
const dict = new Set();
object.map((value) => {
if (!dict.has(value.name)) { // Run only if objet with name is not already existed in dict
dict.add(value.name);
console.log(value.name); // For testing
// functionName(value.name);
}
});
If you want to call the function with two filters then you can use some to find the elements in an array. See I've now declared dict as an array
let object = [{
id: `01`,
name: `fish`,
type: null,
},
{
id: `02`,
name: `fish`,
type: `fresh`,
},
{
id: `03`,
name: `fish`,
type: `tank`,
},
{
id: `04`,
name: `animal`,
type: `pet`,
},
{
id: `05`,
name: `animal`,
type: `wild`,
},
{
id: `06`,
name: `animal`,
type: null,
},
{
id: `07`,
name: `food`,
type: `veg`,
},
{
id: `08`,
name: `food`,
type: null,
},
{
id: `09`,
name: `food`,
type: null,
},
{
id: `10`,
name: `fish`,
type: `tank`,
},
];
const dict = [];
object.map((value) => {
const { name, type } = value;
if (!dict.some((obj) => obj.name === name && obj.type === type)) {
// Run only if objet with name is not already existed in dict
dict.push({ name, type });
console.log(name, type); // For testing
// functionName(value.name);
}
});
.as-console-wrapper { max-height: 100% !important; top: 0; }
I'm trying to open a dialog in slack through a google app script after the user presses a button but i'm getting the following error message:
{"ok":false,"error":"invalid_auth","warning":"missing_charset","response_metadata":{"warnings":["missing_charset"]}}
This is my code:
function openDialog (range, triggerId, token) {
var url = 'https://slack.com/api/dialog.open';
var dialog = {
trigger_id: triggerId,
title: 'Submit a helpdesk ticket',
callback_id: 'submit-ticket',
submit_label: 'Submit',
elements: [
{
label: 'Title',
type: 'text',
name: 'title',
value: 'teste',
hint: '30 second summary of the problem',
},
{
label: 'Description',
type: 'textarea',
name: 'description',
optional: true,
},
{
label: 'Urgency',
type: 'select',
name: 'urgency',
options: [
{ label: 'Low', value: 'Low' },
{ label: 'Medium', value: 'Medium' },
{ label: 'High', value: 'High' },
],
},
],
};
var options = {
'method' : 'post',
'contentType': 'application/json',
'headers': {
'Authorization': 'Bearer ' + token,
},
'payload' : JSON.stringify(dialog),
};
var urlFetch = UrlFetchApp.fetch(url, options);
var message = ContentService.createTextOutput(urlFetch).setMimeType(ContentService.MimeType.JSON);
return message;
}
Can anyone spot what I'm missing?
Thanks
Here's the doPost() function triggering the openDialog() function it reads a payload from a button in slack with callback_id = "gasolina" and value = "update" :
if (payload.callback_id == "gasolina") {
var selectedOption = actions.value;
var operation = payload.callback_id;
var triggerId = payload.trigger_id;
var token = payload.token;
var inputRow = actions.name;
if (selectedOption == 'update') {
var keyword = 'no+money';
var gastoExtra = '';
var operation = payload.callback_id;
var gastoExtraRange = actions.name;
return openDialog (gasRange, triggerId, token);
I think that although your script is almost correct, a little modification is required. How about this modification for your script? From your question, I'm not sure about your current settings for using dialog.open of Slack. So this modified script supposes that the settings is correct.
Modification points :
Reason of missing_charset is due to using JSON.stringify() to the payload.
From the document of dialog.open, the payload is token, dialog and trigger_id.
token doesn't use for the header.
application/json doesn't use for contentType.
When these points are reflected to your script, the modified script is as follows.
Modified script :
function openDialog (range, triggerId, token) {
var url = 'https://slack.com/api/dialog.open';
var dialog = {
title: 'Submit a helpdesk ticket',
callback_id: 'submit-ticket',
submit_label: 'Submit',
elements: [
{
label: 'Title',
type: 'text',
name: 'title',
value: 'teste',
hint: '30 second summary of the problem',
},
{
label: 'Description',
type: 'textarea',
name: 'description',
optional: true,
},
{
label: 'Urgency',
type: 'select',
name: 'urgency',
options: [
{ label: 'Low', value: 'Low' },
{ label: 'Medium', value: 'Medium' },
{ label: 'High', value: 'High' },
],
},
],
};
var options = {
method: 'post',
payload: {
token: token,
dialog: JSON.stringify(dialog),
"trigger_id": triggerId,
},
};
var urlFetch = UrlFetchApp.fetch(url, options);
var message = ContentService.createTextOutput(urlFetch).setMimeType(ContentService.MimeType.JSON);
return message;
}
Note :
In my environment, I'm using dialog.open with the request like above script. But if this didn't work, please check the error messages and modify your settings.
if you request by application/json.
You use to header.authorization.
https://github.com/slackapi/python-slack-sdk/issues/302#issuecomment-825321015
API
https://api.slack.com/methods/chat.postMessage
https://slack.com/api/chat.postMessage
Authorization in Headers
Content-Type: application/json
Authorization: 'Bearer ' + token
{
"text": "hello",
"as_user": true,
"channel": "U##########"
}
I have these two array of objects
todos: [
{
id: 1,
name: 'customerReport',
label: 'Report send to customer'
},
{
id: 2,
name: 'handover',
label: 'Handover (in CRM)'
},
]
And:
todosMoreDetails: [
{
id: 1,
checked: false,
link: {
type: 'url',
content: 'http://something.com'
},
notes: []
},
{
id: 2,
checked: false,
link: {
type: 'url',
content: 'http://something.com'
},
notes: []
}
]
So that the final array of objects will be a combination of the two, based on the object ID, like below:
FinalTodos: [
{
id: 1,
checked: false,
link: {
type: 'url',
content: 'http://something.com'
},
notes: [],
name: 'customerReport',
label: 'Report send to customer'
},
{
id: 2,
checked: false,
link: {
type: 'url',
content: 'http://something.com'
},
notes: [],
name: 'handover',
label: 'Handover (in CRM)'
}
]
I tried with merge mergeAll and mergeWithKey but I am probably missing something
You can achieve this with an intermediate groupBy:
Transform the todosMoreDetails array into an object keyed by todo property ID using groupBy:
var moreDetailsById = R.groupBy(R.prop('id'), todosMoreDetails);
moreDetailsById is an object where the key is id, and the value is an array of todos. If the id is unique, this will be a singleton array:
{
1: [{
id: 1,
checked: false,
link: {
type: 'url',
content: 'http://something.com'
},
notes: []
}]
}
Now transform the todos array by merging each todo to it's details you retrieve from the grouped view:
var finalTodos = R.map(todo => R.merge(todo, moreDetailsById[todo.id][0]), todos);
An alternate more detailed way:
function mergeTodo(todo) {
var details = moreDetailsById[todo.id][0]; // this is not null safe
var finalTodo = R.merge(todo, details);
return finalTodo;
}
var moreDetailsById = R.groupBy(R.prop('id'), todosMoreDetails);
var finalTodos = todos.map(mergeTodo);
I guess merge is only used for arrays. Have a search for object "extend". Maybe storing the todo details not in seperate objects is the better solution.
Using jQuery? https://api.jquery.com/jquery.extend/
Using underscore? http://underscorejs.org/#extend
Native approach? https://gomakethings.com/vanilla-javascript-version-of-jquery-extend/
Using underscore:
var result = [];
var entry = {};
_.each(todos, function(todo) {
_.each(todosMoreDetails, function(detail) {
if (todo.id == detail.id) {
entry = _.extend(todo, detail);
result.push(entry);
}
}
});
return result;
I am trying to create dynamic listbox values but getting this error in console:
Uncaught TypeError: Cannot assign to read only property 'active' of [
Here's my code( pasting only the code for listbox ):
body: [
{
type: 'listbox',
name: 'type',
label: 'Panel Type',
value: type,
'values': get_author_list(),
tooltip: 'Select the type of panel you want'
},
]
.....
And I am calling this function to get dynamic list...
function get_author_list() {
var d = "[{text: 'Default', value: 'default'}]";
return d;
}
I am guessing that the values in listbox only takes static var and not dynamic. But I need to insert dynamic values in this list. Please can anyone help me find a workaround. Is there any possibility to insert via ajax?
Thanks, in advance!!
I needed something similar for .NET site. Even though is not great code I hope it can help someone.
tinymce.PluginManager.add('DocumentSelector', function (editor, url) {
// Add a button that opens a window
editor.addButton('DocumentSelector', {
text: 'Document',
icon: false,
title: "Document Selector",
onclick: function () {
var _documentList;
//load all documents
var _data = JSON.stringify({/* Some data */});
$.ajax({
type: "POST",
url: "/api/TinyMCE/GetDocuments",
data: _data,
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (data) {
_documentList = eval('(' + data + ')');
// Open window
editor.windowManager.open({
title: 'Document Selector',
body: [
{
type: 'listbox',
name: 'DocURL',
label: 'Documents',
values: _documentList
},
{
type: 'textbox'
, name: 'TextToDisplay'
, value: _text
, label: 'Text To Display'
},
{
type: 'textbox'
, name: 'TitleToDisplay'
, value: _title
, label: 'Title'
},
{
type: 'listbox',
name: 'TheTarget',
label: 'Target',
values: [{ text: 'None', value: "_self" }, { text: 'New Window', value: "_blank" }],
value: _target
}
],
onsubmit: function (e) {
// Insert content when the window form is submitted
}
});
},
error: function (xhr, status, error) {
alert("Error! " + xhr.status + "\n" + error);
}
});
}
});
});
And here it is some of the Behind code
public class TinyMCEController : ApiController
{
public class DocumentsInfo
{
// Some data
}
public class DocumentList
{
public string text { get; set; }
public string value { get; set; }
}
[HttpPost]
[ActionName("GetDocuments")]
public object GetDocuments(DocumentsInfo docInfo)
{
//Test data
List<DocumentList> _DocumentList = new List<DocumentList>();
_DocumentList.Add(new DocumentList {
text = "Document1.pdf",
value = "value1"
});
_DocumentList.Add(new DocumentList
{
text = "Document2.pdf",
value = "value2"
});
var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(_DocumentList);
return json;
}
}
I'm trying to set up a bootstrap typehead.Here is my jquery code
$(function () {
$.ajax({
type: "GET",
url: "http://example.com/search?callback=my_callback",
data: { keyword: 'r' },
jsonpCallback: "my_callback",
dataType: "jsonp",
error: function (xhr, errorType, exception) {
var errorMessage = exception || xhr.statusText;
alert("Excep:: " + exception + "Status:: " + xhr.statusText);
}
});
var sources = [
{ name: "local", type: "localStorage", key: "cities", display: "country" },
{ name: "remote", type: "remote", url: "/cities/list" },
{ name: "data", type: "data", data: [] }
];
$('input.typeahead.local.remote').typeahead({
sources: [
{ name: "local", type: "localStorage", key: "cities" }
]
});
});
function my_callback(data) {
alert(data.count);
var src2 = '[';
var i;
for (i = 0; i < data.count; i++) {
src2 = src2 + "{ id : " + (i + 1) + " , name: '" + data.response[i].name + "' },";
}
src2 = src2.substring(0, src2.length - 1);
src2 = src2 + ']';
var sampleJson = [{ id: 1, name: 'Really Awesome' }, { id: 2, name: 'RSpecge'}];
localStorage.setItem("cities", JSON.stringify(src2));
}
In my callback function when i set localStorage using the data returned from jquery ajax call it doesn't work.But when i try to set the data directly using variable sampleJson it works.
Y is it so??
Here is the json dynamically created from response from jquery ajax which looks the same as the sampleJson
[{ id: 1, name: 'Really Awesome' }, { id: 2, name: 'RSpecge'}]
And here is sampleJson
var sampleJson = [{ id: 1, name: 'Really Awesome' }, { id: 2, name: 'RSpecge'}];
Can you clarify "doesn't work"? Trying to serialize your data to a JSON string by hand is unnecessary and error prone. Manipulate your data as regular javascript objects then use JSON.stringify to convert it to a string when ready. It will produce actual JSON, which, for example, requires all keys to be enclosed within double quotes, whereas your code is generating javascript object literal syntax that permits most keys to be unquoted.