How to make an AJAX call to a locally defined variable - javascript

I'm trying generate a list after an obtained JSON, I found docs from dynatable library so they can populate a table in the ajax way receiving a JSON.
However, what if I already have the json stored in a variable. I've tried this so far:
var json = {
"records": [
{
"someAttribute": "I am record one",
"someOtherAttribute": "Fetched by AJAX"
},
{
"someAttribute": "I am record two",
"someOtherAttribute": "Cuz it's awesome"
},
{
"someAttribute": "I am record three",
"someOtherAttribute": "Yup, still AJAX"
}
],
"queryRecordCount": 3,
"totalRecordCount": 3
}
var table = $('#resultados').dynatable({
dataset: {
ajax: true,
ajaxUrl: json,
ajaxOnLoad: true,
records: []
}
})
So I'm getting a 404 code, I understand that's because that's not an actual route. But what can I do to tell library to request for that file. Isn't even ajax required?

Since you already have it in a javascript array called json, you can (I make the assumption that you want to use json.records):
$('#resultados').dynatable({
dataset: {
records: json.records
}
});

Related

JavaScript parsing nested JSON data

I'm creating a discord bot (using discord.js)
I'm writing a help command using pages in embeds, I have the pages working fine - however, the problem seems to come when trying to get the data from the JSON.
I have the JSON file setup in a larger config file, so it's nested inside of it.
Each command has it's name attached to it
{
"other-json-data": "other data",
"commands": {
"rule": {
"info": "This command gives the rules",
"expectedArgs": "<number>"
},
"invite": {
"info": "Invite new users",
"expectedArgs": "<no-args>"
},
"flip": {
"info": "Flip a coin",
"expectedArgs": "<no-args>"
}
},
"other-json-data": "other data"
}
I need to get the data from the commands area for each page.
I only have a integer input (from the page number), but I haven't got a clue how I would get the data from whatever command needs to be shown.
For something else in my project, I am using this to get the expectedArgs from the JSON object config.commands[arguments].expectedArgs, where the config is just a reference to the JSON file, this works perfectly fine. The arguments is a string input (i.e. rule), which returns whatever the info from that command.
However, would there be a way to get say the second one down (invite). I've tried config.commands[pageNumber].expectedArgs}, however, this doesn't seem to work. pageNumber would be an integer, so would it would get whatever value and then I could grab the expectedArgs.
You can get all keys from an object and select one using their index.
const json = {
"other-json-data": "other data",
"commands": {
"rule": {
"info": "This command gives the rules",
"expectedArgs": "<number>"
},
"invite": {
"info": "Invite new users",
"expectedArgs": "<no-args>"
},
"flip": {
"info": "Flip a coin",
"expectedArgs": "<no-args>"
}
},
"other-json-data": "other data"
}
const pageNumber = 1
// key will be a command name, e.g. 'invite'
const key = Object.keys(json.commands)[pageNumber]
const { expectedArgs } = json.commands[key]
console.log(`${key} expects ${expectedArgs}`)
Remember that indexes range starts at zero.

What is wrong with my JSON output for a Slack Message payload?

I have set up what I think should be a working JSON output to send a message in slack but Slack keeps rejecting it.
I have tried multiple different message layout formats using the guides on slack's api site, but so far the only method that has successfully sent is a fully flat JSON with no block formatting.
function submitValuesToSlack(e) {
var name = e.values[1];
var caseNumber = e.values[2];
var problemDescription = e.values[3];
var question = e.values[4];
var completedChecklist = e.values[5];
var payload = [{
"channel": postChannel,
"username": postUser,
"icon_emoji": postIcon,
"link_names": 1,
"blocks": [
{
"type": "section",
"fields": [
{
"type": "mrkdwn",
"text": "*Name:*\n " + name
}
]
}]
}];
console.log(JSON.stringify(payload, null, "\t"));
var options = {
'method': 'post',
'payload': JSON.stringify(payload)
};
console.log(options)
var response = UrlFetchApp.fetch(slackIncomingWebhookUrl, options);
}
When I run this, I get the following output:
[
{
"channel":"#tech-support",
"username":"Form Response",
"icon_emoji":":mailbox_with_mail:",
"link_names":1,
"blocks":[
{
"type":"section",
"fields":[
{
"type":"mrkdwn",
"text":"*Name:*\n test"
}
]
}
]
}
]
Which I believe is correct, however slack api just rejects it with an HTTP 400 error "no text"
am I misunderstanding something about block formatting?
EDIT:
To Clarify, formatting works if I use this for my JSON instead of the more complex format:
{
"channel":"#tech-support",
"username":"Form Response",
"icon_emoji":":mailbox_with_mail:",
"link_names":1,
"text":"*Name:*\n test"
}
The reason you are getting the error no_text is because you do not have a valid message text property in your payload. You either need to have a text property as top line parameter (classic style - your example at the bottom) or a text block within a section block.
If you want to put to use blocks only (as you are asking) the section block is called text, not fields. fields is another type of section bock that has a different meaning.
So the correct syntax is:
[
{
"channel":"#tech-support",
"username":"Form Response",
"icon_emoji":":mailbox_with_mail:",
"link_names":1,
"blocks":[
{
"type":"section",
"text":[
{
"type":"mrkdwn",
"text":"*Name:*\n test"
}
]
}
]
}
]
Also see here for the official documentation on it.
Blocks are very powerful, but can be complicated at times. I would recommend to use the message builder to try out your messages and check out the examples in the docu.

getting signature error for _POST_ORDER_FULFILLMENT_DATA_

I'm trying to post fulfillment data on SubmitFeed using javascript in sapui5 and i have done the steps as,
1) I have created json object for fulfillment data and converted it into XML again XML converted into MD5.
JSON code:-
{
"AmazonEnvelope": {
"-xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
"-xsi:noNamespaceSchemaLocation": "amznenvelope.xsd",
"Header": {
"DocumentVersion": "1.01",
"MerchantIdentifier": "Example"
},
"MessageType": "OrderFulfillment",
"Message": {
"MessageID": "1",
"OperationType": "Update",
"OrderFulfillment": {
"AmazonOrderID": "102-8289425-201934",
"FulfillmentDate": "2017-06-20T00:36:33-08:00",
"FulfillmentData": {
"CarrierName": "UPS",
"ShippingMethod": "Second Day",
"ShipperTrackingNumber": "1234567890"
},
"Item": {
"AmazonOrderItemCode": "1234567",
"MerchantFulfillmentItemID": "1234567",
"Quantity": "2"
}
}
}
}
};
2) Created signature as per the api documents.
3) Post the data on Feed/2009-01-01.
but i'm getting the error as:-
"<?xml version="1.0"?>
<ErrorResponse xmlns="https://mws.amazonservices.com/">
<Error>
<Type>Sender</Type>
<Code>InvalidAddress</Code>
<Message>Resource /$metadata is not found on this server. API Version is missing</Message>
</Error>
<RequestID>c00cb653-f53c-445f-9f24-82587144805d</RequestID>
</ErrorResponse>
"
Please help me to resolve this.
Thank you
The error you are getting is InvalidAddress, not a signature check error. It seems whatever you are doing in step 3 (Post the data on Feed/2009-01-01) does not work as expected. The MWS servers see a request for /$metadata instead of API name and version. Your question does not include the piece of code that does that.

Ext.js problems building model relations from json

In my project, I need to create a questionnaire (a form). The questions are generated dynamically depending on a category, and are on a server, in a database.
To get the questions a REST API is used, so sending a request to /getquestions/1 returns a JSON having all the data needed for form generation.
The JSON looks like this:
{
"questions":[
{
"id":4,
"text":"Question1",
"type":"NUMBER",
"mandatory":true,
"visible":true
},
{
"id":5,
"text":"Dropdown type question",
"type":"DROPDOWN",
"mandatory":true,
"visible":true,
"values":[
{
"id":1,
"text":"Answer1",
"selected":false
},
{
"id":2,
"text":"Answer2",
"selected":false
}
]
},
{
"id":7,
"text":"Question 3 as Radio",
"type":"RADIO",
"mandatory":false,
"visible":false,
"values":[
{
"id":1,
"text":"Yes",
"selected":false
},
{
"id":2,
"text":"No",
"selected":false
}
],
"dependencies":{
"mark_visible":[
{
"question_id":5,
"operation":"=",
"value":2
}
],
"mark_mandatory":[
{
"question_id":5,
"operation":"=",
"value":2
},
{
"question_id":4,
"operation":"<=",
"value":5000
}
]
}
}
]
}
]
}
I have store and model for questions.
I think I need a store for values as well, to make it visible in a dropdown list, and another one for the dependencies too.
I just wondering, whether is it possible to fill all stores somehow without any explicite coding, using ext and model relations like hasMany and so.
I am basically looking for the best practice and fastest solution in Ext.js to create models and relations out of this JSON
any idea woud be really helpful.
To populate a model and its associations from JSON data you need to have it go through a reader class (e.g. Ext.data.JsonReader) where it will move down the 'tree' creating the associations.
If you are loading through a proxy this should happen automatically (as it uses a reader by default). If your JSON is coming from an AJAX call and you are creating the model instance with an Ext.create call then you need to do the reader bit yourself. Something like:
var data = [...];
var reader = Ext.create('Ext.data.JsonReader', {
model: 'MyModel'
});
var resultset = reader.readRecords(data);
console.log(resultset.getRecords()[0]); // logs first read record

Iteration in handlebar using backbone

I'm using backbone and handlebars for templating and i'm new to this.
My current json is in the below format and the code works fine.
[
{
"id": "10",
"info": {
"name": "data10"
}
},
{
"id": "11",
"info": {
"name": "data11"
}
}
]
But when i change my json structure to something like shown below i'm having difficulty in getting things to be populated.
{
"total_count": "10",
"dataElements": [
{
"id": "10",
"info": {
"name": "data10"
}
},
{
"id": "11",
"info": {
"name": "data11"
}
}
]
}
How can i populate name, info and total_count keeping the current code structure ?
JSFiddle : http://jsfiddle.net/KTj2K/1/
Any help really appriciated.
A few things that you need to do in order for this to work.
Replace Backbone's core 'reset' on your collection with a custom one that understands the data you are passing to it. For example:
reset: function (data) {
this.totalCount = data.total_count;
Backbone.Collection.prototype.reset.call(this, data.dataElements);
}
Now when you reset your collection, it will pull the total_count out of the object you are resetting it with, and use Backbone's core reset with the dataElement array. Keep in mind you may have to do a similar thing with 'parse' if you're intending on pulling this from the server.
I'd recommend that (if your example looks anything like the real code you're working with) you reset your collection before getting to rendering.
var dataCollectionList = new dataCollection();
dataCollectionList.reset(jsonData);
var App = new AppView({model : dataCollectionList});
Now in your view's "render" method you can grab the 'totalCount' property off the collection -
render : function() {
//Should spit the total count into the element, just as an example
this.$el.append(this.model.totalCount);
//or console.log it
console.log(this.model.totalCount);
return this;
}
Voila. Side note - as someone who works with Backbone a lot, it drives me nuts when people set an attribute of something like "model" (i.e. peopleModel, itemModel, etc) and it ends up being a backbone collection. It's much clearer to name it after what it is - though some MVC purists may disagree a bit.
Also, in this code block:
_.each(this.model.models, function (myData) {
$(this.el).append(new ItemView({model:myData}).render().el);
}, this);
You don't need to do _.each(this.model.models.......). Since you're working with a collection, the collection has a built in 'each' method.
this.model.each(function (myData) { ..... } , this);
Quite a bit cleaner.

Categories

Resources