400 bad request on twitter oauth request token - javascript

I am trying to send a POST request to https://api.twitter.com/oauth/request_token. The response is 400 Bad Request with no info. Here is my code:
onTwitterRegisterClick: function() {
var callbackURL = 'http://test.loc:1841/',
consumerKey = 'm59nSEhyF3Zp4gVdpDzq6CIPp',
consumerSecret = 'Wou436sq4LUXwO1ajE2egdMdAfV9LtPLkG4JlCF4Yi5YpcrnTF',
requestTokenURL = 'https://api.twitter.com/oauth/request_token';
var time = new Date().valueOf().toString(),
oauth_nonce = makeRandomString(32);
var paramsForSignature = [
encodeURIComponent('oauth_callback') + '=' + encodeURIComponent(callbackURL),
encodeURIComponent('oauth_consumer_key') + '=' + encodeURIComponent(consumerKey),
encodeURIComponent('oauth_nonce') + '=' + encodeURIComponent(oauth_nonce),
encodeURIComponent('oauth_signature_method') + '=' + encodeURIComponent('HMAC-SHA1'),
encodeURIComponent('oauth_timestamp') + '=' + encodeURIComponent(time),
encodeURIComponent('oauth_version') + '=' + encodeURIComponent('1.0')
];
var paramsForSignatureStr = paramsForSignature.join('&');
var signatureBaseString = 'POST&' + encodeURIComponent(requestTokenURL) + '&' + encodeURIComponent(paramsForSignatureStr);
//alert(signatureBaseString);
var signature = btoa(CryptoJS.HmacSHA1(signatureBaseString, consumerSecret + '&'));
//var signature = prompt('hmac-sha1 of signatureBaseString=' + CryptoJS.HmacSHA1(signatureBaseString, consumerSecret + '&'));
//alert(signature);
Ext.Ajax.request({
method: 'POST',
url: requestTokenURL,
async: false,
headers:{
Authorization: 'OAuth oauth_callback="' + encodeURIComponent(callbackURL) + '", ' +
'oauth_consumer_key="' + consumerKey + '", ' +
'oauth_nonce="' + oauth_nonce + '", ' +
'oauth_signature="' + encodeURIComponent(signature) + '", ' +
'oauth_signature_method="HMAC-SHA1", ' +
'oauth_timestamp="' + time + '", ' +
'oauth_version="1.0"'
},
success: function(response, opts) {
alert(response.responseText);
},
failure: function (response, opts) {
alert(response.responseText);
}
})
}
I read the official guide a few times. What am I doing wrong?
I only noticed the value of the variable "signature" is like "YTg5ZmI2ZmEwMWU4MDkzMjlkZmEzMmVmMmVmYzgxMjlmZTJlNDdlZQ==" and is not like "tnnArxj06cWHq44gCs1OSKk/jLY=" (as in the official guide) because the function btoa() work with String and with not Integer.

try changing the async: false to true

Related

How to Add link to message

I was trying to make a notification with line notify but I dont know how to insert a command that puts a link from my google sheet to the message of the notification
// Line Notify
function onFormSubmit() {
var form = FormApp.openById('1ELczQ-uW1mauQrHFBpHK2pQnCCkvPf_4Nq-DPqM4nMw');
var fRes = form.getResponses();
var formResponse = fRes[fRes.length - 1];
var itemResponses = formResponse.getItemResponses();
var link = shape.getLink();
if (link != null && link.getLinkType() == SlidesApp.LinkType.URL) {
Logger.log('Shape has link to URL: ' + link.getUrl());
}
var msg = 'Electric Forklift Incentive'
+ ' \n' + itemResponses[5].getItem().getTitle() + ': ' + itemResponses[5].getResponse()
+ ' \n' + itemResponses[0].getItem().getTitle() + ': ' + itemResponses[0].getResponse()
+ ' \n' + itemResponses[1].getItem().getTitle() + ': ' + itemResponses[1].getResponse()
+ ' \n' + itemResponses[2].getItem().getTitle() + ': ' + itemResponses[2].getResponse()
+ ' \n' + itemResponses[3].getItem().getTitle() + ': ' + itemResponses[3].getResponse()
+ ' \n' + itemResponses[4].getItem().getTitle() + ': ' + itemResponses[4].getResponse()
+ ' \n' + itemResponses[4].getItem().getTitle() + ': ' + itemResponses[4].getResponse()
sendLineNotify(msg);
}
function sendLineNotify(message) {
var token = ["DdiU5tUykpSRpxRVqmEnM7ul3hcE3NEvc6Vzwknyzo7"];
var options = {
"method": "post",
"payload": "message=" + message,
"headers": {
"Authorization": "Bearer " + token
}
};
UrlFetchApp.fetch("https://notify-api.line.me/api/notify", options);
}
}

Calculate age via JS (ASP.NET MVC)

I have this code to get data from back -end
$('#display').click(function () {
var vacancyId = $("#vacancy").val();
var model = {
vacancyId: vacancyId
};
$.ajax({
url: '#Url.Action("Links", "Questions")',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(model),
type: 'POST',
dataType: 'json',
processData: false,
success: function (data) {
var question2 = data;
for (var i = 0; i <= question2.length - 1; i++) {
var videoHTML = '<div style="width:100%;overflow-y: scroll;background:white;height:72%">' + '<div style="float:left; width:50%;height:296px;border-style:solid;margin-bottom:10px;">' +
'<video style="width:100%;height:290px; object-fit: contain;" controls>';
videoHTML += '<source src="' + document.location.origin + "/uploads/" + question2[i].Linkes + ".webm" + '" type="video/webm">';
videoHTML += '</video>' + '</div>' + '<div style="float:right;width:48%;text-align:center;height:296px;border-style:solid;padding-top:30px;">' + '<div>' + '<b>' + "Ф.И.О: " + '</b>' + '<b>' + question2[i].FIO + '</b>' + '</div>' + '<div>' + '<b>' + "Город: " + '</b>' + '<b>' + question2[i].City + '</b>' + '</div>' + '<div>' + '<b>' + "Город: " + '</b>' + '<b>' + question2[i].Vozrast + '</b>' + '</div>'+'</div>'+'</div>';
$(".videolist").append(videoHTML);
}
}
});
});
This one return date of birthday '<b>' + question2[i].Vozrast + '</b>'
I need to display age.
How I can do this on client-side?
You can do this in server side or client side depend on you.
If you like to do it in client side and Vozrast type is Date, so you can use third libraries to do this e.g. Moment.Js
var years = moment().diff(Vozrast, 'years');
var days = moment().diff(Vozrast, 'days');
I do it like this on client side
var today = new Date();
var yyyy = today.getFullYear();
Get year like this
And get age like this
(yyyy - question2[i].Vozrast)

execute javascript after for loop

I have a for loop that gets data from lists in subsites to build a html list on the page using an async ajax request, this works, but i wish to order the list after it has been generated to show the list in alphabetical order. I am on a learning curve with javascript so any help is appreciated. I need to run the sortProjects function after the onWebsLoaded function is complete.
function onWebsLoaded(sender, args) {
for (var i = 0; i < this.webs.get_count(); i++)
{
client = "";
var title = this.webs.itemAt(i).get_title();
var desc = this.webs.itemAt(i).get_description();
var url = this.webs.itemAt(i).get_serverRelativeUrl();
id = (title).replace(/\ /g, "");
getProjectProperties(url, title, desc, client, id);
}
}
function sortProjects () {
tinysort('ul#projectstable>li');
}
function getProjectProperties (url, title, desc, client, id) {
$.ajax({
url: url + "/_api/web/lists/getbytitle('Project Properties')/items('1')",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
client = data.d.Title;
$('#projectstable').append("<li id='" + id + "' class='ms-ListItem'><a href='" + url + "'><span id='" + id + "Client' class='ms-ListItem-primaryText'>" + title + "</span><span class='ms-ListItem-secondaryText'>" + client + "</span><span class='ms-ListItem-tertiaryText'>" + desc + "</span></a></li>");
},
error: function () {
$('#projectstable').append("<li id='" + id + "' class='ms-ListItem'><a href='" + url + "'><span id='" + id + "Client' class='ms-ListItem-primaryText'>" + title + "</span><span class='ms-ListItem-secondaryText'>" + client + "</span><span class='ms-ListItem-tertiaryText'>" + desc + "</span></a></li>");
}
});
}
You can amend your logic so that you store an array of the promises returned from the $.ajax() calls. You can then apply() that array to $.when and call sortProjects(). Try this:
function onWebsLoaded(sender, args) {
var requests = [];
for (var i = 0; i < this.webs.get_count(); i++) {
client = "";
var title = this.webs.itemAt(i).get_title();
var desc = this.webs.itemAt(i).get_description();
var url = this.webs.itemAt(i).get_serverRelativeUrl();
id = (title).replace(/\ /g, "");
requests.push(getProjectProperties(url, title, desc, client, id));
}
$.when.apply($, requests).done(sortProjects);
}
function sortProjects () {
tinysort('ul#projectstable>li');
}
function getProjectProperties (url, title, desc, client, id) {
// note 'return' below
return $.ajax({
url: url + "/_api/web/lists/getbytitle('Project Properties')/items('1')",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
client = data.d.Title;
$('#projectstable').append("<li id='" + id + "' class='ms-ListItem'><a href='" + url + "'><span id='" + id + "Client' class='ms-ListItem-primaryText'>" + title + "</span><span class='ms-ListItem-secondaryText'>" + client + "</span><span class='ms-ListItem-tertiaryText'>" + desc + "</span></a></li>");
},
error: function () {
$('#projectstable').append("<li id='" + id + "' class='ms-ListItem'><a href='" + url + "'><span id='" + id + "Client' class='ms-ListItem-primaryText'>" + title + "</span><span class='ms-ListItem-secondaryText'>" + client + "</span><span class='ms-ListItem-tertiaryText'>" + desc + "</span></a></li>");
}
});
}

400 bad request while passing object and value to url

I know how to pass data in url in json or with plain parameters but this is something different
see the below image :-
http://www.tiikoni.com/tis/view/?id=23d9b98
My api Url /geniedoc/api/doctor/Search
as we can see one thing is in object and two paramater is simply passing
can you suggest me a ajax call?
my ajax call
function getNewSlotContent(startIndex, totalRows) {
var skipindex = 0;
if (startIndex > 1) {
skipindex = totalRows;
}
var totalrows = totalRows + 10;
var searchByName = document.getElementById("searchByName").value;
var selectedSpeciality = document.getElementById("searchByName").value;
if (selectedSpeciality != null || selectedSpeciality != "") {
selectedSpeciality = encodeURIComponent(selectedSpeciality);
}
$("#preloader").addClass("pageload");
$("#preloader").show();
var dataString = '{"firstName":"'+ searchByName + '","start_index":"' + skipindex + '","rows":"' + totalrows +'"}';
console.log(dataString);
$.ajax({
type: 'POST',
url : '/geniedoc/api/doctor/search',
data: dataString,
contentType: 'application/json',
dataType: 'json',
headers: {'Content-Type':'application/json'},
timeout: 100000,
success: function(data) {
var op = "";
for (doctor in data.response.rows) {
op += '<div class="post-sec">';
op += '<img src="/geniedoc/ajax/data/displayImage?fileName=' + data.response.rows[doctor].profilePicId + '" alt="">';
if (data.response.rows[doctor].prefix == null) {
data.response.rows[doctor].prefix = "";
}
op += '<a target="_blank" href="/doctor/' + data.response.rows[doctor].seo_name + '/' + data.response.rows[doctor].idKey + '" class="title"> ' + data.response.rows[doctor].prefix + ' ' + data.response.rows[doctor].firstame + ' ' + data.response.rows[doctor].last_name + '</a>';
op += '<span class="date">' + data.response.rows[doctor].speciality_id + '</span>';
op += '</div>';
op += '<div class="clear"></div>';
}
$("#preloader").hide();
$("#preloader").removeClass("pageload");
$("#doctor-data").html(op);
},
error: function(e) {
console.log("ERROR: ", e);
},
done: function(e) {
console.log("DONE");
}
});
}
Modify your dataString like this :
var dataString = {
"firstName":searchByName,
"start_index": skipindex,
"rows": totalrows
};

How to set CRUD working in Kendo?

How to set CRUD working in Kendo? Update and read is ok, but create not. This is my code for this part:
create: {
url: function (data) {
return $("#gatewayPath").data("value") + "odata/ods/ProcessProductionPerformanceMovements";
},
dataType: "json",
type: "POST",
beforeSend: function (x) {
var auth = $("#authenticationType").data("value") + " " + $("#authenticationToken").data("value");
x.setRequestHeader("Authorization", auth);
}
},
and in parameterMap I have:
if (operation === "create") {
return '{ "_Key": "' + data._Key +
'", "Comment": "' + data.Comment +
'","MovementType": "' + data.MovementType +
((data.Unit) ? '","_UnitKey": "' + data.Unit._Key: "") +
((data.Material) ? '","_MaterialKey": "' + data.Material._Key: "") +
'","MaterialLotID": "' + data.MaterialLotID +
'","Status": "' + data.Status +
'","Quantity": "' + data.Quantity +
'","Description": "' + data.Description +
'","_UnitKey": "' + data._UnitKey +
'","_ProdPerfHeaderKey": "' + data._ProdPerfHeaderKey +
'","StockType": "' + data.StockType +
'","StockIndicator": "' + data.StockIndicator +
'","SAPStorageLocation": "' + data.SAPStorageLocation +
'"}';
}
There is a create example here on telerik.com.
var dataSource = new kendo.data.DataSource({
transport: {
/* the other CRUD settings are ommitted for brevity */
create: function (e) {
// batch is disabled
// generate appropriate data item ID and save the new items to the original datasource
e.data.my_ID_field_name = 123;
// ...
// on success return the new data items with IDs
e.success(e.data);
// on failure
//e.error("XHR response", "status code", "error message");
}
} });

Categories

Resources