How to Post a .json file to ArangoDB using Ajax - javascript

I am trying to post a .json file as a single document to an ArangoDB collection, from within javascript/ajax.
I can post (to ArangoDB) the .json file using curl, so that works
I can post (to ArangoDB) simple {key: value} pairs using AJAX, so that works, but combining the two seems to be a bridge too far. I have spent a couple of nights trying to get this far, so any help would be hugely appreciated. thanks in advance.
My javascript code looks like this
var database_URL = prompt("Please enter your URL", "http://xxx..xxx.xxxx.:8529/_db/collection_name/_api/document?collection=PA_Users&createCollection=false");
var fd = new FormData();
var selectedFile = document.getElementById('files').files[0];
console.log(selectedFile.name);// this works
fd.append(selectedFile.name,selectedFile);
var settings = {
url : database_URL,
type : "POST",
headers: {
'Authorization': "Basic " + btoa(username1 + ":" + passwrd1)
},
data: fd,
processData: false,
success: function(data) {
// display feedback to user
alert("booyah");
},
error: function(data) {
// display feedback to user
alert("boo hoo");
}
};
$.ajax(settings);

I think you should use /_api/import instead of /_api/document:
HTTP Interface for Bulk Imports
Here is a small working example (without authorization):
$.ajax({
type: "POST",
url:
'/_api/import?type=auto&collection=' +
encodeURIComponent(yourCollectionID) +
'&createCollection=false',
data: file,
processData: false,
contentType: 'json',
dataType: 'json',
complete: function(xhr) {
if (xhr.readyState === 4 && xhr.status === 201) {
callback(false);
} else {
try {
var data = JSON.parse(xhr.responseText);
if (data.errors > 0) {
// error
}
else {
// success
}
}
catch (err) {
console.log(err);
}
}
}
});
}
The api supports a few input formats:
1.) Single document
{name: "Jonny"}
2.) Multiple documents (one doc in each row)
{name: "Jonny"}
{name: "Adam"}
{name: "Peter"}
3.) Multiple documents in JSON array
[{name: "Jonny"}, {name: "Adam"}, {name: "Peter"}]

Related

How to get nested JSON data values with a "data-" attribute?

I'm trying to create an elegant way of binding json data to html using data-attributes without having to write a bunch of custom code or using an external library/framework.
I can get this to work just fine without nested data and re-writing my function a little.
The problem is that it's reading my data-api-value as a string..so I'm trying to find the correct way to convert it. I'm open to other suggestions/ work-arounds though.
Here's the code in a (codepen)
Here's a dumb'd down version of the code
function getApiData(apiUrl, callback) {
apiData = $.ajax({
type: 'GET',
url: apiUrl,
dataType: 'json',
success: function(json) {
callback(json.data);
},
error: function(req, err) {
console.log(err);
},
contentType: "application/json; charset=utf-8"
});
}
function dataAPIrealtime() {
const url = 'https://someapi/v1/exchange/getinstrument/bitmex/XBTUSD';
getApiData(url, function(apidata){
$('[data-api]').each(function() {
let api = $(this).data("api");
let value = $(this).data("apiValue");
let data = apidata + value;
if (data || data != data) {
$(this).html(data);
}
});
});
}
/* Run Functions
*********************************/
$(document).ready(function() {
dataAPIrealtime();
setInterval(dataAPIrealtime, 1000); // Refresh data every 1 second
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span data-api="exchange/getinstrument" data-api-value="[instrument][symbol]"></span>

Copy file from local to the server nodejs

I am using nodeJS and I would like to upload a file to the server.
I have pug page where the user fill all the information and choose a file with filechooser. Then I want to send all the information on the page to the server. Therefore, I am using ajax to send a json object and given that file object can not be send through a json object I convert the File object to a json object like this:
function uploadGenome() {
var file = $(':file')[0].files[0];
var fileObject = {
'lastMod': file.lastModified,
'lastModDate': file.lastModifiedDate,
'name': file.name,
'size': file.size,
'type': file.type
};
return fileObject;
}
Then I add everything in a Json object:
var data = {};
data.file = uploadGenome();
data.name = inputs[0].value;
data.description = inputs[1].value;
data.start = inputs[3].value;
data.end = inputs[4].value;
And finally, I send everything with ajax:
$.ajax({
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json',
url: url,
success: function (data) {
console.log('success');
console.log(JSON.stringify(data));
if (data === 'done')
{
window.location.href = "/";
} else {
alert('Error Creating the Instance');
}
},
error: function () {
console.log('process error');
}
});
On the server side with NodeJS I get everything, but now how could I copy the file that I get in data.file on the server ? I mean create a copy on the project folder which is on a server.

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

Validate list item in REST

I have a function that will add list item using REST. But I want to validate a list item if its already exist on my list first before I add it. How will do it?
function addListItem() {
var title = $("#txtTitle").val();
var siteUrl = _spPageContextInfo.webAbsoluteUrl;
var fullUrl = siteUrl + "/_api/web/lists/GetByTitle('Employee')/items";
$.ajax({
url: fullUrl,
type: "POST",
data: JSON.stringify({
'__metadata': { 'type': 'SP.Data.EmployeeListItem' },
'EmployeeID': $("#txtEmpID").val(),
'Name': $("#txtName").val(),
}),
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: onQuerySucceeded,
error: onQueryFailed
});
function onQuerySucceeded(sender, args) {
alert("Item successfully added!");
}
function onQueryFailed() {
alert('Error!');
}
};
You can use the OData query operations in SharePoint REST requests
use the $filter parameter in a Get operation to validate if the user exists in the list, using something like this:
$filter=Name eq '<UserName>'
An example:
siteUrl + "/_api/web/lists/GetByTitle('Employee')/items?$filter=Name eq 'John'
< UserName > is the textbox value
You can see a Response sample here:
http://services.odata.org/Northwind/Northwind.svc/Customers?$filter=ContactName%20eq%20%27Maria%20Anders%27
Just do a Get request and count the elements to know if the user exists
$.get("/_api/web/lists/getbytitle('Employee')/items?$filter=Name eq '<Name>'",function(e){
if($(e).find("entry").length > 0){
console.log("user exists");
}
})
You can see a Complete basic operations using SharePoint 2013 REST endpoints using JQuery/Javascript here:
https://msdn.microsoft.com/en-us/library/office/jj164022.aspx

Pass object from javascript to Perl dancer framework

I have following ajax code to pass values to dancer framework.
BookSave: function(data) {
### data is an object that contain more than one key value pair
var book = Book.code;
$.ajax ({
type: "GET",
url : 'textbook/save/' + book + '/' + data,
success: function(data) {
if(data.status == 1) {
alert("success");
} else {
alert("fail");
}
},
});
},
In dancer:
any [ 'ajax', 'get' ] => '/save/:book/:data' => sub {
set serializer => 'JSON';
my $book = params->{book};
my $data = params->{data}; ## This I am getting as object object instead of hash
};
Is there any way to pass object from js and getting as hash in dancer?
First and foremost, consider using the http PUT or POST verbs, and not GET. Not only is doing so more semantically correct, it allows you to include more complex objects in the http body, such as your 'data' hash (serialized, per my comments below).
I've had limited success with Dancer's native AJAXy methods, plus there is a bug that causes problems in some versions of Firefox. So instead, I serialize and then deserialize the JSON object.
Suggested changes (note I suggested changes to your routes as well):
$.ajax ({
type: "PUT",
url : '/textbook/' + book,
data: {
myhash : JSON.stringify(data)
},
dataType: 'json',
contentType: 'application/json',
success: function (response) {
if (response.status == 1) {
alert("success")
} else {
alert("fail")
}
}
})
and your Perl Dancer code changes as follows:
any [ 'ajax', 'put' ] => '/textbook/:book' => sub {
set serializer => 'JSON';
my $book = param('book');
my $data = from_json(param('myhash'));
};
I did not go as far as testing this code, but it should at least give you a good starting point to finish solving this problem.
Good luck with your project!

Categories

Resources