Javascript HTTP POST input JSON error - javascript

I am trying to add JSON request into a HTTP POST javascript code like below. Please see the code below.
My problem is, I need to input following format JSON and send it. But, I am getting Uncaught SyntaxError: Unexpected token : Could you please advise, What is wrong formatting JSON in my code below?
Sample JSON format to be sent=> {"records":[{"value":{"foo":"bar"}}]}
Code:
function savedata() {
var membernameStr = parseInt(document.getElementById("MemberID").value).toString();
var data = JSON.stringify({
"records": [["value":{"MemberID":membernameStr,"MemberName":"Anna", "AccountNo":"7623", "Address":"Peter", "AccountType":"Peter"}]]
});
var xhr = new XMLHttpRequest();
xhr.addEventListener("readystatechange", function () {
if (this.status == 200) {
console.log(this.responseText);
// Based on successful response, call next POST API.
var xhr1 = new XMLHttpRequest();
xhr1.open("POST", "http://localhost:3500");
xhr1.send(data);
}
});
xhr.open("POST", "http://localhost:8082/topics/topictest");
xhr.setRequestHeader("Content-Type", "application/vnd.kafka.json.v2+json; charset=utf-8");
xhr.setRequestHeader("Accept", "application/vnd.kafka.v2+json; charset=utf-8");
xhr.send(data);
}

Your JSON was incorrect in the syntax, please have a look at below JSON:
{
"records": [
[
{
"value": {
"MemberID": membernameStr ,
"MemberName": "Anna",
"AccountNo": "7623",
"Address": "Peter",
"AccountType": "Peter"
}
}
]
]
}

why did you use array within array ? you can also use as below ..
{
"records": [
{
"value": {
"MemberID": membernameStr ,
"MemberName": "Anna",
"AccountNo": "7623",
"Address": "Peter",
"AccountType": "Peter"
}
}
]
}

Related

Unexpected error while saving Microsoft Teams connector

I've developed an app and connector for Microsoft teams, whenever I try to setup a connector for a specific channel and save the connector when the setup is finished there is an unexpected error message
If I then look in the developer tools I see that some request is send to https://outlook.office.com/connectors/ConnectToO365Inline/Manage/UpdateAsync with a http 500 response. I have followed the documentation provided by Microsoft at https://learn.microsoft.com/en-us/microsoftteams/platform/webhooks-and-connectors/how-to/connectors-creating I also stripped down our code to the bare minimum but still get the unexpected error while saving.
It's also very odd that the connector works perfectly on our Microsoft partner account, but whenever I try the connector on an other microsoft account it gives the unexpected error while saving.
Here you can see the manifest.json for the app:
{
"$schema": "https://developer.microsoft.com/json-schemas/teams/v1.11/MicrosoftTeams.schema.json",
"manifestVersion": "1.11",
"version": "1.0.0",
"id": "0fa0f150-fd7e-4c4e-822e-793951af07f6",
"packageName": "com.package",
"developer": {
"name": "App name",
"websiteUrl": "https://www.domain",
"privacyUrl": "https://www.domain",
"termsOfUseUrl": "https://www.domain"
},
"name": {
"short": "short",
"full": "full"
},
"description": {
"short": "short description",
"full": "long description"
},
"icons": {
"outline": "icon.png",
"color": "icon.png"
},
"accentColor": "#3F487F",
"connectors": [
{
"connectorId": "8b4fe7a3-a04d-4d60-b204-0519ca2f0d04",
"configurationUrl": "https://domain/teams/config",
"scopes": [
"team"
]
}
],
"permissions": [
"identity",
"messageTeamMembers"
],
"validDomains": [
"domain"
]
}
And this is our save handler as part of our file to setup the connector:
microsoftTeams.settings.registerOnSaveHandler(function (saveEvent) {
microsoftTeams.getContext(context => {
microsoftTeams.settings.getSettings(s => {
let data = {
url: s.webhookUrl,
name: context.teamName + ' - ' + context.channelName,
channel_id: context.channelId,
token: s.entityId,
origin: window.location.origin
};
let xhr = new XMLHttpRequest();
xhr.open('POST', '/teams/token/updateWebhook');
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
let response = JSON.parse(xhr.response);
if (response.status === true) {
context.webhookUrl = response.value;
saveEvent.notifySuccess();
}
}
}
xhr.send(JSON.stringify(data));
});
});
});
I already contacted Microsoft support but they said their expertise to developed software and connectors are very little, so we should ask it on Stackoverflow.
What is going wrong, and what do i need to do to make it work?

How to retrieve data from json file

I am having trouble with accessing my json file from my javascript file. I would like to change the object to a different text in my json file once a submit button is clicked on the webpage. I am aware that I would use ajax to achieve this goal, but I do not know how to access the json file.
This is the db.json file
{
{
"assets": [
{
"id": "0946",
"manufacturer": "SONY",
},
{
"id": "0949",
"manufacturer": "AUDIOTECNIA"
}
],
"transfers": [
{
"id": 1,
"status": "in-progress"
}
]
}
This is my Javascript file
$('form').on('submit', function(e){
e.preventDefault();
parsedData = JSON.parse(db.json);
console.log(parsedData[0].id)
//Changing Status
$.ajax({
type: "PATCH",
url: `http://localhost:3000/transfers/`
});
I've tried using parseData because I read that is how to retrieve the object, from the json file, but I do not believe I am writing it correctly. What documentation or steps would one recommend for solving this issue?
You have an extra comma after "in-progress",
const parsedData = JSON.parse(`{
"transfers": [ {
"id": 1,
"status": "in-progress"
}]
}`)
Then, to access id in parsedData:
console.log(parsedData.transfers[0].id)
You did not initialize the variable parsedData.
var parsedData = JSON.parse(db.json);

Error with Remote Pagination in Tabulator 5.0

My tabulator 5.0 table works fine. But when I attempt to use remote pagination it no longer works at all.
var table = new Tabulator("#account-tran-detail-table", {
pagination:true,
paginationMode:"remote", //if this line is commented out then it works fine without pagination
paginationSize: 12,
dataSendParams:{
page: "page",
size: "page_size",
},
dataReceiveParams:{
last_page:"total_pages",
} ,
ajaxResponse:function(url, params, response){
return response.results; // return the array of table items
},
});
table.on("tableBuilt", function(){
table.setColumns(columns);
});
function generateReport () {
table.clearData();
var columns = [
{title:"id", field:"id", headerFilter:false, visible:false, download:true},
{title:"name", field:"name", headerFilter:false, visible:false, download:true},
];
var gender = "m";
var url = "/api/v1/myendpointname/";
var append_params = "?gender=" + gender;
$("#tableBuilt").destroy;
table.setData(url + append_params);
};
The response looks like this:
{
"count": 10,
"total_pages": 3,
"next": "http://localhost:8000/myendpointname/?gender=m&page=2&size=3
"previous": null,
"results": [
{
"id": 1,
"gender": "m",
"name": "abc",
},
{
"id": 2,
"gender": "m",
"name": "def",
},
{
"id": 3,
"gender": "m",
"name": "ghi",
},
]
}
You can see where I'm asking tabulator to read total_pages instead of the default last_page by using dataReceiveParams. And you can also see where I'm asking tabulator to send page_size instead of the default size by using dataSendParams to generate the request.
I get two warnings . . .
Remote Pagination Error - Server response missing 'undefined' property Page.js:707:11
Remote Pagination Error - Server response missing 'undefined' property Page.js:754:11
Followed by an error.
Data Loading Error - Unable to process data due to invalid data type
Expecting: array
Received: undefined
Data: undefined
The code referenced by the warnings:
707: console.warn("Remote Pagination Error - Server response missing '" + this.dataReceivedNames.last_page + "' property");
754: console.warn("Remote Pagination Error - Server response missing '" + this.dataReceivedNames.data + "' property");
So it seems to me that tabulator isn't "seeing" the total_pages portion of the response. Why is it not using defaultReceiveParams? Could it be because of my ajaxResponse function returns response.results and strips the rest of the response away?
(Same behavior for Chrome and Firefox)
Use ajaxResponse to return data and last_page as
Codesandbox

fetch and remove innerHTML from JSON using the same button

I have an external JSON file that looks like this:
[
{
"id": "1",
"label": "2017-03-30",
"value": "1675000",
"accessories": "true"
},
{
"id": "2",
"label": "2017-04-01",
"value": "1440000",
"accessories": "true"
},
{
"id": "3",
"label": "2017-04-02",
"value": "830000",
"accessories": "false"
}
]
I can fetch the JSON using the following button and it displays in the div ID of accessories:
<button id="button2">Get Customers</button>
<h1>Brands that sell Accessories:</h1>
<div id="accessories"></div>
The JavaScript I am using is:
document.getElementById('button2').addEventListener
('click', loadData);
function loadData(e) {
const xhr = new XMLHttpRequest();
xhr.open('GET', 'data.json', true);
xhr.onload = function() {
if(this.status === 200) {
// console.log(this.responseText);
const customers = JSON.parse(this.responseText);
let output = '';
customers.forEach(function(customer) {
output += `
<ul>
<li>Company ID: ${customer.id}</li>
<li>Company label: ${customer.label}</li>
<li>Company value: ${customer.value}</li>
<li>Company Accessories: ${customer.accessories}</li>
</ul>
`;
})
document.getElementById('accessories').innerHTML = output;
}
}
xhr.send();
};
This outputs the company information in bullet points.
What I want to do next is remove the HTML by pressing the same button but I'm struggling to keep it removed.
I've tried:
function removeAcc() {
document.getElementById('accessories').innerHTML = '';
}
But it just flashes back to the same list.
Help will be very much appreciated.
you need to save the current state of your program somewhere so that you know if the "external JSON" was already loaded or not. This way you can switch the action in the eventListener like so:
document.getElementById('button2').addEventListener('click', toggleData);
function toggleData(e) {
if(hasData) {
removeAcc()
hasData = false;
} else {
loadData(e)
hasData = true;
}
}

converting to key, values pair

My question
How to read rom txt file in JS
Best approach to process the data. Something like this below or ????
var data = [
{
name: "Orange",
type: "Fruit",
desc: "some description about the recipe"
},
{
name: "Spinach",
type: "Veg",
desc: "some description about the recipe"
},
{
name: "Beans",
type: "Veg",
desc: "some description about the recipe"
},
]
I want to have an object array so that I can process it further to print out unique names of fruits, just veggies and just fruits.
You can accomplish this using AJAX and then a regular expression.
If you're using jQuery:
$.ajax({
url: 'someTextFile.txt',
success: function(data) {
var regEx = /([a-zA-Z]+), ([a-zA-Z]+).*[\r\n \t]*([a-zA-Z0-9 \.]+)/g,
recipe, allRecipies = [];
while (recipe = rege.exec(data)) {
allRecipies.push({
name: recipe[1],
type: recipe[2],
desc: recipe[3],
});
}
console.log(allRecipies);
}
});
If you're not using jQuery
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
data = xhttp.responseText;
var regEx = /([a-zA-Z]+), ([a-zA-Z]+).*[\r\n \t]*([a-zA-Z0-9 \.]+)/g,
recipe, allRecipies = [];
while (recipe = rege.exec(data)) {
allRecipies.push({
name: recipe[1],
type: recipe[2],
desc: recipe[3],
});
}
console.log(allRecipies);
}
};
xhttp.open("GET", "filename", true);
xhttp.send();
Don't bother creating your own parser to read in formats.
Save your content in a standard data-interchange format like json or xml
There are so many others and lookup standard libraries to parse them and get your information.
I'll recommend json, as Javascript as a JSON object for parsing JSON Files. And their are other good libraries for parsing JSON.

Categories