How to retrieve files from Sharepoint Document library Folders - javascript

I have two folders in my document library, that two folders are created automatically based on the year when the file was uploaded. Now what I need to do is Retrieve the file from multiple files.How can I achieve this using javascript...
My Function for Uploading file and create a folder based on year
onclick="fileUpload('Improvement-Projects','improvementprojects')
function fileUpload(divId , fileId) {
var clientContext;
var oWebsite;
var oList;
var itemCreateInfo;
var resultpanel = "MySite";
clientContext = new SP.ClientContext.get_current();
oWebsite = clientContext.get_web();
oList = oWebsite.get_lists().getByTitle("QualityCI");
itemCreateInfo = new SP.ListItemCreationInformation();
itemCreateInfo.set_underlyingObjectType(SP.FileSystemObjectType.folder);
var d = new Date();
var n = d.getFullYear();
var dynfloder = itemCreateInfo.set_leafName(divId + '-' + n.toString());
alert(dynfloder);
this.oListItem = oList.addItem(itemCreateInfo);
this.oListItem.update();
clientContext.load(this.oListItem);
clientContext.executeQueryAsync(
Function.createDelegate(this, successHandler),
Function.createDelegate(this, errorHandler)
);
And function to retrieve the files
var d = new Date();
var n = d.getFullYear();
fileGetAction("/sites/Sitename/QualityCI" + '/' + divId + '-' + n.toString());
function fileGetAction(folderUrl) {
if ($.fn.DataTable.isDataTable('#table_id')) {
$('#table_id').DataTable().destroy();
}
$('#table_id tbody').empty();
var requestURL = _spPageContextInfo.webAbsoluteUrl
+ "/_api/web/GetFolderByServerRelativeUrl('" + folderUrl + "')/Files";
$.ajax({
url: requestURL,
type: "GET",
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
complete: function (data) {
console.log("folder: " + folderUrl + " - files: ", data);
var dynamicTable = "";
for (j = 0; j < data.responseJSON.d.results.length; j++) {
var tableData = data.responseJSON.d.results[j];
dynamicTable += "<tr>";
dynamicTable += "<td>" + tableData.Name.split('.').slice(0, -1).join('.') + "</td>";
dynamicTable += "<td>" + ' "' + tableData.Name + '"' + "</td>";
dynamicTable += "<td class='text-center'>" + '<a class="btn btn-primary delete" onclick="javascript: fileDeleteAction(\'' + tableData.ServerRelativeUrl + '\',\'' + folderUrl + '\');">Delete</a>' + "</td>";
dynamicTable += "</tr>";
}
document.getElementById("datatable").innerHTML = dynamicTable;
table = $('#table_id').DataTable();
},
error: function (err) {
console.error("Error: ", err);
}
});
}
This is working fine.But my requirement is if the folder name is Improvement-Projects-2020 then that folder data only I can retrieve I want to retrieve Improvement-Projects-2019 files also Please help me

Use promise, you could request multiple requests and get return data from these requests and then bind the data.
Sample script:
<script>
var d = new Date();
var n = d.getFullYear();
fileGetAction("/sites/dev/QualityCI" + '/Improvement-Projects-' + n.toString(),"/sites/dev/QualityCI" + '/Improvement-Projects-' + (n-1).toString());
function fileGetAction(...args) {
if(arguments.length==0){
console.log("There is no corresponding folder in the library")
return;
}
var reqs=new Array()
$('#table_id tbody').empty();
var dynamicTable = "";
for(var i=0;i<args.length;i++){
var folderUrl=args[i]
var requestURL = _spPageContextInfo.webAbsoluteUrl+ "/_api/web/GetFolderByServerRelativeUrl('" + folderUrl + "')/Files";
reqs[i] = _ajax(requestURL)
}
Promise.all(reqs).then((result) => {
var dynamicTable = "";
for (j = 0; j < result.length; j++) {
for(var x=0;x<result[j].d.results.length;x++){
var tableData = result[j].d.results[x]
dynamicTable += "<tr>";
dynamicTable += "<td>" + tableData.Name.split('.').slice(0, -1).join('.') + "</td>";
dynamicTable += "<td>" + ' "' + tableData.Name + '"' + "</td>";
dynamicTable += "<td class='text-center'>" + '<a class="btn btn-primary delete" onclick="javascript: fileDeleteAction(\'' + tableData.ServerRelativeUrl + '\',\'' +args[j] + '\');">Delete</a>' + "</td>";
dynamicTable += "</tr>";
}
}
document.getElementById("datatable").innerHTML = dynamicTable;
table = $('#table_id').DataTable();
}).catch((error) => {
console.log(error)
})
}
function _ajax(requestURL){
return new Promise((resolve, reject) => {
$.ajax({
url: requestURL,
type: "GET",
headers: {
"Accept": "application/json;odata=verbose"
},
success: function(data) {
resolve(data)
},
error: function(error) {
reject(error)
}
})
})
}
</script>

Related

if else Ajax success restapi Sharepoint Online

Im trying to show a custom 'No new uploads' message when the rest api returns no entries on Success event. The code below works perfect when rows are returned on Success event and shows blank on 0 entries.
I tried implementing if else statement with no luck. Kindly assist.
$(function(){
var today = new Date();
today = moment(today).format("YYYY-MM-DD");
var currentDate = today+'T00:00:00.000Z';
var requestUri = "#SPO_SITE#/_api/web/lists/getbytitle('LIST_NAME')/items?$top=20000&$select=DistrDate,EncodedAbsUrl&$filter= DistrDate ge datetime'" +currentDate+ "'";
$.ajax({
url: requestUri,
type: "GET",
headers: {
"accept":"application/json; odata=verbose"
},
success: onSuccess,
});
function onSuccess(data) {
var objItems = data.d.results;
var tableContent = '<table id="mbrTable" style="width:100%"><caption class="text-info">Report</caption>';
for (var i = 0; i < objItems.length; i++) {
tableContent += '<tr>';
tableContent += '<td>' + moment(objItems[i].DistrDate).format("DD-MM-YYYY") + " - " + "<a target='_blank' href=" + objItems[i].EncodedAbsUrl + ">" + "View" + "</a>" + '</td>';
tableContent += '</tr>';
}
document.getElementById("mbrTable").innerHTML = (tableContent);
}
});
Following fixed the issue.
$(function(){
var today = new Date();
today = moment(today).format("YYYY-MM-DD");
var currentDate = today+'T00:00:00.000Z';
var requestUri = "#SPO_SITE#/_api/web/lists/getbytitle('LIST_NAME')/items?$top=20000&$select=DistrDate,EncodedAbsUrl&$filter= DistrDate ge datetime'" +currentDate+ "'";
$.ajax({
url: requestUri,
type: "GET",
headers: {
"accept":"application/json; odata=verbose"
},
success: onSuccess,
});
function onSuccess(data) {
var objItems = data.d.results;
if (objItems.length == 0) {
var tableContent = '<table id="mbrTable" style="width:100%"><caption class="text-info">Report</caption><tr><td>No new uploads</td></tr>';
}
else {
var tableContent = '<table id="mbrTable" style="width:100%"><caption class="text-info">Report</caption>';
for (var i = 0; i < objItems.length; i++) {
tableContent += '<tr>';
tableContent += '<td>' + moment(objItems[i].DistrDate).format("DD-MM-YYYY") + " - " + "<a target='_blank' href=" + objItems[i].EncodedAbsUrl + ">" + "View" + "</a>" + '</td>';
tableContent += '</tr>';
}
}
document.getElementById("mbrTable").innerHTML = (tableContent);
}
});

Export button in datatable does not take filters into consideration

im new here , i write you because i have a problem when i export data from datatable i export the data without filtring : here is my code javascript
$('#returnview').DataTable({
pagingType: "full_numbers",
bInfo: false,
dom: 'lBfrtip',
buttons: [
'copyHtml5',
'excelHtml5'
],
function: showReturnViewData()
});
function showReturnViewData() {
var contractType = $("#contractTypes").val();
var company = $("#company").val();
var year = $("#selectdate").val();
var tbody = document.getElementById('tbody');
tbody.innerHTML = ''
$.ajax({
url: "api/Operations/showReturnViewData",
async: false,
dataType: "json",
data: { contractType, company, year },
success: function (data) {
var displayReturnView = JSON.parse(data.returnViewData);
for (var i = 0; i < displayReturnView.length; i++) {
var tr = "<tr>";
var sum = 0;
sum += parseInt(displayReturnView[i].Decommissioned) + parseInt(displayReturnView[i].LocalStock) + parseInt(displayReturnView[i].Return)
+ parseInt(displayReturnView[i].Replace) + parseInt(displayReturnView[i].Missing) + parseInt(displayReturnView[i].UnRepair)
+ parseInt(displayReturnView[i].Used) + parseInt(displayReturnView[i].Repair);
tr += "<td><a style='cursor: pointer; text-decoration: underline; color: blue;' target='_blank' href='/DecommissioningTarget?contractType=" + contractType+"&&company=" + company + "&&date=" + displayReturnView[i].DecommissioningdDate + "'>" + displayReturnView[i].DecommissioningdDate + "</a></td>" + "<td>" + displayReturnView[i].Decommissioned +
"</td>" + "<td>" + displayReturnView[i].Return + "</td>" + "<td>" + displayReturnView[i].LocalStock + "<td>"
+ displayReturnView[i].Replace + "<td>" + displayReturnView[i].Used + "</td>"+
"<td>" + displayReturnView[i].Repair + "</td>" + "<td>" + displayReturnView[i].UnRepair + "</td>"
+ "<td>" + displayReturnView[i].Missing + "</td>" + "<td>" + sum + "</td>"
"</td></tr>";
tbody.innerHTML += tr;
}
}
});
var x = document.getElementById("returnview").rows.length;
document.getElementById("rvEntries").innerHTML = x - 1;
}
Try
name of param
get string in the method variable
| | |
data: JSON.stringify({ contractType: contractType }),
or:
data: JSON.stringify({ contractType: $("#contractTypes").val() }),
multiple args:
data: JSON.stringify({ contractType: contractType, company: company, year: year }),
etc...

unable to load html table through onclick

I have a function which loads a html table with sql data query and a html page to display the table when i click the button but it is not showing the table, it just shows the url changing to match my search but does not display the table
Function code:
function Search()
{
var search = new Object;
search.restaurantName = document.getElementById("searchinput").value; //get input
var searchrestaurant = new XMLHttpRequest();
searchrestaurant.open("POST", Search_url, true);
searchrestaurant.setRequestHeader("Content-Type", "application/json");
searchrestaurant.onload = function()
{
search_array = JSON.parse(request.responseText);
result();
}
searchrestaurant.send(JSON.stringify(search));
}
function result()
{
var table = document.getElementById("result");
table.innerHTML = "";
result = search_array.length
for (var count = 0; count < result; count++)
{
// data from sql
var restaurant_name = search_array[count].restaurant_name;
var Description = search_array[count].Description;
var location = search_array[count].location;
var thumbnail = search_array[count].thumbnail;
var price = search_array[count].price;
var rating = search_array[count].avg_rating;
//table to show all sql data
var AllrestaurantTable = "<table class = fixed style=width:100% border=1px>" +
"<tr>"+
"<td>" +"<a href = 'detailed_restaurant.html' target ='_blank'>"+"<img src ='" + thumbnail + "'style=width:100px;height:100px;></img>"+"</td>" +
"<td>"+"<a href = 'detailed_restaurant.html' target ='_blank'>"+ restaurant_name + "</td>" +
"<td>"+ location + "</td>" +
"<td>"+ Description + "</td>" +
"<td>"+ price + "</td>" +
"<td>"+ rating + "</td>"
"</tr>" +
"</table>";
table.insertAdjacentHTML('beforeend', AllrestaurantTable);
}
}
Html:
<body>
<form id = "SearchForm">
<label>Search </label>
<input type="text" id="searchinput" name="restaurantName">
<input type="button" onclick="Search()" value="Submit">
</form>
<div class="container"></div>
<div id="result" class="row"></div>
</div>
I have already loaded the script into the html site but it is just take my input and does not display the table i created
Concatenation operator is missing after "<td>" + rating + "</td>".
Add the + operator. like "<td>" + rating + "</td>" +.
function result() {
var table = document.getElementById("result");
table.innerHTML = "";
result = 5
for (var count = 0; count < result; count++) {
// data from sql
var restaurant_name = 1;
var Description = 'ddf';
var location = 'location';
var thumbnail = 1;
var price = 'Price';
var rating = 'rating';
//table to show all sql data
var AllrestaurantTable = "<table class = fixed style=width:100% border=1px>" +
"<tr>" +
"<td>" + "<a href = 'detailed_restaurant.html' target ='_blank'>" + "<img src ='" + thumbnail + "'style=width:100px;height:100px;></img>" + "</td>" +
"<td>" + "<a href = 'detailed_restaurant.html' target ='_blank'>" + restaurant_name + "</td>" +
"<td>" + location + "</td>" +
"<td>" + Description + "</td>" +
"<td>" + price + "</td>" +
"<td>" + rating + "</td>" +
"</tr>" +
"</table>";
table.insertAdjacentHTML('beforeend', AllrestaurantTable);
}
}
result();
<div id="result" class="row"></div>
</div>
You have to pass the search array in your result function.
function Search() {
var search = new Object;
search.restaurantName = document.getElementById("searchinput").value; //get input
var searchrestaurant = new XMLHttpRequest();
searchrestaurant.open("POST", Search_url, true);
searchrestaurant.setRequestHeader("Content-Type", "application/json");
searchrestaurant.onload = function () {
search_array = JSON.parse(request.responseText);
result(search_array);
}
searchrestaurant.send(JSON.stringify(search));
}
Hope this will work.

Active or Inactive on Button click in ASP.Net MVC?

I am getting return json data from server,every value is inserted in table except status.
<script>
$(document).ready(function () {
$("#DomainID").change(function () {
var id = $(this).val();
$("#example tbody tr").remove();
$.ajax({
type: 'POST',
url: '#Url.Action("ViewModules")',
dataType: 'json',
data: { id: id },
success: function (data) {
var items = '';
$.each(data.EmpList, function (i, item) {
$("#findValue").show();
/*Find Role here - Comparing Emp List ModuleId to RoleList ModuleId*/
var RoleName = $(data.role).filter(function (index, item) {
return item.ModuleID == item.ModuleID
});
if (item.ParentModuleID == -1) {
item.ModuleName = " -- " + item.ModuleName
}
else {
item.ModuleName = item.ModuleName
}
if (item.Status == "Y") {
item.Status = + '<img src="~/img/Active.png" height="32" width="32"/>'
}
else (item.Status == "N")
{
item.Status = + '<img src="~/img/InActive.png" height="32" width="32"/>'
}
var t = i + 1;
var rows = "<tr>"
+ "<td>" + t + "</td>"
+ "<td>" + item.ModuleName + "</td>"
+ "<td>" + item.Url + "</td>"
+ "<td>" + RoleName[i].RoleName + "</td>"
+ "<td>" + '' + item.Status + "</td>"
+ "</tr>";
$('#example tbody').append(rows);
});
},
error: function (ex) {
var r = jQuery.parseJSON(response.responseText);
alert("Message: " + r.Message);
alert("StackTrace: " + r.StackTrace);
alert("ExceptionType: " + r.ExceptionType);
}
});
return false;
});
});
</script>
}
if item.Status == "N" means InActive image will display and if item.Status == "Y" means Active image will display
But in my code Status Value i didn't get any idea.?
Controller:
public ActionResult ViewModules(int id)
{
Domain_Bind();
dynamic mymodel = new ExpandoObject();
userType type = new userType();
List<ViewRoleModules> EmpList = type.GetRoleModulesViews(id);
List<ViewRoleModules> RoleList;
List<ViewRoleModules> role = new List<ViewRoleModules>();
foreach (ViewRoleModules emp in EmpList)
{
RoleList = type.GetSiteRoleModulesViews(emp.ModuleID);
foreach (ViewRoleModules vip in RoleList)
{
role.Add(new ViewRoleModules
{
RoleName = vip.RoleName,
ModuleID = vip.ModuleID
});
}
}
var data = new { EmpList = EmpList, role = role };
return Json(data, JsonRequestBehavior.AllowGet);
}
Your code is a bit of a mess to be honest with several syntax errors. Hope this helps:
$.ajax({
type: 'POST',
url: '#Url.Action("ViewModules")',
dataType: 'json',
data: { id: id },
success: function (data) {
$.each(data.EmpList, function (i, item) {
$("#findValue").show();
var roleName = $(data.role).filter(function (index, item) {
return item.ModuleID == item.ModuleID
});
var moduleName = item.ModuleName;
if (item.ParentModuleID == -1) {
moduleName = " -- " + moduleName;
}
var status = '';
if (item.Status == "Y") {
status = '<img src="~/img/Active.png" height="32" width="32"/>';
} else {
status = '<img src="~/img/InActive.png" height="32" width="32"/>';
}
var row = "<tr>" +
"<td>" + (i + 1) + "</td>" +
"<td>" + moduleName + "</td>" +
"<td>" + item.Url + "</td>" +
"<td>" + roleName[i].RoleName + "</td>" +
"<td>" + status + "</td>" +
"</tr>";
$('#example tbody').append(row);
});
},
error: function (ex) {
var r = jQuery.parseJSON(response.responseText);
alert("Message: " + r.Message);
alert("StackTrace: " + r.StackTrace);
alert("ExceptionType: " + r.ExceptionType);
}
});

400 bad request while passing object and value to url

I know how to pass data in url in json or with plain parameters but this is something different
see the below image :-
http://www.tiikoni.com/tis/view/?id=23d9b98
My api Url /geniedoc/api/doctor/Search
as we can see one thing is in object and two paramater is simply passing
can you suggest me a ajax call?
my ajax call
function getNewSlotContent(startIndex, totalRows) {
var skipindex = 0;
if (startIndex > 1) {
skipindex = totalRows;
}
var totalrows = totalRows + 10;
var searchByName = document.getElementById("searchByName").value;
var selectedSpeciality = document.getElementById("searchByName").value;
if (selectedSpeciality != null || selectedSpeciality != "") {
selectedSpeciality = encodeURIComponent(selectedSpeciality);
}
$("#preloader").addClass("pageload");
$("#preloader").show();
var dataString = '{"firstName":"'+ searchByName + '","start_index":"' + skipindex + '","rows":"' + totalrows +'"}';
console.log(dataString);
$.ajax({
type: 'POST',
url : '/geniedoc/api/doctor/search',
data: dataString,
contentType: 'application/json',
dataType: 'json',
headers: {'Content-Type':'application/json'},
timeout: 100000,
success: function(data) {
var op = "";
for (doctor in data.response.rows) {
op += '<div class="post-sec">';
op += '<img src="/geniedoc/ajax/data/displayImage?fileName=' + data.response.rows[doctor].profilePicId + '" alt="">';
if (data.response.rows[doctor].prefix == null) {
data.response.rows[doctor].prefix = "";
}
op += '<a target="_blank" href="/doctor/' + data.response.rows[doctor].seo_name + '/' + data.response.rows[doctor].idKey + '" class="title"> ' + data.response.rows[doctor].prefix + ' ' + data.response.rows[doctor].firstame + ' ' + data.response.rows[doctor].last_name + '</a>';
op += '<span class="date">' + data.response.rows[doctor].speciality_id + '</span>';
op += '</div>';
op += '<div class="clear"></div>';
}
$("#preloader").hide();
$("#preloader").removeClass("pageload");
$("#doctor-data").html(op);
},
error: function(e) {
console.log("ERROR: ", e);
},
done: function(e) {
console.log("DONE");
}
});
}
Modify your dataString like this :
var dataString = {
"firstName":searchByName,
"start_index": skipindex,
"rows": totalrows
};

Categories

Resources