Change name of card on Trello with API by Javascript - javascript

I have this code in Javascript to modify the name of a Trello card through its API, and I do not get it, any ideas?
Documentation API Trello: https://developers.trello.com/v1.0/reference#cardsid-1
Code:
var onAuthorize = function() {
updateLoggedIn();
$("#output").empty();
Trello.members.get("me", function(member){
$("#fullName").text(member.fullName);
var id= "5ab7c3c631a2019c50b701c8";
//Change name
Trello.put('/boards/me/cards/5ab7c3c631a2019c50b701c8/name?value=nombrecito',function () {alert("funciona bien")}, function(err) {alert( "mal")});
});
};
var updateLoggedIn = function() {
var isLoggedIn = Trello.authorized();
$("#loggedout").toggle(!isLoggedIn);
$("#loggedin").toggle(isLoggedIn);
};
var logout = function() {
Trello.deauthorize();
updateLoggedIn();
};
Trello.authorize({
interactive:false,
success: onAuthorize
});
$("#connectLink")
.click(function(){
Trello.authorize({
type: "popup",
success: onAuthorize
})
});
$("#disconnect").click(logout);
The error I get is [object Object]
I have also tried with this URL:'cards/5ab7c3c631a2019c50b701c8/name?value=nombrecito'

It looks like your Trello.put URL is a little off.
Fix the Trello.put with...
Trello.put("/boards/mecards/5ab7c3c631a2019c50b701c8/name?value=nombrecito", function () {}, function(err) {alert(err)});

Have you tried the live example on the documentation page? It's not that complicated and something like this.
const API_KEY = 'your key';
const TOKEN = 'your token';
let id = 'your trello card id';
let newName = 'a new name what you want';
var data = null;
var xhr = new XMLHttpRequest();
xhr.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
console.log(this.responseText);
}
});
xhr.open("PUT", "https://api.trello.com/1/cards/"+id+"?name="+newName+"&key="+API_KEY+"&token="+TOKEN);
xhr.send(data);
I've tested with my own cards and it works very well.

Related

Manage bootstrap modal with javascript

Good evening guys,
I program a symfony website by using webpack encore bundle to manage js & css.
I used to work with jquery which is quite simple, but would like to evolve to pure javascript.
I try to translate the following code in javascript :
<html>
<button class="exercice-class" data-id="x">exercice button</button>
</html>
when an user click on the "exercice button", i want to get the value of data-id to generate an URL
<script>
$(function() {
$('.exercice-class').on("click", function(e) {
e.preventDefault();
let id = $(this).data("id");
let url = "../exercice-class/" + id + "/";
$.get(url, function(data){
$(".container-fluid").append(data);
$('#showModal').modal('show');
});
});
});
</script>
Then i get the content of the URL and add it to the modal window
What I want to do first is to open a modal window by using a variable as a parameter.
Second question, I would like to get data from a modal (using a form) and send them to a database. I read things about asynchronous request by it's not really clear for me, i'm looking for something close to ajax request.
Thank you in advance.!
Juuk
here is a small example, you can test it
var classbutton = document.querySelector('.exercice-class');
classbutton.addEventListener('click', (e) => {
e.preventDefault();
let id = element.getAttribute('id');
let url = "../exercice-class/" + id + "/";
let requete = new XMLHttpRequest();
requete.open('GET', url);
requete.send();
requete.onload = function() {
if (requete.readyState === XMLHttpRequest.DONE) {
if (requete.status === 200) {
let reponse = requete.response;
document.querySelector('.container-fluid').append(reponse);
document.querySelector('#showModal').showModal();
}
else {
}
}
}
});
Thanks for your response! i tried your code and work on it...
This is what i did :
let httpRequest = new XMLHttpRequest();
httpRequest.open("GET", url);
httpRequest.send();
httpRequest.onload = function (){
if (httpRequest.readyState === XMLHttpRequest.DONE){
if (httpRequest.status === 200){
let httpResponse = httpRequest.response;
console.log(httpResponse);
}
}
}
It seems that fetch is a newer way to work with data since vanilla.
I did the same thing we tried to do before and i succeeded to get data.
document.addEventListener('click', function (event) {
if (!event.target.closest('.exercice-class')){
return null;
}
else {
event.preventDefault();
let exercice = event.target.closest(".exercice-class");
let dataAttribute = exercice.getAttribute('data-id');
let url = "../exercice-class/" + dataAttribute + "/";
fetch(url)
.then(function (response) {
return response.text();
})
.then(function (data) {
console.log(data)
})
.catch(function (error) {
console.log(error);
});
}
});
In reality i get the same result with the two solutions.. the problem is that i get "data" i can't exploit...
Imagine i use the second example :
if i try to do :
.then(function (data) {
let exerciceData = data.getElementById("#adiv");
document.querySelector('container-fluid').append(exerciceData);
document.querySelector('showModal').show();
"exerciceData" can't be used.
Modal just don't open.
Thank for your help.

Cannot read property toLowerCase of undefined

So, I am working on an audio part where I fetch my words from a JSON file and when I show them on my front-end it should onclick on the audio button fetch the word from the server and create the audio... But I keep on getting Cannot read property toLowerCase of undefined and I cannot seem to find the error.
let's start with the variables I declared:
var MEDIAARRAY;
var WORDS;
var audioArray;
var audio = new Audio();
var LANGUAGE;
var SOUNDARRAY;
The piece of code (I took over the code given as answer and it helped me a bit further so I decided to edit the question with the code I have right now).
$(document).ready(function () {
getFileArray();
});
$(document).on("click", ".sound", function () {
getFileArray("SomeLanguage");
var foundID = MEDIAARRAY.audio.lowercase.indexOf($(this).parent().find('.exerciseWord').val().toLowerCase() + '.mp3');
var currentVal = $(this).parent().find('.fa-volume-up');
if (foundID > -1) {
var audio = new Audio();
audio.src = 'TheServerURL' + MEDIAARRAY.audio.path + MEDIAARRAY.audio.files[foundID] + '';
audio.play();
}
});
The line where the error occurs:
var foundID = MEDIAARRAY.audio.lowercase.indexOf($(this).parent().find('.exerciseWord').val().toLowerCase() + '.mp3');
The button where the class sound is appended to:
function getAudioForWords() {
var audioBtn = $('<a/>', {
'class': 'sound btn btn-primary'
}).html('<i class="fa fa-volume-up"></i>');
return audioBtn;
}
the code where class exerciseWord gets append to:
var wordCol = $('<div>', {
class: 'col-md-9 ExerciseWordFontSize exerciseWord',
'id': 'wordInput[' + ID123 + ']',
text: exercise.word
});
and the piece of code that gets the fileArray, but most likely will be useless for you to inspect, but it was related to my code so... yeah.
function getFileArray(param)
{
var request = {
language: param
};
$.ajax(
{
url: "TheServerURL",
type: "POST",
async: true,
data: request,
dataType: 'json',
}).done(function (response)
{
console.log(response)
MEDIAARRAY = response;
audioArray = response.audio;
console.log(audioArray);
});
}
The error states varialble MEDIAARRAY remains uninitialized somewhere in your code flow. See if following takes you close to the resolution
You have not mentioned at what point getFileArray function is called. Call to getFileArray function is critical because that is when MEDIAARRAY is assigned value.
Ensure getFileArray is called before you access any propery of MEDIAARRAY.
Ensure your API always returns object which contains audio property.
Example,
$(document).on("click", ".sound", function () {
//Ensure you supply parameter value to your function(i.e. value of the element you take user input from)
getFileArray("SomeLanguage");
var foundID = MEDIAARRAY.audio.lowercase.indexOf($(this).parent().find('.exerciseWord').val().toLowerCase() + '.mp3');
var currentVal = $(this).parent().find('.fa-volume-up');
if (foundID > -1) {
var audio = new Audio();
audio.src = 'TheServerURL' + MEDIAARRAY.audio.path + MEDIAARRAY.audio.files[foundID] + '';
audio.play();
}
});

How to download a file that I have chosen from Google Picker API?

I am implementing the Google Picker in a PHP site. I am able to get the file id from the Google Picker API and also I can download the file using JavaScript. Following is my callback function called in setCallback(pickerCallback) function.
function pickerCallback(data) {
if (data.action == google.picker.Action.PICKED) {
var fileId = data.docs[0].id;
document.getElementById('googleFileId').value = fileId;
var name = data.docs[0].name;
var url = data.docs[0].url;
var accessToken = gapi.auth.getToken().access_token;
var request = new XMLHttpRequest();
request.open('GET', 'https://www.googleapis.com/drive/v2/files/' + fileId);
request.setRequestHeader('Authorization', 'Bearer ' + accessToken);
request.addEventListener('load', function() {
var item = JSON.parse(request.responseText);
window.open(item.webContentLink,"_self"); //Download file in Client Side
});
request.send();
}
var message = 'File ID of choosen file : ' + fileId;
document.getElementById('result').innerHTML = message;
}
I can pass the file id to PHP, but to download the file I have to authenticate again. Can any one help in how to proceed with file download in PHP ?
There is a Manage Downloads help in Google Developers page but it is not working for me https://developers.google.com/drive/web/manage-downloads.
Found a question similar to this one but no answers to how to download the file in backend Download file right after picked file from google picker.
You have to implement a callback for the pick action. Take a look at my implementation:
var buildPicker = function(parentId) {
var pickerCallback = function(data) {
if (data[google.picker.Response.ACTION] === google.picker.Action.PICKED && data.viewToken[0] !== 'upload') {
var docs = data[google.picker.Response.DOCUMENTS];
for (var d = 0; d < docs.length; d++) {
downloadFile(docs[d].id);
}
}
};
GAuth.getToken().then(function(token) {
var picker = new $window.google.picker.PickerBuilder()
.addView(new google.picker.DocsUploadView().setParent(parentId))
.addView(new google.picker.DocsView().setParent(parentId).setIncludeFolders(true))
.setDeveloperKey(apiKey)
.setOAuthToken(token.access_token)
.setCallback(pickerCallback);
picker.enableFeature(google.picker.Feature.MULTISELECT_ENABLED);
picker.build().setVisible(true);
});
};
var downloadFile = function(fileId) {
getFile(fileId).then(function(file) {
var downloadUrl;
if (angular.isDefined(file.exportLinks)) {
downloadUrl = file.exportLinks['application/pdf'];
} else {
downloadUrl = file.webContentLink;
}
var $idown;
var makeiFrame = function(url) {
if ($idown) {
$idown.attr('src', url);
} else {
$idown = $('<iframe>', {
id: 'idown',
src: url
}).hide().appendTo('body');
}
};
makeiFrame(downloadUrl);
});
};
// Implemented with https://github.com/maximepvrt/angular-google-gapi. But any other implementation will be fine as well
var getFile = function(fileId) {
var parameters = {
'fileId': fileId
};
return GApi.executeAuth('drive', 'files.get', parameters);
};
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

How to validate a data insert with mongoDB

how can i validate after data insert and saving data to database if data already in a database send user to error alert message.
how can i do this with express REST server?
this is my "POST" on client side
button.addEventListener('click', function(e) {
var service_ = service.value;
var amount_ = amount.value;
var name_ = name.value;
var phone_ = phone.value;
var reminder_ = reminder.value;
if (start_pick < end_pick) {
var jsondata = [{
start_time : new Date(start_pick),
end_time : new Date(end_pick),
service : service_,
amount : amount_,
client_phone : phone_,
client_name : name_,
reminder : reminder_
}];
var xhr = Titanium.Network.createHTTPClient();
xhr.setTimeout(10000);
xhr.open("POST", "http://127.0.0.1:3000/collections/appoinments");
xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
xhr.send(JSON.stringify(jsondata));
xhr.onerror = function() {
Titanium.API.info("Error in connecting to server !!");
alert("Error on connecting to server, Please try again");
};
xhr.onload = function() {
windowPayment.close();
}
this is my POST on server
app.post('/collections/:collectionName', function(req, res, next) {
req.collection.insert(req.body, {}, function(e, results){
if (e) return next(e)
res.send(results)
})
})
how can i do this.any help?

Get LinkedIn Access Token with OAuthSimple in Javascript

I'm using OAuthSimple in Javascript with PIN based authentication (OOB flow).
We are developing an HTML5 app which lives inside a mobile device's native wrapper using PhoneGap. There's not ANY server side (no URL at all), all requests are sent using the mobile device as a proxy.
So far I managed to:
- Get Request Token
- Redirect user to authorization page
- Got authorization PIN
I need sample code that shows how to get an Access Token using OAuthSimple Javascript library.
Any help will be appreciated. Thanks!
Not sure if you are the same person who posted on our forums recently (see post here https://developer.linkedin.com/forum/oauthsimple-request-access-token), but I replied with demo code on how to do just that using OAuthSimple.
The actual sample code can be found here: https://gist.github.com/efc88a38da25ff4e9283
If you need any help using it, don't hesitate to reach out!
-Jeremy
This will create a phonegap linkedIn login, its just a worked around code though, but this works atleast for me
var consumer_key = "key";
var shared_secret = "secrete";
self.oauth = OAuthSimple(consumer_key, shared_secret); var linkedInScope = 'r_basicprofile r_emailaddress w_messages r_network';
var url = self.oauth.sign({action: "GET", path: "https://api.linkedin.com/uas/oauth/requestToken", parameters: {scope: linkedInScope, oauth_callback: "oob"}}).signed_url;
var request = 'requestToken';
var linkedInObj = new Object;
function linkedInWorkAround(url,request,data){
var callType = 'GET';
var xhr = $.ajax({
url : url,
beforeSend : function(){
$.mobile.loading( 'show' );
if(request == 'linkedIn_login'){
callType = 'POST';
}
},
timeout : 8000,
data : data,
type : callType,
success: function(r){
$.mobile.loading( 'hide' );
if(request == 'requestToken'){
var oauthRes = r.split('&');
$.each(oauthRes, function(k,v){
var resObj = v.split('=')
linkedInObj[resObj[0]] = resObj[1];
});
url = 'https://www.linkedin.com/uas/oauth/authenticate?scope='+linkedInScope+'&oauth_token='+linkedInObj.oauth_token;
request = 'oauth_token';
linkedInWorkAround(url,request);
}
else if(request == 'oauth_token'){
var accessCode = $(r).find('.access-code');
if(accessCode.size()){
self.oauth.reset();
var pin = $(r).find('.access-code').text();
url = self.oauth.sign({action: "GET", path: "https://api.linkedin.com/uas/oauth/accessToken", parameters: {scope: linkedInScope, oauth_verifier: pin}, signatures: linkedInObj}).signed_url;
request = 'accessToken';
linkedInWorkAround(url,request);
}
else{
$('.custom-linkedIn').remove();
var cloneIn = $(r).find('form').addClass('custom-linkedIn').clone();
$('a,span,select,.duration-label,.access',cloneIn).hide();
$('#pageLinkedIn .errMsgHolder').after(cloneIn)
$('#session_key-oauthAuthorizeForm').textinput();
$('#session_password-oauthAuthorizeForm').textinput();
$('input[type=submit]').button();
$('form.custom-linkedIn').submit(function(){
$('.errMsgHolder').hide().text('');
url = 'https://www.linkedin.com/uas/oauth/authorize/submit';
request = 'linkedIn_login';
var data = $(this).serialize();
linkedInWorkAround(url,request,data);
return false;
});
}
}
else if(request == 'linkedIn_login'){
self.oauth.reset();
var pin = $(r).find('.access-code').text();
url = self.oauth.sign({action: "GET", path: "https://api.linkedin.com/uas/oauth/accessToken", parameters: {scope: linkedInScope, oauth_verifier: pin}, signatures: linkedInObj}).signed_url;
request = 'accessToken';
linkedInWorkAround(url,request);
}
else if(request == 'accessToken'){
var oauthRes = r.split('&');
self.oauth.reset();
$.each(oauthRes, function(k,v){
var resObj = v.split('=')
linkedInObj[resObj[0]] = resObj[1];
});
url = self.oauth.sign({action: "GET", path: "https://api.linkedin.com/v1/people/~/email-address", signatures: linkedInObj}).signed_url;
request = 'getResultLinkedIn';
linkedInWorkAround(url,request);
}
else if(request == 'getResultLinkedIn'){
$('body').css({opacity:0});
var userLIemail = ($('#session_key-oauthAuthorizeForm').size()) ? $('#session_key-oauthAuthorizeForm').val() : $(r).text();
}
},
error : function(a,b,c){
alert('err')
console.log(a,b,c)
self._cs(a)
$.mobile.loading( 'hide' );
if(a.statusText.toLowerCase() == 'unauthorized'){
$('.errMsgHolder').show().text('The email address or password you provided does not match our records');
}
}
})
}
linkedInWorkAround(url,request);

Categories

Resources