Add ListItem to List Folder using Rest-Api - javascript

I have a problem with adding a ListItem in a specified Folder while using SharePoint 2013 REST api.
With the Client Object Model it would look like this:
var creationInfo = new SP.ListItemCreationInformation();
creationInfo.FolderUrl = "/Lists/MyList/MyFolder";
var item = list.addItem(creationInfo );
item.update();
ctx.executeQueryAsync(
Function.createDelegate(this, onSuccess),
Function.createDelegate(this, onFail));
But when i'm trying to set the FolderUrl via the Rest Service
{ '__metadata' : { 'type': 'SP.Data.MyListListItem' }, 'Title': 'NewItemInFolder', 'FolderUrl': '/sites/example/Lists/MyList/MyFolder' }
I got an 400 Bad Request
I have also tried to first add a ListItem to the List and then update the FolderUrl but this also didn't work.
How can I add ListItem's to a List Folder in SharePoint using the Rest-Api ?
Edit:
{ '__metadata' : {
'type': 'SP.Data.MyListListItem',
'type': 'SP.Data.ListItemCreationInformation'
},
'Title': 'NewItemInFolder',
'FolderUrl': '/sites/example/Lists/MyList/MyFolder'
}
I have now tried to use both ListItemEntityTypeFullName the Entity from my List and the ListItemCreationInformation but I also only get a 400 Bad Request.
And when i'm looking into the request with Fiddler I see that SharePoint is ignoring now my List Entity Type SP.Data.MyListItem

You should not use the REST api but instead use the listdata.svc
url: /_vti_bin/listdata.svc/[Name of List]
Header:Content-Type: application/json;odata=verbose
Body: {Title: "Title", Path: "/ServerRelativeUrl"}
I had the same problem but with REST api it won't work with the old svc it will.

You could consider the following solution, it consists of 3 steps listed below:
create a ListItem resource
get associated File resource and finally move it into folder
Example
function executeJson(options)
{
var headers = options.headers || {};
var method = options.method || "GET";
headers["Accept"] = "application/json;odata=verbose";
if(options.method == "POST") {
headers["X-RequestDigest"] = $("#__REQUESTDIGEST").val();
}
var ajaxOptions =
{
url: options.url,
type: method,
contentType: "application/json;odata=verbose",
headers: headers
};
if("payload" in options) {
ajaxOptions.data = JSON.stringify(options.payload);
}
return $.ajax(ajaxOptions);
}
function createListItem(webUrl,listTitle,properties,folderUrl){
var url = webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/items";
return executeJson({
"url" :url,
"method": 'POST',
"payload": properties})
.then(function(result){
var url = result.d.__metadata.uri + "?$select=FileDirRef,FileRef";
return executeJson({url : url});
})
.then(function(result){
var fileUrl = result.d.FileRef;
var fileDirRef = result.d.FileDirRef;
var moveFileUrl = fileUrl.replace(fileDirRef,folderUrl);
var url = webUrl + "/_api/web/getfilebyserverrelativeurl('" + fileUrl + "')/moveto(newurl='" + moveFileUrl + "',flags=1)";
console.log(url);
return executeJson({
"url" :url,
"method": 'POST',
});
});
}
Usage
var webUrl = _spPageContextInfo.webAbsoluteUrl;
var listTitle = "Requests"; //list title
var targetFolderUrl = "/Lists/Requests/Archive"; //folder server relative url
var itemProperties = {
'__metadata': { "type": "SP.Data.RequestsListItem" },
"Title": 'Request 123'
};
createListItem(webUrl,listTitle,itemProperties,targetFolderUrl)
.done(function(item)
{
console.log('List item has been created');
})
.fail(function(error){
console.log(JSON.stringify(error));
});
Gist

Microsoft.SharePoint.Client.ClientContext clientContext = new Microsoft.SharePoint.Client.ClientContext("URL");
Microsoft.SharePoint.Client.List list = clientContext.Web.Lists.GetByTitle("FolderName");
var folder = list.RootFolder;
clientContext.Load(folder);
clientContext.Credentials = new NetworkCredential(username, password, domain);
clientContext.ExecuteQuery();
folder = folder.Folders.Add("ItemName");
clientContext.Credentials = new NetworkCredential(username, password, domain);
clientContext.ExecuteQuery();

creationInfo.set_folderUrl("http://siteURL/Lists/Docs/Folder1");

Related

Is there any better way to display POST request in Angular Js

I have used both PUT and POST request to modify and create a data. But the thing is POST request is not working properly. When i click on add() button , automatically POST request is generating id in the json-data before filling the information in the text fields.
Moreover data should be updated when I click on the save() button . Below I have pasted my code, if I have made any mistake tel me know and I appreciate every one whomever gives any information.
HTMl :
<button class="btn btn-info" ng-click="addmode()"> Add </button>
<button class="btn btn-success" ng-show="editMode" ng-click="saveinfo()"> Save </button>
Angular JS :
$scope.addmode = function(information) {
var postinfo = information;
$http({
url:'http://localhost:3000/contacts' ,
method : 'POST',
data : postinfo
})
.then(
function successCallback(response) {
$scope.selectedcontact = '';
console.log(response.data)
},
function errorCallback(response) {
console.log("Error : " + response.data);
});
};
First create services/api.js
angular.module('app')
.factory('api', function ($rootScope,ApiEndpoint, $http, $q,$timeout,$cookies) {
var get = function (url) {
var config = {url: url, method: ApiEndpoint.Methods.GET};
return this.call(config);
};
var del = function (url) {
var config = {url: url, method: ApiEndpoint.Methods.DELETE};
return this.call(config);
};
var post = function (url, data) {
var config = {url: url, method: ApiEndpoint.Methods.POST, data: data};
return this.call(config);
};
var put = function (url, data) {
var config = {url: url, method: ApiEndpoint.Methods.PUT, data: data};
return this.call(config);
};
return {call: call, get: get, post: post, del: del, put: put};
});
After create service/apiendpoint.js
angular.module('app')
.constant('ApiEndpoint', {
ServerUrl: 'http://localhost/',
BaseUrl: 'http://localhost/',
Methods: {GET: 'GET', POST: 'POST', PUT: 'PUT', DELETE: 'DELETE'},
Models: {
test:"fe_api/test",
},
URLS: {
QUERY: 'app/'
},
getUrl: function (url) {
var host=window.location.host;
var protocol=window.location.protocol ;
return protocol+"//"+host+"/"+url;
}
});
**Create model handler **
angular.module('app')
.factory('ApiService', function (api, ApiEndpoint) {
var getModel = function (url_part)
{
var url = ApiEndpoint.getUrl(ApiEndpoint.URLS.QUERY) + url_part;
return api.get(url);
};
var getModelViaPost = function (url_part, data)
{
var url = ApiEndpoint.getUrl(ApiEndpoint.URLS.QUERY) + url_part;
return api.post(url, data);
};
var postModel = function(model_name, data) {
var url = ApiEndpoint.getUrl(ApiEndpoint.URLS.QUERY) + model_name;
return api.post(url, data);
};
var putModel = function(model_name, data) {
var url = ApiEndpoint.getUrl(ApiEndpoint.URLS.QUERY) + model_name;
return api.put(url, data);
};
var deleteModel = function(model_name, id) {
var url = ApiEndpoint.getUrl(ApiEndpoint.URLS.QUERY) + model_name + '/' + id;
return api.delete(url);
};
return {
getModel: getModel,
postModel : postModel,
putModel : putModel,
deleteModel : deleteModel,
getModelViaPost : getModelViaPost
};
});
write API call in the controller
var data = {
wut_token: $cookies.data,
};
ApiService.postModel(ApiEndpoint.Models.test, data).then(function (response) {
if (response.SUCCESS == "FALSE") {
} else {
}
})

Create File with Google Drive Api v3 (javascript)

I want to create a file with content using Google Drive API v3. I have authenticated via OAuth and have the Drive API loaded. Statements like the following work (but produce a file without content):
gapi.client.drive.files.create({
"name": "settings",
}).execute();
Unfortunately I cannot figure out how to create a file that has a content. I cannot find a JavaScript example using Drive API v3. Are there some special parameters that I need to pass?
For simplicity, assume that I have a String like '{"name":"test"}' that is in JSON format that should be the content of the created file.
Unfortunately, I have not found an answer using only the google drive api, instead I followed Gerardo's comment and used the google request api. Below is a function that uploads a file to google drive.
var createFileWithJSONContent = function(name,data,callback) {
const boundary = '-------314159265358979323846';
const delimiter = "\r\n--" + boundary + "\r\n";
const close_delim = "\r\n--" + boundary + "--";
const contentType = 'application/json';
var metadata = {
'name': name,
'mimeType': contentType
};
var multipartRequestBody =
delimiter +
'Content-Type: application/json\r\n\r\n' +
JSON.stringify(metadata) +
delimiter +
'Content-Type: ' + contentType + '\r\n\r\n' +
data +
close_delim;
var request = gapi.client.request({
'path': '/upload/drive/v3/files',
'method': 'POST',
'params': {'uploadType': 'multipart'},
'headers': {
'Content-Type': 'multipart/related; boundary="' + boundary + '"'
},
'body': multipartRequestBody});
if (!callback) {
callback = function(file) {
console.log(file)
};
}
request.execute(callback);
}
here is the solution with gapi.client.drive,
var parentId = '';//some parentId of a folder under which to create the new folder
var fileMetadata = {
'name' : 'New Folder',
'mimeType' : 'application/vnd.google-apps.folder',
'parents': [parentId]
};
gapi.client.drive.files.create({
resource: fileMetadata,
}).then(function(response) {
switch(response.status){
case 200:
var file = response.result;
console.log('Created Folder Id: ', file.id);
break;
default:
console.log('Error creating the folder, '+response);
break;
}
});
you'll need to connect/authorise with either of the following scopes
https://www.googleapis.com/auth/drive
https://www.googleapis.com/auth/drive.file
EDIT: it is possible to create google files (doc, sheets and so on) by changing the mimeType from application/vnd.google-apps.folder to one of the supported google mime types. HOWEVER, as of now it not possible to upload any content into created files.
To upload files, use the solution provided by #Geminus. Note you can upload a text file or a csv file and set its content type to google doc or google sheets respectively, and google will attempt to convert it. I have tested this for text -> doc and it works.
Using gapi.client.drive, it is not possible to upload file content. You can only upload metadata.
Instead it is recommended to work directly with the Google REST API. This solution uses a FormData object to build the multipart form body, which simplifies the implementation, and gapi.auth.getToken() to retrieve the required access token. The solution also works with Google shared drives:
var fileContent = "sample text"; // fileContent can be text, or an Uint8Array, etc.
var file = new Blob([fileContent], {type: "text/plain"});
var metadata = {
"name": "yourFilename",
"mimeType": "text/plain",
"parents": ["folder id or 'root'"], // Google Drive folder id
};
var accessToken = gapi.auth.getToken().access_token;
var form = new FormData();
form.append('metadata', new Blob([JSON.stringify(metadata)], { type: 'application/json' }));
form.append('file', file);
fetch("https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&supportsAllDrives=true", {
method: 'POST',
headers: new Headers({ 'Authorization': 'Bearer ' + accessToken }),
body: form,
}).then((res) => {
return res.json();
}).then(function(val) {
console.log(val);
});
this works fine usin v3:
var fileMetadata = {
'name' : 'MaxBarrass',
'mimeType' : 'application/vnd.google-apps.folder'
};
gapi.client.drive.files.create({
resource: fileMetadata,
fields: 'id'
}).execute(function(resp, raw_resp) {
console.log('Folder Id: ', resp.id);
});
/* Now to create a new file */
function insertNewFile(folderId)
{
var content = " ";
var FolderId = "";
var contentArray = new Array(content.length);
for (var i = 0; i < contentArray.length; i++)
{
contentArray[i] = content.charCodeAt(i);
}
var byteArray = new Uint8Array(contentArray);
var blob = new Blob([byteArray], {type: 'text/plain'});
insertFile(blob, fileInserted, folderId);
}
function fileInserted(d)
{
setPercent("100");
var FI = FolderId;
if(FI !== myRootFolderId)
{
insertFileIntoFolder(FI, d.id);
removeFileFromFolder(d.parents[0].id,d.id);
}
openFile(d.id);
}
function insertFileIntoFolder(folderId, fileId)
{
var body = {'id': folderId};
var request = gapi.client.drive.parents.insert({
'fileId': fileId,
'resource': body });
request.execute(function(resp) { });
}
Source: https://gist.github.com/mkaminsky11/8624150

how to use PostgreSQL mod for vertx in js?

hi im new in vertx and i want use https://github.com/vert-x/mod-mysql-postgresql for a service
i use this code for my web server
var vertx = require('vertx');
var console = require('vertx/console');
var Server = vertx.createHttpServer();
Server.requestHandler(function (req) {
var file = req.path() === '/' ? 'index.html' : req.path();
if (file === '/foo') {
foo(req);
}
else{
req.response.sendFile('html/' + file);
}
}).listen(8081);
function foo(req) {
req.bodyHandler(function (data) {
//data is json {name:foo, age:13} i want insert this in any table in postgre
//do
var dataresponse= messagefrompostgre;//e: {status:"ok", code:200, message: "its ok"}
req.response.putHeader("Content-Type", "application/json");
req.response.end(dataresponse);
});
}
and this is my event click button
$.ajax({
data: {name:foo, age:13} ,
url: '/foo',
type: 'post',
dataType: 'json',
complete: function (response) {
alert(JSON.stringify(response));
}
});
I found how to do it:
var vertx = require('vertx');
var console = require('vertx/console');//TODO: remove
var eventBus = vertx.eventBus;
var Server = vertx.createHttpServer();
Server.requestHandler(function (req) {
var file = req.path() === '/' ? 'index.html' : req.path();
if (file === '/foo') {
foo(req);
}
else{
req.response.sendFile('html/' + file);
}
}).listen(8081);
function foo(req) {
req.bodyHandler(function (data) {
//data is json {name:foo, age:13}
var jsona={
"action" : "raw",
"command" : "select * from test"
}
eventBus.send("PostgreSQL-asyncdb",jsona, function(reply) {
req.response.putHeader("Content-Type", "application/json");
req.response.end(JSON.stringify(reply));
});
});
}
and this return:
{"message":"SELECT 6","rows":6,"fields":["testt"],"results":[["lol"],["lolŕ"],["lol2"],["lol2"],["testlol"],["testlolp"]],"status":"ok"}

How get json parameters if I use post method in vertx?

I want to get all post parameters.
This is my vertx code:
var vertx = require('vertx/http');
var console = require('vertx/console');
var Server= vertx.createHttpServer();
Server.requestHandler(function(req) {
console.log(req.path());
console.log(req.method());
console.log(req.params());
// nothing
if(myPostparametersContainAnyitem){ //do anything}
else{
var file = req.path() === '/' ? 'index.html' : req.path();
req.response.sendFile('html/' + file);}
}).listen(8081)
This is my button click code:
$.ajax({
data: {name:'foo',age:'13'},
url: '/somedir',
type: 'post',
dataType: 'json',
success: function (response) {
alert(response);
}
});
I discovered how to do it thanks
var vertx = require('vertx');
var console = require('vertx/console');
var Server = vertx.createHttpServer();
Server.requestHandler(function (req) {
var file = req.path() === '/' ? 'index.html' : req.path();
if (file === '/foo') {
foo(req);
}
else{
req.response.sendFile('html/' + file);
}
}).listen(8081);
function foo(req) {
console.log(req);
req.bodyHandler(function (data) {
//data is json {name:foo, age:13}
//do
req.response.end(data);
});
}

Backbone.js fetch with parameters

Following the documentation, I did:
var collection = new Backbone.Collection.extend({
model: ItemModel,
url: '/Items'
})
collection.fetch({ data: { page: 1} });
the url turned out to be: http://localhost:1273/Items?[object%20Object]
I was expecting something like http://localhost:1273/Items?page=1
So how do I pass params in the fetch method?
changing:
collection.fetch({ data: { page: 1} });
to:
collection.fetch({ data: $.param({ page: 1}) });
So with out over doing it, this is called with your {data: {page:1}} object as options
Backbone.sync = function(method, model, options) {
var type = methodMap[method];
// Default JSON-request options.
var params = _.extend({
type: type,
dataType: 'json',
processData: false
}, options);
// Ensure that we have a URL.
if (!params.url) {
params.url = getUrl(model) || urlError();
}
// Ensure that we have the appropriate request data.
if (!params.data && model && (method == 'create' || method == 'update')) {
params.contentType = 'application/json';
params.data = JSON.stringify(model.toJSON());
}
// For older servers, emulate JSON by encoding the request into an HTML-form.
if (Backbone.emulateJSON) {
params.contentType = 'application/x-www-form-urlencoded';
params.processData = true;
params.data = params.data ? {model : params.data} : {};
}
// For older servers, emulate HTTP by mimicking the HTTP method with `_method`
// And an `X-HTTP-Method-Override` header.
if (Backbone.emulateHTTP) {
if (type === 'PUT' || type === 'DELETE') {
if (Backbone.emulateJSON) params.data._method = type;
params.type = 'POST';
params.beforeSend = function(xhr) {
xhr.setRequestHeader('X-HTTP-Method-Override', type);
};
}
}
// Make the request.
return $.ajax(params);
};
So it sends the 'data' to jQuery.ajax which will do its best to append whatever params.data is to the URL.
You can also set processData to true:
collection.fetch({
data: { page: 1 },
processData: true
});
Jquery will auto process data object into param string,
but in Backbone.sync function,
Backbone turn the processData off because Backbone will use other method to process data
in POST,UPDATE...
in Backbone source:
if (params.type !== 'GET' && !Backbone.emulateJSON) {
params.processData = false;
}
Another example if you are using Titanium Alloy:
collection.fetch({
data: {
where : JSON.stringify({
page: 1
})
}
});
try {
// THIS for POST+JSON
options.contentType = 'application/json';
options.type = 'POST';
options.data = JSON.stringify(options.data);
// OR THIS for GET+URL-encoded
//options.data = $.param(_.clone(options.data));
console.log('.fetch options = ', options);
collection.fetch(options);
} catch (excp) {
alert(excp);
}

Categories

Resources