What is the error in this code?My data is not inserting into sql server - json

I have checked my api through postman and its working but the error is in the jquery or ajax.
I have tried to find error but cant understand.Please Try to solve this problem.Thankyou so much
$(document).ready(function () {
$("#AddPatientReport").click(function () {
alert("PatientReport Added Successfully");
var DoctorId = $("#ReportDoctorId").val();
var DoctorName = $("#ReportDoctorName").val();
var PatientName = $("#ReportPatientName").val();
var PatientId = $("#ReportPatientId").val();
var PharmacyCategory1 = $("#ReportPharmacyCategory1").val();
var Medicine1 = $("#ReportMedicine1").val();
var PharmacyCategory2 = $("#ReportPharmacyCategory2").val();
var Medicine2 = $("#ReportMedicine2").val();
var AppointmentDate = $("#ReportPatientDate").val();
var AppointmentTime = $("#ReportPatientTime").val();
var PatientDescription = $("#ReportPatientDescription").val();
$.ajax({
url: '/home/addpatientreport',
type: 'POST',
data: {
DoctorId: DoctorId,
DoctorName: DoctorName,
PatientName: PatientName,
PatientId: PatientId,
PharmacyCategory1: PharmacyCategory1,
Medicine1: Medicine1,
PharmacyCategory2: PharmacyCategory2,
Medicine2: Medicine2,
AppointmentDate: AppointmentDate,
AppointmentTime: AppointmentTime,
PatientDescription: PatientDescription
},
dataType: 'application/json; charset=utf-8',
contentType: "application/x-www-form-urlencoded"
});
});
});

Related

FinBox.com logging in with UrlFetchApp to access another link?

I can't log in successfully from Google Apps Script despite looking for solutions hours long, including many entries in SoF.
The login process sends a POST request to this url: https://finbox.com/_/api/v5/tokens
Input of the credentials happens here: https://finbox.com/login/email
Response code is 400.
Any help will be really appreciated :)
So far I ended up with this:
function testFinBoxWithCredentials(stock = "AAPL") {
var options = {
method: 'post',
contentType: 'application/json',
payload: {
email: 'xxxxxxxxx',
password: 'xxxxxxxxx'
},
muteHttpExceptions: true,
followRedirects: false
};
const response = UrlFetchApp.fetch("https://finbox.com/_/api/v5/tokens", options);
Logger.log(response.getResponseCode());
if ( response.getResponseCode() == 200 ) {
Logger.log("Couldn't login.");
}
else if ( response.getResponseCode() == 302 ) {
Logger.log("Logged in successfully");
var cookie = response.getAllHeaders()['Set-Cookie'];
Logger.log(cookie);
//Access then a link like https://finbox.com/NASDAQGS:AAPL
/* var cookies = response.getAllHeaders()['Set-Cookie'];
for (var i = 0; i < cookies.length; i++) {
cookies[i] = cookies[i].split( ';' )[0];
};
url2 = "https://finbox.com/NASDAQGS:AAPL";
options2 = {
"method": "get",
"headers": {
"Cookie": cookies.join(';')
}
}
var response2 = UrlFetchApp.fetch(url2, options2);
var content = response2.getContentText();
Logger.log(content)*/
} ```

Telegram BOT API, method setMyCommands, Google Apps Script

I want to set some command on my t-bot, but i cant understand how to do that
var token = "123456....";
var url = "https://api.telegram.org/bot" + token;
function setMyCommands(chat_id, message_id){
var data = {
method: "post",
payload:{
method: "setMyCommands",
chat_id: String(chat_id),
message_id: message_id,
parse_mode: "HTML"
}
};
UrlFetchApp.fetch(url + '/', data);
}
Now, I am doing like
if message is "/command" to do so. through following:
function sendMessage(id, text, keyBoard){
var data = {
method: "post",
payload: {
method: "sendMessage",
chat_id: String(id),
text: text,
parse_mode: "HTML",
reply_markup: JSON.stringify(keyBoard)
}
};
UrlFetchApp.fetch(url + "/", data);
}
function doPost(e) {
var contents = JSON.parse(e.postData.contents);
var id = contents.message.from.id;
var text = contents.message.text;
if (text == "/command") {
sendMessage(id,"someTEXT...")
}
}
could u pls, also explain what should var data look like and where can I take a form(or structure) of this to apply other methods from telegram bot API
Pyhton case:
create variables:
BOT_TOKEN = '12324'
BOT_COMMANDS= [{"command":"a", "description":"aaa"},{"command":"b","description":"bbb"}]
create the function:
def setMyCommands():
send_text = 'https://api.telegram.org/bot' + BOT_TOKEN + '/setMyCommands?commands=' + str(json.dumps(BOT_COMMANDS) )
response = requests.get(send_text)
and finnaly execute:
if __name__ == '__main__':
#getMyCommands()
setMyCommands()

orgchart splitting into three, and displaying Id's on the chart

Here's what my chart displays:
Here's my Position tables:
My position table
cant really seem to figure out whats the problem.
-Ive got a button and a dropdown, when an item is selected from the dropdown and button is selected an orgchart must be displayed. The chart displays but the problems are:
-orgchart splitting into three charts
-And it keeps showing some Id's
-here's my code:
google.load("visualization", "1", { packages: ["orgchart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
$("#btnGetOrganogram").on('click', function (e) {
debugger
$ddlDepOrgano = $('[id$="ddlDepOrgano"]').val();
if ($ddlDepOrgano != "") {
var jsonData = $.ajax({
type: "POST",
url: '/services/eleaveService.asmx/GetChartData',
data: "{'depid':'" + $ddlDepOrgano + "'}",
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: OnSuccess_getOrgData,
error: OnErrorCall_getOrgData
});
function OnSuccess_getOrgData(repo) {
var data = new google.visualization.DataTable(jsonData);
data.addColumn('string', 'Name');
data.addColumn('string', 'Manager');
data.addColumn('string', 'ToolTip');
var response = repo.d;
for (var i = 0; i < response.length; i++) {
var row = new Array();
var Pos_Name = response[i].Pos_Name;
var Pos_Level = response[i].Pos_Level;
var Emp_Name = response[i].Emp_Name;
var Pos_ID = response[i].Pos_ID;
var Emp_ID = response[i].Emp_ID;
data.addRows([[{
v: Emp_ID,
f: Pos_Name
}, Pos_Level, Emp_Name]]);
}
var chart = new google.visualization.OrgChart(document.getElementById('chart_div'));
chart.draw(data,{ allowHtml: true });
}
function OnErrorCall_getOrgData() {
console.log("something went wrong ");
}
} else {
bootbox.alert("Invalid Department Name please try again.");
}
e.preventDefault();
});
}
according to the data format, Column 1 should be the ID of the manager, which is used to build the tree...
Column 1 - [optional] The ID of the parent node. This should be the unformatted value from column 0 of another row. Leave unspecified for a root node.
looking at the data table image posted, this should be in column --> Mngr_ID
as such, recommend the following changes when loading the data...
for (var i = 0; i < response.length; i++) {
var row = new Array();
var Pos_Name = response[i].Pos_Name;
var Emp_Name = response[i].Emp_Name;
var Emp_ID = response[i].Emp_ID;
var Mngr_ID = response[i].Mngr_ID;
data.addRow([
{
v: Emp_ID,
f: Pos_Name
},
Mngr_ID,
Emp_Name
]);
}

Wordpress custom JSON feed with multiple categories

Good morning to all.
It is possible to have a custom JSON feed with the last 10 posts from all categories with 10 or more posts published?
I'm doing that with a loop over all categories with 10 or more posts published using the JSON API plugin for wordpress by dphiffer
So if I have 14 categories I will do 140 requests and overload the server.
I'm searching for a way to do that with 1 or 2 requests. Like first request to get the categories indexes with 10 or more posts and the second request with all the data.
Thanks
Here is the code i've developed so far:
<script type="text/javascript">
var slug = 'news'; // Main categorie
var maxLength = 10; // Total of articles per categorie
var wpurl = 'http://wpurl.com'; // WP URL
var loadedValue, loadedTotal;
var categories = new Array();
var newsData = new Array();
//Get main categorie index by slug
$.ajax({
url: wpurl+'/?json=get_category_index',
type: 'GET',
dataType: 'jsonp',
success: function(data){
for (i = 0; i < data.categories.length; i++) {
var cat = data.categories[i];
if(cat.slug == slug) {
get_all_categories(cat.id);
}
}
},
error: function(data){
console.log(data);
}
});
//Get all sub-categories from an categorie slug
function get_all_categories(cat_index) {
$.ajax({
url: wpurl+'/?json=get_category_index&parent='+cat_index,
type: 'GET',
dataType: 'jsonp',
success: function(data){
for (i = 0; i < data.categories.length; i++) {
var cat = data.categories[i];
//Check if categorie have 10 (maxLength) or more posts. If so push it to array (categories)
if(cat.post_count >= maxLength) {
categories.push({
'index': cat.id,
'title': cat.title
});
}
}
},
error: function(data){
console.log(data);
}
}).done(function() {
//Set loading
var totalItem = categories.length*maxLength;
var actualItem = 0;
var loaded = 0;
for(var i=1; i<=categories.length; i++){
prepareCategory(categories[i-1].index, maxLength, i);
function prepareCategory(categorieIndex, maxLenght, count) {
var content;
$.ajax({
url: wpurl+'/api/get_category_posts?category_id='+categorieIndex+'&count='+maxLenght+'&status=publish',
type: 'GET',
dataType: 'jsonp',
success: function(data){
for (e = 0; e < data.posts.length; e++) {
//Loading percent
actualItem++;
loaded = (actualItem/totalItem)*100;
document.getElementById('loadingBox').innerHTML = 'Loading: '+Math.round(loaded)+'%';
//Post data
var post = data.posts[e];
var title = post.title;
var thumb = post.thumbnail_images.appthumb.url || 'content/images/noimage.png';
var newContent = '<div class="new"><img src="'+thumb+'" width="320" height="164"><div class="new_description">'+title+'</div></div>';
var newId = 'cat'+count+'new'+(e+1);
newsData.push({
'id': newId,
'content':newContent
});
}
},
error: function(data){
console.log(data);
}
});
}
}
});
};
function loaded() {
if (window.localStorage.length != 0)
{
localStorage.clear();
setGlobalStorageAndRedirect();
} else {
setGlobalStorageAndRedirect();
}
function setGlobalStorageAndRedirect() {
localStorage.setItem('postPerCat', maxLength);
localStorage.setItem('catNumbs', categories.length);
localStorage.setItem('wpurl', wpurl);
localStorage.setItem('categoriesArray', JSON.stringify(categories));
localStorage.setItem('newsData', JSON.stringify(newsData));
window.location="main.html";
}
}
</script>

Save Data with KnocloutJS viewmodel to server

I want to save my ViewModel to my SQL server. The standard knockout ko.toJSON(viewModel) keeps giving me an undefined error, so after some digging i found this Question, but still keeps giving me undefined.
Here is the code for my viewmodel, this is just a currency conversion table that gets the Conversion Rate between 2 currencies.
//ko Event Handler for datepicker.js
ko.bindingHandlers.datepicker = {
init: function (element, valueAccessor, allBindingsAccessor) {
//initialize datepicker with some optional options
var options = allBindingsAccessor().datepickerOptions || {};
$(element).datepicker(options).on("changeDate", function (ev) {
var observable = valueAccessor();
observable(ev.date);
});
},
update: function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
$(element).datepicker("setValue", value);
}
};
//Currency Model Definition
var currency = function (data) {
var self = this;
self.DateCreated = ko.observable(formatJsonDate(data.DateCreated));
self.CurrencyFrom = ko.observable(data.CurrencyFrom);
self.CurrencyTo = ko.observable(data.CurrencyTo);
self.ConversionRate = ko.observable(data.ConversionRate);
//Yhoo Finance API
ko.computed(function () {
var from = self.CurrencyFrom(),
to = self.CurrencyTo();
if (!from || !to) {
self.ConversionRate("N/A");
return;
}
getRate(from, to).done(function (YahooData) {
console.log("got yahoo data for [" + from + "," + to + "]: ", YahooData);
self.ConversionRate(YahooData.query.results.row.rate);
});
});
}
var NewDate = new Date().getFullYear() + '-' + ("0" + (new Date().getMonth() + 1)).slice(-2) + '-' + new Date().getDate();
var CurrencyModel = function (Currencies) {
var self = this;
self.Currencies = ko.observableArray(Currencies);
self.AddCurrency = function () {
self.Currencies.push({
DateCreated: NewDate,
CurrencyFrom: "",
CurrencyTo: "",
ConversionRate: ""
});
};
self.RemoveCurrency = function (Currency) {
self.Currencies.remove(Currency);
};
self.Save = function () {
$.ajax({
url: "#",
contentType: 'application/json',
data: ko.mapping.toJSON(CurrencyModel),
type: "POST",
dataType: 'json',
success: function (data) {
//I get undefined....
alert(ko.mapping.toJSON(CurrencyModel));
},
error: function (data) { alert("error" + data); }
});
}
$.ajax({
url: "CurrencyConfiguration.aspx/GetConfiguredCurrencies",
data: '{}',
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "JSON",
timeout: 10000,
success: function (Result) {
// callback(Result);
var MappedCurrencies =
$.map(Result.d,
function (item) {
getRate(item.CurrencyFrom, item.CurrencyTo);
return new currency(item);
}
);
self.Currencies(MappedCurrencies);
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
};
function formatJsonDate(jsonDate) {
var FormatDate = new Date(parseInt(jsonDate.substr(6)));
var Output = FormatDate.getFullYear() + '-' + ("0" + (FormatDate.getMonth() + 1)).slice(-2) + '-' + FormatDate.getDate();
return (Output);
};
function getRate(from, to) {
return $.getJSON("http://query.yahooapis.com/v1/public/yql?q=select%20rate%2Cname%20from%20csv%20where%20url%3D'http%3A%2F%2Fdownload.finance.yahoo.com%2Fd%2Fquotes%3Fs%3D" + from + to + "%253DX%26f%3Dl1n'%20and%20columns%3D'rate%2Cname'&format=json&callback=?");
}
function callback(data) {
if (viewModel) {
// model was initialized, update it
ko.mapping.fromJS(data, viewModel);
} else {
// or initialize and bind
viewModel = ko.mapping.fromJS(data);
ko.applyBindings(viewModel);
}
}
$('#Date').datepicker();
$(document).ready(function () {
var VM = new CurrencyModel();
ko.applyBindings(VM);
})
data: ko.mapping.toJSON(CurrencyModel)
You are trying to JSONify the definition not the actual instance
Isn't the method that you want to use:
ko.toJSON
rather than off the mapping object?