Full url sharepoint item in Javascript - javascript

I'm trying to get the ContentTypeId of an item in sharepoint to get the full url of the item to get the binary of it and after send it to another plateform.
So here i put this code in element.xml to get the list ID and the document ids of the items i'm selecting, after this i send them to an ASPX page in a Sharepoint Dialog to define the destination of the items and after this in the postback, stream the binary and send it to the another platform. The problem is : To get the full url of my items i need ListId, ItemId and ContentTypeId.
Because i've found a code to stream the binary here :
How to Programatically Download files from sharepoint document library
And i need the full url of my items.
Any idea?
thanks
var iddocs ='';
var listId ='';
function geturl()
{
var context = SP.ClientContext.get_current();
this.web = context.get_web();
listId = SP.ListOperation.Selection.getSelectedList();
var list = this.web.get_lists().getById(listId);
var ok = false;
try
{
if ( SP.ListOperation.Selection.getSelectedItems(context) !== false)
{
var items = SP.ListOperation.Selection.getSelectedItems(context);
var url='listId:'+listId+ ' Number of selected items: ' + items.length ;
var i = 0;
if(items.length==0)
{
}else{
while( i != items.length )
{
url += ' Doc' + i + ': ' + items[i].id;
if(i>0){iddocs += '-'};
iddocs += items[i].id;
i++;
};
ok = true;
alert(url+' Id of clicked item:'+{ItemId});
};
};
}
catch(err)
{
};
return ok;
};
function OpenDialog(pidliste) {
var options = SP.UI.$create_DialogOptions();
options.width = 600;
options.height = 600;
options.title = 'Envoyer vers Nuxeo';
options.url ='/_Layouts/SPTest.CustomMenuItem/index.aspx?click={ItemId}';
if(pidliste){options.url += '&ids='+pidliste +'-'+ iddocs;};
options.dialogReturnValueCallback = Function.createDelegate(null, CloseCallback);
SP.UI.ModalDialog.showModalDialog(options);
}
function CloseCallback(result, target) {
if (result == SP.UI.DialogResult.OK) {
}
if (result == SP.UI.DialogResult.cancel) {
SP.UI.Notify.addNotification('Opération canceled', false, '', null);
}
}
if(geturl())
{
OpenDialog(listId);
}else{
alert('Please select an item');
};

I've found the solution. In fact, items can be reached via :
{SiteUrl}+{ItemUrl}
The download function is linked in my first Post. But it doesn't work for multiple items, with this method you can only reach the properties of the item you're selecting.
You have to note that if you want to access to a SP file, you have to set your request.credential via :
request.Credentials = System.Net.CredentialCache.DefaultCredentials;
which will take the current credential you're using.
Hope it helps.

Related

Delete element from array when deleting record from localStorage

I have a localStorage object like this:
Key: jpxun
Value: [{"id":"0","name":"royal"},{"id":"1","name":"tippins"},{"id":"4","name":"leviosa"},{"id":"5","name":"vicious"}]
I have this JS to display output the localStorage:
var jpxun = JSON.parse(localStorage.getItem('jpxun')) || [];
if (jpxun) {
var jpxun_length = jpxun.length;
} else {
var jpxun_length = 0;
}
var hst = document.getElementById("usernames");
var MyUsernames = JSON.parse(localStorage.getItem("jpxun"));
if (jpxun_length > 0) {
// declare array to hold items for outputting later in plain text format
var plain_text_array = [];
for (var i = 0; i < MyUsernames.length; i++) {
var un1 = MyUsernames[i].name;
hst.innerHTML += "<li>" +"<a id="+MyUsernames[i].id + " href='#content' onclick='deleteById(this)'>x </a>" + un1 + "</li>";
// add word to plain text array
plain_text_array.push(un1);
}
}
Each element is outputted in a list item with an 'x' as a hyperlink so that it can be clicked and that element is deleted from localStorage.
This is the code to delete the item from localStorage:
var deleteById = function ( self ){
MyUsernames = MyUsernames.filter(function(elem) {
return elem.id !== self.id;
});
localStorage.setItem("jpxun",JSON.stringify(MyUsernames));
self.parentNode.parentNode.removeChild(self.parentNode);
}
That works fine.
Unfortunately I don't really understand how the code works in deleteById.
As that is the case, I am stuck on working out how to delete the corresponding record from plain_text_array when its value is deleted from localStorage.
I would try to find the text in the array thats includes that string 'id="item_id"':
plain_text_array = plain_text_array.filter(item => !item.includes(`id="${self.id}"`));
Just add it in the end of deleteById function.

How I can get object from another function

I'm trying to do a Shopping cart with HTML and JS. So I'm using (https://www.smashingmagazine.com/2019/08/shopping-cart-html5-web-storage/).
In my function save(), I have,
`function save(id, title, price) {
// var button = document.getElementById('button');
// button.onclick=function(){
// var test = localStorage.setItem('test', id);
window.location.href='/panier'
var obj = {
title: title,
price: price
};
localStorage.setItem(id, JSON.stringify(obj));
var test = localStorage.getItem(id);
var getObject = JSON.parse(test);
console.log(getObject.title);
console.log(getObject.price);
}`
so to get "title for example I don't have problem in my function save(), but in my function doShowAll(),
function CheckBrowser() {
if ('localStorage' in window && window['localStorage'] !== null) {
// We can use localStorage object to store data.
return true;
} else {
return false;
}
}
function doShowAll() {
if (CheckBrowser()) {
var key = "";
var id = localStorage.getItem(id);
var list = "<tr><th>Item</th><th>Value</th></tr>\n";
var i = 0;
//For a more advanced feature, you can set a cap on max items in the cart.
for (i = 0; i <= localStorage.length-1; i++) {
key = localStorage.key(i);
list += "<tr><td>" + key + "</td>\n<td>"
+ localStorage.getItem(key) + "</td></tr>\n";
}
//If no item exists in the cart.
if (list == "<tr><th>Item</th><th>Value</th></tr>\n") {
list += "<tr><td><i>empty</i></td>\n<td><i>empty</i></td></tr>\n";
}
//Bind the data to HTML table.
//You can use jQuery, too.
document.getElementById('list').innerHTML = list;
} else {
alert('Cannot save shopping list as your browser does not support HTML 5');
}
}
I can't to get my object.
I have tried:
if (CheckBrowser()) {
var key = "";
var id = localStorage.getItem(id);
var getObject = JSON.parse(test);
}
var list = "<tr><th>Item</th><th>Value</th></tr>\n";
var i = 0;
//For a more advanced feature, you can set a cap on max items in the cart.
for (i = 0; i <= localStorage.length-1; i++) {
key = localStorage.key(i);
list += "<tr><td>" + key + "</td>\n<td>" + getObject.title
+ localStorage.getItem(key) + "</td></tr>\n";
}
but when I add something else than key or localStorage.getItem(key) in "list +=" nothing is displayed in my html view.
So I just Want to display data from my object in the PHP array in doShowAll() function.
Hoping to have clear and wainting a reply. Thank you

injecting data from URL to inputbox

I want to add some data from url to an input-box with an unique name ( not id ) , Because I don't have any accesses on the page I can't edit it with ids or sth.
<input type="text" name="test">
and sth like that :
site.com/index.php?test=text123
Ok from what I understand, You want to put get data from URL into your input fields.
First, when you open the tab, put the 'document' of the tab into a global variable
var url = "www.url.com"; //the url of the page to open in tab
var tabInstance= window.open(url);
tabDocument = tabInstance.document; //tabDocument is a global variable
Now, assuming the data you want to put into the tab is in the URL of the page that is opening the tab
function populateInputFields(){
var data = parseURLParams(document.URL); //get url data in json format.
if(!data) return; //if no get parameters found
//iterate json
for(var key in data){//for each key in the json data
var value = data[key]; //get the 'value' for corresponding key
var element = tabDocument.getElementsByTagName(key)[0];//get the input element
if(element && element.tagName == 'input'){//check if element exists and is of type input
element.value = value;
}
}
}
Implementation of parseURLParams take from here: How to read GET data from a URL using JavaScript?
function parseURLParams(url) {
var queryStart = url.indexOf("?") + 1,
queryEnd = url.indexOf("#") + 1 || url.length + 1,
query = url.slice(queryStart, queryEnd - 1),
pairs = query.replace(/\+/g, " ").split("&"),
parms = {}, i, n, v, nv;
if (query === url || query === "") {
return;
}
for (i = 0; i < pairs.length; i++) {
nv = pairs[i].split("=");
n = decodeURIComponent(nv[0]);
v = decodeURIComponent(nv[1]);
if (!parms.hasOwnProperty(n)) {
parms[n] = [];
}
parms[n].push(nv.length === 2 ? v : null);
}
return parms;
}

How to delete a specific value in a cookie - jquery

I am developing a shopping cart system, where the user can add or remove products to his or her basket.
I am storing 2 things for each product in the product cookie: product barcode and price.
My code so far looks like this:
var addToBasketHandler = $(".add-product");
var removeFromBasketHandler = $(".unselect");
var Basket = {
select: function (box, cookie) {
box.addClass("selected");
var ean = box.attr('ean');
var value = box.find($(".price strong")).html().replace(/[^0-9\.]/g, '');
if ($.cookie(cookie) == undefined) {
$.cookie(cookie, ean + "~" + value);
} else if ($.cookie(cookie).indexOf(ean) == -1) {
$.cookie(cookie, $.cookie(cookie) + "|" + ean + "~" + value);
}
},
deselect: function (box, cookie) {
box.removeClass("selected");
// code to delete the cookie value
}
};
$(document).ready(function () {
$(addToBasketHandler).click(function () {
var box = $(this).parents(".box-offer");
Basket.select(box, "productCookie");
});
$(removeFromBasketHandler).click(function () {
var box = $(this).parents(".box-offer");
Basket.deselect(box, "productCookie");
});
});
And after adding 3 products to my cart, my cookie looks like this:
productCookie = 9918430821007~12.00 | 7C9918430831006~3.00 | 7C7501031311309~50.30
Please help on how I could remove only the selected product from this cookie list above.
FYI I am using jquery + jquery cookie
Try
deselect: function (box, cookie) {
box.removeClass("selected");
var ean = box.attr('ean');
var value = box.find($(".price strong")).html().replace(/[^0-9\.]/g, '');
var val = ean + "~" + value; //value to be removed
if ($.cookie(cookie) !== undefined) {
var cookie_val = $.cookie(cookie);
if (cookie_val.indexOf(val) !== -1) { //check value present in cookie
var arr = cookie_val.replace(' ', '').split('|'); //remove spaces and split with |
var index = arr.indexOf(val);//get index of value to be deleted
arr.splice(index, 1); //remove value from array
$.cookie(cookie, arr.join(' | ')); //convert array to sting using join and set value to cookie
}
}
}

simple code to Show / Hide with cookie

Does anyone know a code as simple as possible to show / hide HTML.
With:
-Store the cookies option
-Effect to the Show / Hide
The jquery cookie plugin could simplify cookie management. As far as showing/hiding HTML is concerned you may take a look at the show() and hide() methods.
It really depends on the event/reason the content needs to show/hide...
Is it user specific content that must appear for a particular user, if so, how are you identifying the user (sessions, openID)?
Or is it event driven, ie, a user clicks on a button and content shows/hides and the cookie stores the show/hide state?
Damo
Probably more than you need, but I use this with the tablesorter plugin to collapse/expand sections of tables, store the state in the cookie and with .toggle() you can get a nice effect.
function tableContainer(id,visible,sortColumn,sortOrder){
this.ID = id;
this.Visible = visible;
this.SortColumn = sortColumn;
this.SortOrder = sortOrder;
}
function bindTableHeaders(element){
//Bind click handler to the table THs to update object as to current sort column.
$("thead th","#" + element).bind("click",function(){
var order = this.order
var column = this.column
var $table = $(this).closest("table")
var visible = $table.attr("expanded") //Technically I suppose if you can click these then it must be visible
var id = $table.attr("id")
var tableObj = new tableContainer(id,visible,column,order);
$.cookie(element, JSON.stringify(tableObj), { secure: true }); //Write the current state into the section cookie
});
};
function recoverState(element) {
// pull cookie for page state and visibility
var elementData = $.cookie(element);
if (elementData != null){
// parse JSON based on object representation
var json = JSON.parse(elementData)
var id = json.ID;
var visible = json.Visible;
var sortColumn = json.SortColumn == undefined ? 0 : json.SortColumn
var sortOrder = json.SortOrder == undefined ? 0 : json.SortOrder
} else {
var id = element;
var visible = "true"
var sortColumn = 0;
var sortOrder = 0;
}
// switch visibility
if(visible == "false"){
toggleElement(element)
}
// Determine if this section has any data (eg. a <tbody>)
if ($("tbody","#" + id).length == 0 || $("tbody","#" + id).html() == "")
return
if (pageAction == "Edit"){
$("#" + id).tablesorter({widgets: ['zebra'], sortList: [[sortColumn,sortOrder]]});
} else {
$("#" + id)
.collapsible("td.collapsible",{
collapse:true
})
.tablesorter({widgets: ['zebra'], sortMultiSortKey:'false', sortList: [[sortColumn,sortOrder]]});
}
}
function toggleElement(element) {
if ($("#" + element).attr("expanded") == "true"){
$("#" + element).attr("expanded","false")
$("#" + element).hide();
var isVisible = "false"
} else {
$("#" + element).attr("expanded","true")
$("#" + element).show();
var isVisible = "true"
}
//Rewrite the cookie for this section changing only the visibility
var elementData = $.cookie(element);
var visible = isVisible;
if (elementData != null){
var json = JSON.parse(elementData)
var id = json.ID;
var sortColumn = json.SortColumn;
var sortOrder = json.SortOrder;
} else {
var id = element
var sortColumn = 0;
var sortOrder = 0;
}
var tableObj = new tableContainer(id,visible,sortColumn,sortOrder);
$.cookie(element, JSON.stringify(tableObj), { secure: true }); //Write the current state into the section cookie
}

Categories