Can I trigger a Power Automate workflow from custom JavaSript? - javascript

How can I start/trigger any flow from my custom JavaScript code?
I am not asking about the button flow, and not any Out of the Box feature, I just want to trigger my flow from my JavaScript code

Create the flow triggers by 'Request – when a HTTP request is received', you could find the script in TechNet wiki page.
function StartMicrosoftFlowTriggerOperations() {
try {
var dataTemplate = "{\r\n \"emailaddress\":\"{0}\",\r\n \"emailSubject\": \"{1}\",\r\n \"emailBody\": \"{2}\"\r\n}";
var httpPostUrl = "<Supply with the HTTP POST Url>";
//Call FormatRow function and replace with the values supplied in input controls.
dataTemplate = dataTemplate.FormatRow($("#txtEmailAddress").val(), $("#txtEmailSubject").val(), $("#txtEmailBody").val());
var settings = {
"async": true,
"crossDomain": true,
"url": httpPostUrl,
"method": "POST",
"headers": {
"content-type": "application/json",
"cache-control": "no-cache"
},
"processData": false,
"data": dataTemplate
}
$.ajax(settings).done(function (response) {
console.log("Successfully triggered the Microsoft Flow. ");
});
}
catch (e) {
console.log("Error occurred in StartMicrosoftFlowTriggerOperations " + e.message);
}
}

Related

Possible to create an account system with restdb.io? AJAX jQquery method

I'm fairly new to APIs in general, I managed to post data into restdb but how can i go about creating a system to log in based on the user/account data that i posted previously? what i'm thinking is using get and checking if any email and password matches but that does not sound efficient to code or im not sure if its possible to. could someone point me in the right direction
This is how my post function looks
$(document).ready(function () {
const APIKEY = ".";
$("#account-submit").on("click", function (e) {
//prevent default action of the button
e.preventDefault();
let name = $("#name").val();
let contactEmail = $("#contact-email").val();
let studentID = $("#student-id").val();
let password = $("#password").val();
var jsondata = {
"name": name,
"email": contactEmail,
"studentid": studentID,
"password": password,
};
var settings = {
"async": true,
"crossDomain": true,
"url": "https://nerdge-d48f.restdb.io/rest/account",
"method": "POST",
"headers": {
"content-type": "application/json",
"x-apikey": ".",
"cache-control": "no-cache"
},
"processData": false,
"data": JSON.stringify(jsondata)
}
$.ajax(settings).done(function(response) {
console.log(response);
$("#account-submit").prop("disabled", false);
});
})
}
)

how to send photo from telegram bot api (javascript)

I have a problem with sending the api via telegram text messages that arrive but the pictures are not arriving and I don't understand where the problem is
Is it possible to modify this code and make it send images?
var telegram_bot_id = "api";
var chat_id = "id";
var img;
var ready = function () {
img = document.getElementById("photo").value;
message = "photo: " + img ;
};
var sender = function () {
ready();
var settings = {
"async": true,
"crossDomain": true,
"url": "https://api.telegram.org/bot" + telegram_bot_id + "/sendPhoto",
"method": "POST",
"headers": {
"Content-Type": "application/json",
"cache-control": "no-cache"
},
"data": JSON.stringify({
"chat_id": chat_id,
"text": message
})
};
$.ajax(settings).done(function (response) {
console.log(response);
window.location.href = "index.html";
});
document.getElementById("photo").value = "";
return false;
};
In order to be able to send a photo via sendPhoto method, you have to send a proper picture file or a string represent a valid URL.
According to code you posted, you're sending into the HTTP request as body parameters the chat_id, the text message itself and that's it.
The sendPhoto method does not expect a text field, that's used in sendMessage method.
In your case, since you're trying to send via Telegram chatbot a picture taken from the HTML entity, which in this case is not the picture itself but its path on your webserver, you have to change the POST request body and to set the picture URL as parameter of the request itself.
To conclude, if you want to add the text message, the sendPhoto method allows you to add it but as caption.
For instance:
var telegram_bot_id = "api";
var chat_id = "id";
var img;
var ready = function () {
img = "http://your-website.com/imagepath/imagename.png";
};
var sender = function () {
ready();
var settings = {
"async": true,
"crossDomain": true,
"url": "https://api.telegram.org/bot" + telegram_bot_id + "/sendPhoto",
"method": "POST",
"headers": {
"Content-Type": "application/json",
"cache-control": "no-cache"
},
"data": JSON.stringify({
"chat_id": chat_id,
"photo": img,
"caption": message
})
};
$.ajax(settings).done(function (response) {
console.log(response);
window.location.href = "index.html";
});
return false;
};

Upload to vimeo with tus-js-client

I’m new to tus and I’m using tus-js-client. I’m following the example in this link https://github.com/tus/tus-js-client/blob/master/docs/usage.md#example-upload-to-vimeo.
I was able to successfully upload a video on Vimeo but I would like to set the title/name and description in advance. And also the optional onSuccess function is not returning anything. I would like to get the video details that I’ve uploaded successfully like the clipid.
Are these things something possible to do on tus-js-client? Below is my code for reference.
function UploadVideoTusJs(uploadUrl, videoFile) {
var upload = new tus.Upload(videoFile.files[0], {
uploadUrl: uploadUrl,
metadata: {
name: videoFile.files[0].name, // not working
description: "Test", // not working
},
onError: function (error) {
console.log("Failed because: " + error);
},
onProgress: function (bytesUploaded, bytesTotal) {
var percentage = (bytesUploaded / bytesTotal * 100).toFixed(2)
console.log(bytesUploaded, bytesTotal, percentage + "%")
},
onSuccess: function (data) {
console.log(data); //returns undefined
console.log("Download %s from %s", upload.file.name, upload.url);
},
onAfterResponse: function (req, res) {
var url = req.getURL()
var value = res.getHeader("X-My-Header")
console.log(`Request for ${url} responded with ${value}`)
}
});
// Start the upload by default
upload.start();
}
-- Dan
Vimeo's implementation of tus is a bit different as the "creation" step is done using the Vimeo API, not using tus. If you want to provide metadata like name or description, that should be provided with the initial API request, which should look something like this:
var settings = {
"url": "https://api.vimeo.com/me/videos",
"method": "POST",
"timeout": 0,
"headers": {
"Accept": "application/vnd.vimeo.*+json;version=3.4",
"Content-Type": "application/json",
"Authorization": "Bearer TOKEN"
},
"data": JSON.stringify({"upload":{"approach":"tus","size":666666666},"name":"name","description":"description"}),
};
$.ajax(settings).done(function (response) {
console.log(response);
});
Hope this points you in the right direction!

ClientId is null when calling ValidateClientAuthentication with Ajax

I have the following code that are generated by POSTMAN:
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost:51734/token",
"method": "POST",
"headers": {
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "application/json",
"cache-control": "no-cache",
"Postman-Token": "2879f786-3b1f-42fe-8198-b2193764d165"
},
"data": {
"grant_type": "client_credentials",
"client_id": "6E1JIQDEF0M"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
When you run the code above, the following code below are first executed:
public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
string clientId = string.Empty;
string clientSecret = string.Empty;
ClientDTO client = null;
if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
{
context.TryGetFormCredentials(out clientId, out clientSecret);
}
if (context.ClientId == null)
{
//Remove the comments from the below line context.SetError, and invalidate context
//if you want to force sending clientId/secrects once obtain access tokens.
context.Validated();
//context.SetError("invalid_clientId", "ClientId should be sent.");
//return Task.FromResult<object>(null);
return;
}
}
The problem I have is that context.ClientId is always null, and I don't know why.
When I make the same request with C# it works:
var client = new RestClient("http://localhost:51734/token");
var request = new RestRequest(Method.POST);
request.AddHeader("Postman-Token", "db182d32-9eff-4150-815e-2fd7d10ebd58");
request.AddHeader("cache-control", "no-cache");
request.AddHeader("Accept", "application/json");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("undefined", "grant_type=client_credentials&client_id=6E1JIQDEF0M&undefined=", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
So why does it work with c# but not javascript? Anyone who has any idea?
Try to call like this from Javascript.
data : 'grant_type=client_credentials&client_id=6E1JIQDEF0M'

JQuery Ajax function not being executed in chrome extension

I am creating a chrome extension which uses simple HTTP POST requests. It's my first javascript code ever. I used POSTMAN to generate this code which fulfills the requirement (POSTMAN worked with the POST request).
var form = new FormData();
form.append("email", "XXX");
form.append("password", "XXX");
var settings = {
"async": true,
"crossDomain": true,
"url": "http://xxx.xxx.in/xxx/",
"method": "POST",
"headers": {
"cache-control": "no-cache",
"postman-token": "fa86846e-4030-d90f-701a-82e36e6117b0"
},
"processData": false,
"contentType": false,
"mimeType": "multipart/form-data",
"data": form
};
chrome.extension.getBackgroundPage().console.log("outside")
try {
chrome.extension.getBackgroundPage().console.log("inside try block")
$.ajax(settings).done(function (response) {
chrome.extension.getBackgroundPage().console.log("inside")
chrome.extension.getBackgroundPage().console.log(response);
});
} catch (e) {
chrome.extension.getBackgroundPage().console.log("Exception caught")
chrome.extension.getBackgroundPage().console.log(e)
} finally {
}
I tried it with a chrome extension but my console does not log after the inside try block. I can't understand what happened in this line
$.ajax(settings).done(function (response) {
The error is not caught anywhere else. I have given appropriate permissions in my manifest.json file.
I have some very specific questions to ask:
What is the best workaround for requests? XmlHttpRequests or JQuery
What are some best ways of debugging javascript applications? That would help a lot, thanks.

Categories

Resources