I need to make recursive RestAPI calls to overcome the 5000 view threshold of SharePoint online. Below code goes into a loop after generating the first 5000 entries. It generates the datatable and then increments into displaying the same data in a loop. I totally have only 8800 entries in my SharePoint list.
I just need to generate the 1st batch of 5000 entries and then the second batch of 3800 entries using recursive calls and display the concat data in Jquery Datatables.
$(document).ready(function() {
var table = $('#table_id').DataTable({
"pageLength": 100,
"dom": 'Bfrtip',
"buttons": [searchBuilder, copy],
"aoColumns": [{"mData": "Created"}, {"mData": "EncodedAbsUrl"}]
});
var response = response || [];
var listURL = "SPO_Site/_api/web/lists/getbytitle('List_Name')/items?$top=5000&$select=Created,EncodedAbsUrl";
GetListItemsRecursive(listURL);
function GetListItemsRecursive() {
$.ajax({
url: listURL,
type: "GET",
dataType: "json",
headers: {
"accept": "application/json;odata=verbose"
},
success: mySuccHandler,
error: myErrHandler
});
}
function mySuccHandler(data) {
response = response.concat(data.d.results);
console.log(data);
if (data.d.__next) {GetListItemsRecursive(data.d.__next);}
try {table.rows.add(response).draw();}
catch (e) {alert(e.message);}
}
function myErrHandler(data, errMessage) {alert("Error");}
});
My test cide for your reference:
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.24/css/jquery.dataTables.css">
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.24/js/jquery.dataTables.js"></script>
<script>
$(document).ready(function () {
var response = response || [];
var listURL = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('testn')/items?$top=5000&$select=ID,Title";
GetListItemsRecursive(listURL);
function GetListItemsRecursive(listURL) {
$.ajax({
url: listURL,
type: "GET",
dataType: "json",
async: false,
headers: {
"accept": "application/json;odata=verbose"
},
success: mySuccHandler,
error: myErrHandler
});
}
function mySuccHandler(data) {
console.log(data)
response = response.concat(data.d.results.map(e=>[e.ID,e.Title]));
console.log(response);
if (data.d.__next) { GetListItemsRecursive(data.d.__next); }
// try { table.rows.add(response).draw(); }
// catch (e) { alert(e.message); }
}
function myErrHandler() {
}
$('#table_id').DataTable({
data: response,
columns: [
{ title: "ID" },
{ title: "Title" }
]
});
})
</script>
<table id="table_id" class="display"></table>
Test result:
Related
This is the code for fetching the data from database using Json and displaying it in handsontable. I checked in console and it shows the data I am getting from database but somehow that data is not being displayed in handsontable.
```
<div id="example"></div>
<script type="text/javascript">
const container = document.getElementById('example');
var hot = new Handsontable(container, {
// data: getData(),
rowHeaders: true,
colHeaders: true,
licenseKey: 'non-commercial-and-evaluation',
colHeaders: true
});
$(document).ready(function () {
var result = null;
$.ajax({
url: 'someurl',
type: 'post',
dataType: 'json',
async: false,
success: function (res) {
result = res;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
console.log(result);
var resultdata = JSON.parse(JSON.stringify(result));
hot.loadData(resultdata);
});
</script>
This is the Code from controller that is fetching the data from the database and returning it. I don't know if I am returning right type of data or if the data returned needs to be serialized. Can anyone help me with this? I will really appreciate any help from anyone
public class SupplierTypeController : BaseController
{
[HttpGet]
public JsonResult Index()
{
IEnumerable<SupplierTypeDto> supplierType = new List<SupplierTypeDto>();
var apiResponse = Post<List<SupplierTypeDto>>("api/SupplierType/SuppliersType", null);
if (apiResponse != null)
{
if (apiResponse.Success)
{
supplierType = apiResponse.Data;
}
}
else
{
ShowErrorMesage(ResponseMessages.API_NoResponse);
}
return Json(supplierType,JsonRequestBehavior.AllowGet);
}
}
Im getting the following error on my Ajax post back {"readyState":0,"status":0,"statusText":"error"}
on my first ajax call but the second one returns data I want.
My C# method (UserSelect) JsonResults shows the data when I put break point
My C# code :
public IActionResult OnPostAreaSelect(string Id)
{
//Generating list for Areas
Guid ModelId = new Guid(Id);
List<ModelArea> modelAreas = _context.ModelArea.Distinct()
.Where(w => w.ModelId == ModelId).OrderBy(o => o.AreaColumn.Name).Include(i => i.AreaColumn).ToList();
return new JsonResult(modelAreas);
}
public IActionResult OnPostUserSelect(string Id)
{
//Generating list for Users
Guid ModelId = new Guid(Id);
List<UserModel> userModels = _context.UserModel
.Where(w => w.ModelId == ModelId).OrderBy(o => o.User.FullName)
.Include(i => i.User)
.ToList();
return new JsonResult(userModels);
}
My JavaScript :
<script type="text/javascript">
$(document).ready(function () {
$("#RepfocusModelDropdown").change(function () {
var Id = $(this).val();
if (Id != null) {
$.ajax({
async: true,
type: "POST",
url: "./Create?handler=UserSelect",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
Id: Id
},
crossDomain: true,
dataType: "json",
success: function (response) {
alert(JSON.stringify(response));
},
error: function (response) {
alert(JSON.stringify(response));
}
});
$.ajax({
type: "POST",
url: "./Create?handler=AreaSelect",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
Id: Id
},
dataType: "json",
success: function (response) {
alert(JSON.stringify(response));
},
error: function (response) {
alert(JSON.stringify(response));
}
});
}
})
})
The second ajax call on my script works fine only the first one returns the error
How can I solve the error
When you work with EntityFramework (or other ORM) there may be problems with serialization because an entity could have some circular references. To avoid this problem a solution is to set serialization settings:
services.AddMvc().AddJsonOptions(opt => {
opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
or:
Newtonsoft.Json.JsonConvert.DefaultSettings = () => new Newtonsoft.Json.JsonSerializerSettings {
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
};
As title, I tried load data from ajax to zabuto calendar, but seem it's not working, ref of zabuto calendar http://zabuto.com/dev/calendar/examples/show_data.html. And i want to use this function load data when click nav prev month or next month. (use two action action and action_nav). This is snipped code
<script>
$(document).ready(function () {
function load_data() {
var list = '';
$.ajax({
type: "POST",
url: "../BUS/WebService.asmx/LOAD_DATA",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function (data) {
list = $.parseJSON(data.d);
console.log(list);
}
});
return list;
}
function myNavFunction(id) {
//code in here
}
function myDateFunction(id) {
//code in here
}
$("#my_calendar").zabuto_calendar({
data: load_data(),
action: function () {
return myDateFunction(this.id);
},
action_nav: function () {
return myNavFunction(this.id);
}
});
});
</script>
When i test this, data not show, the data from ajax as
{ "date": "2016-06-01", "title": 2, "badge": true },{ "date": "2016-06-04", "title": 1, "badge": true },{ "date": "2016-06-10", "title": 1, "badge": true }
Thank you so much.
Try the following: you need to place the calendar function in the success function of the ajax call because ajax is asynchronous
$(document).ready(function () {
function load_data() {
$.ajax({
type: "POST",
url: "../BUS/WebService.asmx/LOAD_DATA",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function (data) {
var list = $.parseJSON(data.d);
$("#my_calendar").zabuto_calendar({
data: list;
});
},
error: function (data) {
console.log(data.d);
}
});
}
load_data();
});
I solved the issue by the code as below. It works well in window's browser but not in a mobile browser.
function initZabuto(id, events, month){
$('#zabuto_parent').empty().append("<div id='"+id+"'></div>");
$("#"+id).zabuto_calendar({
year:moment(month).format("YYYY"),
month:moment(month).format("MM"),
language:"cn",
data: events,
action: function () {
zabutoDayClick(this.id);
},
action_nav: function () {
zabutoMonthChange(this.id);
}
});
}
This is the code I used to refresh Zabuto calendar after a modal. The problem with other options is that upon refresh, Zabuto would create a new batch of modals appended to the current body. This solutions clears all those "old" modals and opens room for the new. Key area is the success section of the modal update ajax.
$(document).ready(function () {
$("#date-popover").popover({html: true, trigger: "manual"});
$("#date-popover").hide();
$("#date-popover").click(function (e) {
$(this).hide();
});
load_calendar();
});
function load_calendar() {
$("#my-calendar").zabuto_calendar({
show_next: 1,
action: function () {
return myDateFunction(this.id, false);
},
ajax: {
url: "calendar-info.php",
modal: true
},
});
}
function myDateFunction(id, fromModal) {
$("#date-popover").hide();
if (fromModal) {
$("#" + id + "_modal").modal("hide");
var date = $("#" + id).data("date");
var optradio = $("#" + id + "_modal").find("input[name='optradio']:checked").val();
$.ajax("calendar-update.php?status="+optradio+"&date="+date, {
success: function(data) {
$(".modal").remove();
$('body').removeClass('modal-open');
$('.modal-backdrop').remove();
$("#my-calendar").empty();
load_calendar();
},
error: function() {
alert("Problem!");
}
});
}
var hasEvent = $("#" + id).data("hasEvent");
if (hasEvent && !fromModal) {
return false;
}
return true;
}
Not only should this be a straightforward operation but I'm following the documentation as well. I have an ajax call that returns a json data set. I've cleared the table successfully but when the success method is called nothing happens. The console statement shows that data is being returned... however the table remains empty. Any idea why?
JS
$('#SortByCoverage').click(function () {
var table = $('#theTable').DataTable();
table.fnClearTable();
$.ajax({
url: '/Home/Question2',
type: 'GET',
dataType: 'json',
success: function (data) {
console.log(data);
$("#thetable").dataTable({
"aaData": data,
"aoColumns": [
{title:"AdId"},
{title:"BrandId"},
{title:"BrandName"},
{title:"NumPages"},
{title:"Position"}
]
});
}
});
Server Side Code
public JsonResult Question2()
{
var ads = _client.GetAdDataByDateRange(new DateTime(2011, 1, 1), new DateTime(2011, 4, 1));
var json = ads.Where(x => x.Position.Equals("Cover") && x.NumPages >= (decimal)0.5).Select(x => new{
AdId = x.AdId,
BrandId = x.Brand.BrandId,
BrandName = x.Brand.BrandName,
NumPages = x.NumPages,
Position = x.Position
});
return Json(json, JsonRequestBehavior.AllowGet);
}
Sample Data (client side)
EDIT
As pointed out in the comments I misspelled the element name dataTable in the success callback. However, now I'm getting the following error:
Cannot reinitialise DataTable. To retrieve the DataTables object for this table, pass no arguments or see the docs for bRetrieve and bDestroy
Do I really have to destroy the table, once it's clear, to reload the data?
I added the bRetrieve and bDestroy. This got rid of the error but still no new data loaded into the table.
$.ajax({
url: '#Url.Action("Question2", "Home")',
type: 'GET',
dataType: 'json',
success: function (data) {
console.log(data);
$("#theTable").dataTable({
//"bRetrieve": true,
"bDestroy": true,
"aaData": data,
"aoColumns": [
{title:"AdId"},
{title:"BrandId"},
{title:"BrandName"},
{title:"NumPages"},
{title:"Position"}
]
});
}
});
I would make a little different, see how:
var theTable = $("#thetable").dataTable({
"aaData": [],
"aoColumns": [
{data:"AdId"},
{data:"BrandId"},
{data:"BrandName"},
{data:"NumPages"},
{data:"Position"}
]
}).DataTable();
$('#SortByCoverage').click(function () {
$.ajax({
url: '/Home/Question2',
type: 'GET',
dataType: 'json',
success: function (data) {
theTable.clear().draw();
table.rows.add(data)
.draw();
}
});
I want to retrieve some data from Weather.asmx and wrote below code to get some data. There was no error from Javascript as I have seen but when the program runs it always go to groupPropertiesErrorHandler function. Any idea?
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#butCallAjax').click(function() {
jQuery.support.cors = true;
$.ajax({
url: "http://wsf.cdyne.com/WeatherWS/Weather.asmx/GetCityWeatherByZIP?ZIP=10007",
method: "GET",
headers: {
"Accept": "application/json; odata=verbose"
},
success: groupPropertiesSuccessHandler,
error: groupPropertiesErrorHandler
});
});
function groupPropertiesSuccessHandler(data) {
var jsonObject = JSON.parse(data.body);
var properties = 'Group Properties:\n';
alert(properties);
}
// Error Handler
function groupPropertiesErrorHandler(data, errorCode, errorMessage) {
alert("Could not get the group properties: " + errorMessage);
}
});
</script>