JQuery Ajax function not being executed in chrome extension - javascript

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.

Related

Can I trigger a Power Automate workflow from custom JavaSript?

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);
}
}

Draftable.com API giving truncated response when passed a JSON in Google App Script

I am trying to call an API from draftable.com (https://api.draftable.com/v1/comparisons) using Google App Script. The API takes two files and returns a string. I have made the GET and DELETE functions which are working fine, but when I run a POST function I am getting an error at the
UrlFetchApp.fetch("URL",object);
Error: Request failed for https://api.draftable.com/v1/comparisons
returned code 400. Truncated server response: {"left":["This field is
required."],"right":["This field is required."]}
I am passing a JSON like the code below:
function POST() {
var options = {
"method": "POST",
"headers": {
"Content-Type": "multipart/form-data",
"Accept": "application/json",
"Authorization": "Token {iputmytokenhere}",
},
"left": {
"source_url": "https://api.draftable.com/static/test-documents/paper/left.pdf",
"display_name": "old-example.docx",
"file_type": "pdf"
},
"right": {
"source_url": "https://api.draftable.com/static/test-documents/paper/right.pdf",
"display_name": "newer-example.docx",
"file_type": "pdf"
}
};
var result = UrlFetchApp.fetch("https://api.draftable.com/v1/comparisons", options);
var params = JSON.parse(result.getContentText());
Logger.log(params.identifier);
}
}
Can anyone tell me why is the error coming.

Facebook Graph API publish picture with Javascript

I'm using the Facebook Javascript SDK in my react app and I want to make a post with multiple photos. I know that that means I have to first post the pictures unpublished and then use the returned ids to make the post.
However, I'm having trouble finding good documentation and running into issues figuring out how to allow a user select and post a local picture (not from a url). The code is a bit difficult to put all here, but here are the steps I'm taking and the errors I'm getting:
Get file the user selected using a file input.
Encode the picture as a blob and put that and the access token into FormData to use in the api request.
var reader = new FileReader();
reader.onload = function(e) {
var arrayBuffer = e.target.result;
var blob = new Blob([arrayBuffer], { type: photo.type });
var pictureData = new FormData();
pictureData.append('access_token:', this.state.FBaccessToken);
pictureData.append('source', blob);
return pictureData;
}.bind(this)
return reader.readAsArrayBuffer(photo);
Do a post request
var encodedRequest = this.encodePhoto(photo);
FB.api(
"/me/photos?published=false",
"POST",
encodedRequest,
function (response) {
if (response && !response.error) {
//once successfully gotten the photos add them to the array of photo ids
temp.push({"media_fbid": response.id});
console.log(response);
}
else {
alert(response.error.message);
}
}.bind(this)
);
The error when I run it this way is that it doesn't seem to recognize the access token, but when I remove the access token from pictureData in step 2, and change the api encodedRequest part to this:
{
access_token: this.state.FBaccessToken,
source: encodedRequest,
},
I get the error "(#324) Requires upload file". I tried adding fileUpload: true, to the SDK init code but that also didn't seem to do anything. Posting simple text only statuses and reading from feed is all working fine.
Sorry for the long post, but I'd be really grateful if anyone has any insight! Thanks.
Is it the extra colon you have after access_token in your first pictureData.append() call?
pictureData.append('access_token:', this.state.FBaccessToken);
versus
pictureData.append('access_token', this.state.FBaccessToken);
Edit: Below is output from postman to post images referencing a file on my laptop
var form = new FormData();
form.append("source", "/Users/patricklambe/images/test.jpg");
form.append("access_token", "PAGEACCESSTOKEN");
form.append("caption", "check this photo");
var settings = {
"async": true,
"crossDomain": true,
"url": "https://graph.facebook.com/v2.11/444873272561515/photos",
"method": "POST",
"headers": {
"cache-control": "no-cache",
"postman-token": "1d786fec-c9b1-2494-1b5c-8fd0e2ea5ade"
},
"processData": false,
"contentType": false,
"mimeType": "multipart/form-data",
"data": form
}
$.ajax(settings).done(function (response) {
console.log(response);
});

Asp.net core api getting "415 Unsupported Media Type" error from Javascript, not Postman

I've created an Asp.Net Core Web Application and am looking to implement a Web API.
I've got a functional HttpGet implemented and am now trying to implement a HttpPost function:
[HttpPost]
public object Post([FromBody] object data)
{
return null;
}
I've tested this using Postman which worked fine.
I set it up with json object in the body (set to raw and JSON (application/json)).
I get the expected response.
But when I try to call this from javascript using code suggested by Postman (or my own attempts):
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost:51139/api/data",
"method": "POST",
"headers": {
"content-type": "application/json",
"cache-control": "no-cache",
"postman-token": "999ee8ee-4e92-acb8-b7cf-144ffa49e5ee"
},
"processData": false,
"data": "{\"Message\":\"This is body data\"}"
}
$.ajax(settings).done(function (response) {
console.log(response);
});
I get a "415 Unsupported Media Type" error.
Anyone see where I'm going wrong?
I had the same problem and tried a million different combinations ($.ajax, $.post etc), but what finally did it was the accepts: "application/json":
{
type: "post",
accepts: "application/json",
url: "http://localhost:51139/api/data",
contentType : "application/json",
data: "{\"Message\":\"This is body data\"}"
}
You could try something like this
[HttpPost]
public object Post()
{
Object o = Request.Form.First(o => o.Key == "data").Value
return null;
}
Then if you can create a class of that object you can use JsonConvert to Deserialize that object into the class object that you have created.

Posting multiple Photos to one post

I have been trying to create an application which needs multiple photos to be attached to one post. These are the following attempts i tried,
First i used facebook-node-sdk which JS SDK to achieve different functionality, but Official Js Sdk does't have option for file to upload, when then i moved to attaching/inserting photo itself to HTTP POST with the help of form-data, with the following code-
var form = new FormData();
form.append('file', fs.createReadStream(picPaths[0]));
form.append('message', "Hello"); //Put message
var ACCESS_TOKEN = "ACCESS_TOKEN";
var options = {
method: 'post',
host: 'graph.facebook.com',
path: '{Object-ID}/photos' + '?access_token=' + ACCESS_TOKEN,
headers: form.getHeaders(),
}
var request = https.request(options, function(res) {
console.log(res, false, null);
});
form.pipe(request);
request.on('error', function(error) {
console.log(error);
});
This works with one photo.
But as you can see in this github.com/Thuzi/facebook-node-sdk/issues/113 which i started, it is not possible to attach more than one photo.
So as mentioned by dantman i stated looking in batch process, which can be found developers.facebook.com/docs/graph-api/making-multiple-requests titled under Uploading binary data. The one thing that hits and give me hope is this one statement.
The attached_files property can take a comma separated list of attachment names in its value.
Note That (batching with photos) also is not possible with this library or JS SDK (Please correct me if i am wrong)
You can do post images with curl like this,
curl -F 'access_token=ACCESS_TOKEN' -F 'batch=[{"method":"POST","relative_url":"{Object-Id}/photos","body":"message=Test Post","attached_files":"file1"}]' -F 'file1=#image1' -F 'file2=#image2' https://graph.facebook.com
The above code posts with one image
So my question is this, it possible to attach multiple images/binary_files to the post with the help of curl, something like ..."attached_files":"file1,file2"... as suggested by docs, please help me with this problem and if you have already done this can you please post the snapshot of your code.
Thanks, Ravi
I finally figured out how.
So first, read the section here titled "Publishing a multi-photo post with uploaded photos": https://developers.facebook.com/docs/graph-api/reference/page/photos/#Creating
What it says is basically correct, however, it is not in JavaScript. Also, they don't emphasize enough an important step: You have to set "published" to "false" for the image you upload, for it to then be attachable to the post that gets created.
So anyway, here is the working code -- in JavaScript, and with "published" correctly set to false:
async function PostImageToFacebook(token, filename, mimeType, imageDataBlob, message) {
var fd = new FormData();
fd.append("access_token", token);
fd.append("source", imageDataBlob);
//fd.append("message", "photo message for " + filename);
fd.append("no_story", "true");
//fd.append("privacy", "SELF");
fd.append("published", "false");
// Upload image to facebook without story(post to feed)
let uploadPhotoResponse = await $.ajax({
url: "https://graph.facebook.com/me/photos?access_token=" + token,
type: "POST",
data: fd,
processData: false,
contentType: false,
cache: false
});
console.log(`Uploaded photo "${filename}": `, uploadPhotoResponse);
let uploadPhotoResponse2 = await $.ajax({
url: "https://graph.facebook.com/me/photos?access_token=" + token,
type: "POST",
data: fd,
processData: false,
contentType: false,
cache: false
});
console.log(`Uploaded photo "${filename}": `, uploadPhotoResponse2);
let makePostResponse = await $.ajax({
"async": true,
"crossDomain": true,
"url": "https://graph.facebook.com/v2.11/me/feed",
"method": "POST",
"headers": {
"cache-control": "no-cache",
"content-type": "application/x-www-form-urlencoded"
},
"data": {
"message": "Testing multi-photo post2!",
"attached_media[0]": `{"media_fbid":${uploadPhotoResponse.id}}`,
"attached_media[1]": `{"media_fbid":${uploadPhotoResponse2.id}}`,
"access_token": token
}
});
console.log(`Made post: `, makePostResponse);
}
The code above currently just uploads the same image twice, then attaches both to the new post. Obviously, in real world usage you would replace the data in the second photo-upload with a different image.
Anyway, to use the function, just call it like so:
function dataURItoBlob(dataURI) {
var byteString = atob(dataURI.split(",")[1]);
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ab], {type: "image/png"});
}
let imageDataURI = GetImageDataURIFromSomewhere();
let imageBlob = dataURItoBlob(imageDataURI);
PostImageToFacebook(fbToken, "some_filename", "image/png", imageBlob, window.location.href);
this is possible.
Note: This one is not an efficient way to do this but just for explaining purpose i am doing here,
The first hint that i got that it may be possible is from this post
Steps that i used:
Follow the doc to create custom open graph stories
Let's suppose you four image to attach (pic[1, 2, 3, 4])
First i staged them with the help of new facebook-node-sdk v1.1.0-alpha1 with the code something like this (with batch process).
FB.api( "", "post", {
batch: [
{
method: "POST",
relative_url: "me/staging_resources",
attached_files: "file1",
type:"image/png"
}, {
method: "POST",
relative_url: "me/staging_resources",
attached_files: "file2",
type:"image/png"
}, {
method: "POST",
relative_url: "me/staging_resources",
attached_files: "file3",
type:"image/png"
}, {
method: "POST",
relative_url: "me/staging_resources",
attached_files: "file4",
type:"image/png"
}],
file1: fs.createReadStream(picPaths[0]),
file2: fs.createReadStream(picPaths[1]),
file3: fs.createReadStream(picPaths[2]),
file4: fs.createReadStream(picPaths[3])
},
function(response) {
console.log(response);
});
Now from the response part get the url and dis the post with the same library. With the code something like this.
FB.api(
"me/objects/{app-namespace}:{custom-object}",
"post", {
"object": {
"og:title": "Sample Post",
"og:image[0]": {
"url": "fbstaging:{...}",
"user_generated": true
},
"og:image[1]": {
"url": "fbstaging:{...}",
"user_generated": true
},
"og:image[2]": {
"url": "fbstaging:{...}",
"user_generated": true
},
"og:image[3]": {
"url": "fbstaging:{...}",
"user_generated": true
}
}
},
function(response) {
console.log(response);
}
);
Now, with these two piece of code you will be able to push multiple images/photo to the single post.
Note: this can make more sense or can be done with the help of named batch process which is being described here.
Thanks,
Ravi

Categories

Resources