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.
Related
I'm trying to create a JavaScript object based on a template I received as a test. I use Ajax to get the data from my database but i cant seem to create the object.
$(document).ready(function() {
$.ajax({
type: 'POST',
url: 'fetch.php',
dataType: 'JSON',
success: function(response) {
var test = JSON.parse(response);
var products = {};
for (var x = 0; x < test.length; x++) {
products[x] = {
productName: test[x]['name']
};
products[x] = {
category: test[x]['category']
};
products[x] = {
price: test[x]['price']
};
}
}
});
});
I'm trying to create something like this object below
products = {data: [
{
productName: "test_item_1",
category: "category1",
price: "49",
image: "test_image.jpg",
},
{
productName: "test_item_2",
category: "category3",
price: "99",
image: "test_image.jpg",
},
{
productName: "test_item_3",
category: "category3",
price: "29",
image: "test_image.jpg",
},],};
This is the how i fetch the data from my database
while($row = mysqli_fetch_assoc($run)){$datas[] = $row;}echo json_encode($datas);
Your lines with products[x] overwrite the earlier.
Change to
products[x] = {
productName: test[x]['name'],
category: test[x]['category'],
price: test[x]['price'],
};
There's a couple of problems first...
The $.ajax() config option is dataType, not datatype
Specifying dataType: "json" means jQuery will automatically parse the response as JSON. You don't need to manually parse it again
As to your mapping problem, you can map the response array to a new one with name renamed to productName using Array.prototype.map()
$.ajax("fetch.php", {
method: "POST",
dataType: "json",
// data: ¯\_(ツ)_/¯
}).done(data => {
const products = {
data: data.map(({ name: productName, category, price }) => ({
productName,
category,
price
}))
};
});
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##########"
}
How can I upsert an edge in a transaction using orientjs? My current implementation upserts two vertices and always creates a new edge:
function add(db, from, edge, to, cb) {
cb = cb || function() {};
log(
'[' + from.clazz + ']' + JSON.stringify(from.attributes) + ' ' +
'-[' + edge.clazz + ']' + JSON.stringify(edge.attributes) + '> ' +
'[' + to.clazz + ']' + JSON.stringify(to.attributes)
);
db.let('source', function(s) {
s.update(from.clazz)
.set(from.attributes)
.upsert()
.where(from.attributes)
.return('after #this');
})
.let('destination', function(d) {
d.update(to.clazz)
.set(to.attributes)
.upsert()
.where(to.attributes)
.return('after #this');
})
.let('edge', function(e) {
e.create('EDGE', edge.clazz)
.from('$source')
.to('$destination')
.set(edge.attributes);
})
.commit()
.return('$edge')
.all()
.then(cb);
}
I've not found any upsert method for an edge in OrientJS, but you can prevent creation of edges twice between the same source and destination. You need to just
Create a UNIQUE index while creating an edge migration.
Here is the migration code for creating an edge with a unique index :
exports.up = (db) => {
return db.class.create('HasApplied', 'E')
.then((hasApplied) => {
return hasApplied.property.create(
[{
name: 'out',
type: 'link',
linkedClass: 'Consultant',
mandatory: true
}, {
name: 'in',
type: 'link',
linkedClass: 'Job',
mandatory: true
}, {
name: 'technicalQuestions',
type: 'embedded'
}, {
name: 'technicalAnswers',
type: 'embedded'
}, {
name: 'behavioralQuestions',
type: 'embedded'
}, {
name: 'behavioralAnswers',
type: 'embedded'
}, {
name: 'artifacts',
type: 'embeddedset'
}, {
name: 'comments',
type: 'string',
}, {
name: 'createdAt',
type: 'datetime'
}, {
name: 'updatedAt',
type: 'datetime'
}]
);
})
.then(() => db.query('CREATE INDEX HasApplied.out_in ON HasApplied (out, in) UNIQUE'));
};
Then when your code trying to run transaction containing let block :
.let('edge', function(e) {
e.create('EDGE', edge.HasApplied)
.from('$source')
.to('$destination')
.set(edge.attributes);
})
will throw db level error if found already exist edge between the same $source and $destination .
I hope this will definitely help you :)
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 );
}
});
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;
}
}