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);
}
});
Related
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>
I want to display fontawesome icon if the user level is equal to 1 or etc. How can i do that in this code. i got an error if i used if else statement inside. Thanks in advance!
function show_product(){
$.ajax({
type : 'ajax',
url : '<?php echo site_url('User/userData')?>',
async : true,
dataType : 'json',
success : function(data){
var html = '';
var i;
var q = '';
for(i=0; i<data.length; i++){
html += '<tr>'+
'<td>'+data[i].create_at+'</td>'+
'<td>'+data[i].user_email+'</td>'+
'<td>'+data[i].user_name+'</td>'+
'<td>'+data[i].user_lastname+'</td>'+
'<td>'if (data[i].user_level == '1') {
++
}'</td>'+
'<td>'+data[i].status+'</td>'+
'</tr>';
}
$('#show_data').html(html);
}
});
}
You can do using the ternary operator
function show_product(){
$.ajax({
type : 'ajax',
url : '<?php echo site_url('User/userData')?>',
async : true,
dataType : 'json',
success : function(data){
var html = '';
var i;
var q = '';
for(i=0; i<data.length; i++){
html += '<tr>'+
'<td>'+data[i].create_at+'</td>'+
'<td>'+data[i].user_email+'</td>'+
'<td>'+data[i].user_name+'</td>'+
'<td>'+data[i].user_lastname+'</td>'+
'<td>'+ data[i].user_level==1?'<i class="fa"></i>':'<i class="fa"></i></td>'
+
'<td>'+data[i].status+'</td>'+
'</tr>';
}
$('#show_data').html(html);
}
});
}
The problem is most likely because the code don't know that you want run the if statement.
'<td>'if (data[i].user_level == '1') as you can see there is nothing separating the string <td> and the statement if (data[i].user_level == '1')
Try something like this:
function show_product() {
$.ajax({
type: 'ajax',
url: '<?php echo site_url('
User / userData ')?>',
async: true,
dataType: 'json',
success: function(data) {
var html = '';
var i;
var q = '';
for (i = 0; i < data.length; i++) {
html += '<tr>' +
'<td>' + data[i].create_at + '</td>' +
'<td>' + data[i].user_email + '</td>' +
'<td>' + data[i].user_name + '</td>' +
'<td>' + data[i].user_lastname + '</td>' +
'<td>';
if (data[i].user_level == '1') {
html += '<i class="fas fas-user"></i>'
}
html += '</td>' +
'<td>' + data[i].status + '</td>' +
'</tr>';
}
$('#show_data').html(html);
}
});
}
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
};
I'm trying to query data using AJAX from a controller, my controller is:
[HttpGet]
public ActionResult GetTestStatus(string userName)
{
var db = new SREvalEntities();
var allTests = db.Tests
.Where(x => string.Equals(x.Owner, userName))
.Select(x => new { CreateDate = x.CreateDate, EndDate = x.EndDate, Status = x.Status })
.OrderByDescending(x => x.CreateDate)
.ToList();
return Json(allTests, JsonRequestBehavior.AllowGet);
}
And my javascript code in an extern file is:
function Filter() {
var userAlias = document.getElementById("UserAliasInput");
var txt = "<tr><th>StartDate</th><th>EndDate</th><th>Status</th><th>Detail</th></tr>";
$.ajax({
url: '/TestStatus/GetTestStatus',
type: "GET",
dataType: "JSON",
data: { userName: userAlias },
success: function (results) {
$.each(results, function (i, result) {
txt += "<tr><td>" + result.CreateDate + "</td>";
txt += "<td>" + result.EndDate + "</td>";
txt += "<td>" + result.Status + "</td>";
txt += "<td>Goto</td></tr>";
});
}
});
$("#ShowDetail").html(txt);
}
When I tried to debug this function, the code will never excute to
$("#ShowDetail").html(txt);
And my page will never be changed. How can I get it work? Thanks.
As you are using $.ajax(), which is asynchronous. Thus the $("#ShowDetail").html(txt) is called before the value is returned from API.
You should set the html() after the each block
function Filter() {
var userAlias = document.getElementById("UserAliasInput");
var txt = "<tr><th>StartDate</th><th>EndDate</th><th>Status</th><th>Detail</th></tr>";
$.ajax({
url: '/TestStatus/GetTestStatus',
type: "GET",
dataType: "JSON",
data: { userName: userAlias.value }, //Use the value property here
success: function (results) {
$.each(results, function (i, result) {
txt += "<tr><td>" + result.CreateDate + "</td>";
txt += "<td>" + result.EndDate + "</td>";
txt += "<td>" + result.Status + "</td>";
txt += "<td>Goto</td></tr>";
});
$("#ShowDetail").html(txt); //Move code to set text here
}
});
}
Try the following function
function Filter() {
var userAlias = $("#UserAliasInput").val();//change this
var txt = "<tr><th>StartDate</th><th>EndDate</th><th>Status</th><th>Detail</th></tr>";
$.ajax({
url: '/TestStatus/GetTestStatus',
type: "GET",
dataType: "JSON",
data: { userName: userAlias },
success: function (results) {
$.each(results, function (i, result) {
txt += "<tr><td>" + result.CreateDate + "</td>";
txt += "<td>" + result.EndDate + "</td>";
txt += "<td>" + result.Status + "</td>";
txt += "<td>Goto</td></tr>";
});
$("#ShowDetail").html(txt);//place this in the success function
}
});
}
I'm having a problem and don't know how to solve it. I have two functions in Javascript, both are called via AJAX, first function get values and insert records in DB and second function reads from DB and show the results. Since first function get values remotely sometimes response times are larger than second function and for that reason second function executes before first. What I need is to call buildTablesFromDB() only if AJAX call for buildClassification() is done. This is how my code looks like:
$(document).ready(function() {
function buildTablesFromDB() {
var request = $.ajax({
type: 'GET',
dataType: 'json',
url: "http://local/parser/reader.php",
success: function(data) {
$("#clasification-data").html();
if (data.response === false) {
$(".alert").show();
$(".close").after(data.error);
} else {
if (data.html_content.position.length != 0) {
$("#clasification-holder").show();
var iterator = data.html_content.position;
var tr = "";
$.each(iterator, function(key, value) {
tr += "<tr>";
tr += '<td><img src="' + value.team_image + '" alt="' + value.team_name + '" title="' + value.team_name + '"> ' + value.team_name + '</td>';
tr += '<td>' + value.team_jj + '</td>';
tr += '<td>' + value.team_jg + '</td>';
tr += '<td>' + value.team_jp + '</td>';
tr += '<td>' + value.team_difference + '</td>';
tr += '<td><span class="glyphicon glyphicon-play"></span><span class="glyphicon glyphicon-stop"></span></td>';
tr += '</tr>';
});
$("#clasification-data").html(tr);
}
}
},
error: function() {
request.abort();
}
});
}
function buildClassification() {
var request = $.ajax({
type: 'GET',
dataType: 'json',
url: "http://local/parser/parser.php",
success: function(data) {
if (data.response === false) {
// some error
}
},
error: function() {
request.abort();
}
});
}
window.setInterval(function() {
buildClassification();
}, 1800000); // Updates table results each 30 minutes
window.setInterval(function() {
buildTablesFromDB();
}, 1800000); // Updates table results each 30 minutes
buildClassification();
buildTablesFromDB();
});
How I can get this done?
you can call buildTablesFromDB() in the callback method of buildClassification()
e.g.
....
dataType: 'json',
url: "http://local/parser/parser.php",
success: function(data) {
if (data.response === false) {
//
}else{
buildTablesFromDB();
}
},