i try to show result in alert box
i try this
[WebMethod]
public static string Jqufunc(int yearP)
{
string res = "[";
ProjectdbEntities a = new ProjectdbEntities();
var b = a.Catg_type;
foreach (var c in b)
{
res += "'" + c.Catg_type1 + "',";
}
res = res.Substring(0, res.Length - 1);
res += "]";
var allprogs = a.Program_type;
string res2 = "[";
foreach (var pr in allprogs)
{
res2 += "{name: '" + pr.Prog_name + "',";
//var y = a.Year_info;
var allcats = a.Catg_type;
res2 += "data:[";
var query = (a.Std_info.Join(a.Catg_type, stdtable => stdtable.Catg_id,
catg => catg.Catg_id, (stdtable, catg) => new {stdtable, catg})
.Join(a.Program_type, t => t.stdtable.Prog_id, prog => prog.Prog_id, (t, prog) => new {t, prog})
.Join(a.Year_info, t => t.t.stdtable.year_id, yea => yea.year_id, (t, yea) => new {t, yea})
.Where(t=>t.t.t.stdtable.year_id==yearP)
.GroupBy(
t =>
new { t.t.t.catg.Catg_type1, t.t.prog.Prog_name, t.yea.year, t.t.t.stdtable.Catg_id },
t => t.t.t.stdtable)
.Select(g => new
{
g.Key.Catg_type1,
g.Key.Prog_name,
g.Key.year,
g.Key.Catg_id,
total_students = g.Select(p=>p.Catg_id).Distinct().Count()
})).ToList();
res2 = res2.Substring(0, res2.Length - 1);
}
res2 += "]";
res2 += "},";
return res + "*" + res2;
}
i try to show in alert box
var webmethod = 'WebForm1.aspx/Jqufunc';
$.ajax({
type: 'POST',
url: webmethod,
data: JSON.stringify({ yearP: $('#DropDownList1').val() }),
contentType: 'application/json;charset=utf-8',
dataType: 'json',
success: function (response) {
alert(JSON.stringify(response.d));;
i have a dropdown in page i filled this dropdown from db
when i select year suppose i select 2014 year from drop down then according to the year 2014 following data is save in db
Catg_type Prog_name year total_students
ComputerScience Bachelors 2014 1
Management Bachelors 2014 1
Finance Masters 2014 3
Management Masters 2014 2
now i want this in alert box
['Management','ComputerScience','Finance']
[{name:'Bachelors','2014',data:1,1,0
name :'Masters,'2014, data:2,0,3}]
but currently data is displayed in alert box like this
['Management','ComputerScience','Finance']
[{name:Bachelors,data:}{name:Masters,data:}]
alert("Name: " + response.d.Prog_name + ", Type: "+ response.d.Catg_type);
Related
I am trying to understand how the batch rest calls work.
I could not find any simple example on the internet. I have found the examples from https://github.com/andrewconnell/sp-o365-rest but can't run these examples or I have no idea how yet. I am guessing you have to deploy the app to a sharepoint site.
Given that, I am just looking for the simplest example of a add list item and update list item in bulk/batch. Also if anyone knows how I can make the app from that git to run will be really appreciated.
Thanks.
The github project is a add-in project so you need deploy the add-in project, then you can use it.
You could check below script from here.
My test result in this thread
(function () {
jQuery(document).ready(function () {
jQuery("#btnFetchEmployees").click(function () {
addEmployees();
});
});
})();
function addEmployees() {
var employeesAsJson = undefined;
employeesAsJson = [
{
__metadata: {
type: 'SP.Data.EmployeeInfoListItem'
},
Title: 'Geetanjali',
LastName: 'Arora',
Technology: 'SharePoint'
},
{
__metadata: {
type: 'SP.Data.EmployeeInfoListItem'
},
Title: 'Geetika',
LastName: 'Arora',
Technology: 'Graphics'
},
{
__metadata: {
type: 'SP.Data.EmployeeInfoListItem'
},
Title: 'Ashish',
LastName: 'Brajesh',
Technology: 'Oracle'
}
];
addEmployeeInfoBatchRequest(employeesAsJson);
}
function generateUUID() {
var d = new Date().getTime();
var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c == 'x' ? r : (r & 0x7 | 0x8)).toString(16);
});
return uuid;
};
function addEmployeeInfoBatchRequest(employeesAsJson) {
// generate a batch boundary
var batchGuid = generateUUID();
// creating the body
var batchContents = new Array();
var changeSetId = generateUUID();
// get current host
var temp = document.createElement('a');
temp.href = _spPageContextInfo.webAbsoluteUrl;
var host = temp.hostname;
// iterate through each employee
for (var employeeIndex = 0; employeeIndex < employeesAsJson.length; employeeIndex++) {
var employee = employeesAsJson[employeeIndex];
// create the request endpoint
var endpoint = _spPageContextInfo.webAbsoluteUrl
+ '/_api/web/lists/getbytitle(\'EmployeeInfo\')'
+ '/items';
// create the changeset
batchContents.push('--changeset_' + changeSetId);
batchContents.push('Content-Type: application/http');
batchContents.push('Content-Transfer-Encoding: binary');
batchContents.push('');
batchContents.push('POST ' + endpoint + ' HTTP/1.1');
batchContents.push('Content-Type: application/json;odata=verbose');
batchContents.push('');
batchContents.push(JSON.stringify(employee));
batchContents.push('');
}
// END changeset to create data
batchContents.push('--changeset_' + changeSetId + '--');
// batch body
var batchBody = batchContents.join('\r\n');
batchContents = new Array();
// create batch for creating items
batchContents.push('--batch_' + batchGuid);
batchContents.push('Content-Type: multipart/mixed; boundary="changeset_' + changeSetId + '"');
batchContents.push('Content-Length: ' + batchBody.length);
batchContents.push('Content-Transfer-Encoding: binary');
batchContents.push('');
batchContents.push(batchBody);
batchContents.push('');
// create request in batch to get all items after all are created
endpoint = _spPageContextInfo.webAbsoluteUrl
+ '/_api/web/lists/getbytitle(\'EmployeeInfo\')'
+ '/items?$orderby=Title';
batchContents.push('--batch_' + batchGuid);
batchContents.push('Content-Type: application/http');
batchContents.push('Content-Transfer-Encoding: binary');
batchContents.push('');
batchContents.push('GET ' + endpoint + ' HTTP/1.1');
batchContents.push('Accept: application/json;odata=verbose');
batchContents.push('');
batchContents.push('--batch_' + batchGuid + '--');
batchBody = batchContents.join('\r\n');
// create the request endpoint
var endpoint = _spPageContextInfo.webAbsoluteUrl + '/_api/$batch';
var batchRequestHeader = {
'X-RequestDigest': jQuery("#__REQUESTDIGEST").val(),
'Content-Type': 'multipart/mixed; boundary="batch_' + batchGuid + '"'
};
// create request
jQuery.ajax({
url: endpoint,
type: 'POST',
headers: batchRequestHeader,
data: batchBody,
success: function (response) {
var responseInLines = response.split('\n');
$("#tHead").append("<tr><th>First Name</th><th>Last Name</th><th>Technology</th></tr>");
for (var currentLine = 0; currentLine < responseInLines.length; currentLine++) {
try {
var tryParseJson = JSON.parse(responseInLines[currentLine]);
$.each(tryParseJson.d.results, function (index, item) {
$("#tBody").append("<tr><td>" + item.Title + "</td><td>" + item.LastName + "</td><td>" + item.Technology + "</td></tr>");
});
} catch (e) {
}
}
},
fail: function (error) {
}
});
}
I get this error in the Google Sheets application trying to text reminders every day I used this format 4175555555, (417) 5555555, and (417) 5555555 you are not sure what the problems are.
The error is:
Request failed for api.fluentcloud.com/v1/sms/send/GeneralRentalCenter returned code 417. Truncated server response: {"error":{"code":417,"message":"Expectation Failed: To number: is not formatted properly"}} (use muteHttpExceptions option to examine full response) (line 25, file "REMINDER")
//This sends out sms to phone number in row
function sendSms(to, name, time) {
var messages_url = 'https://api.fluentcloud.com/v1/sms/send/GeneralRentalCenter';
var body = {
'direction': '',
'to': to,
'from': '(417) 886-7368',
'timestamp': '',
'message': 'Hello' + ' ' + name + ', This is a reminder of your reservation at General Rental at ' + time + ' tomorrow. If you have any questions call 417-886-7368 ',
'messageId': '',
'particContactName': ''
};
var options = {
"method": "post",
"payload": body
};
options.headers = {
"Authorization": "4LsEvTFn-jD4i-XOmg-iGEXji7x2ZTb"
};
//sends out SMS to number for the row
UrlFetchApp.fetch(messages_url, options);
};
function sendAll() {
var date = new Date();
var today = ((date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear());
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
var activeSheet;
for (i in sheets) {
if ((((new Date(today)) - (new Date(sheets[i].getName()))) / 86400000) === -1) {
activeSheet = sheets[i].getName();
SpreadsheetApp.setActiveSheet(sheets[i]);
}
}
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2;
var numRows = sheet.getLastRow() - 1;
var dataRange = sheet.getRange(startRow, 8, numRows, 4);
var data = dataRange.getValues();
for (i in data) {
var row = data[i];
if (!row[1]) {
continue;
};
var num = row[1].toString().split(".")[0];
if (row[3] === 'y') {
`enter code here`
try {
response_data = sendSms(num, row[0], row[2]);
} catch (err) {
Logger.log(err);
}
}
}
};
function myFunction() {
sendAll();
}
When script works it should pull there name,number and items and send out a reminder to them
I have an array and inside each array is a json object with each day of the week, so my array would look something like this:
var array = [
{
"wednesday":{
"notes":"some notes for Wednesday"
},
},
{
"thursday":{
"notes":"some notes for Thursday"
}
}
];
i can get away with updating my object directly by calling the following:
array[0].wednesday.notes = "updating Wednesday notes";
However, I need to update it dynamically....
I have a function that looks something like this, I need to dynamically call the day of the week on my json object and not be locked into just wednesday, i need to be able to call wednesday, thursday, friday etc on my object, how can i do this?
function updateObject(index, empNum) {
console.log(index+", "+empNum)
array[index].employee = $("#employee_" + empNum).val();
array[index].wednesday.notes = $("#employee_" + empNum + "_wed_notes").val();
array[index].wednesday.start = $("#employee_" + empNum + "_wed_shift_start").val();
array[index].wednesday.lunch = $("#employee_" + empNum + "_wed_lunch").val();
array[index].wednesday.end = $("#employee_" + empNum + "_wed_shift_end").val();
array[index].wednesday.short_day = $("#employee_" + empNum + "_wed_short_day").is(':checked');
array[index].wednesday.lack_of_work = $("#employee_" + empNum + "_wed_lack_of_work").is(':checked');
array[index].wednesday.full_day = $("#employee_" + empNum + "_wed_full_day").is(':checked');
var row_count = $("input[id*='employee_" + empNum + "_wed_job_']").length;
for (var i = 0; i < row_count; i++) {
var data = {};
data.job = $("input[id*='employee_" + empNum + "_wed_job_']").eq(i).val();
data.hrs = $("input[id*='employee_" + empNum + "_wed_hrs_']").eq(i).val();
data.cost_code = $("input[id*='employee_" + empNum + "_wed_cost_code_']").eq(i).val();
data.st = $("input[id*='employee_" + empNum + "_wed_st_']").eq(i).is(':checked');
data.ot = $("input[id*='employee_" + empNum + "_wed_ot_']").eq(i).is(':checked');
data.dt = $("input[id*='employee_" + empNum + "_wed_dt_']").eq(i).is(':checked');
array[index].wednesday.data[i] = data;
}
}
i tried something like doing
array[index].[thursday].notes = "x";
but unfortunately that doesnt work, i need to be able to call the day of the week i need when i call the function
so i need it to be something like updateObject(2,1,"thursday");
You just need to use the bracket notation to access the correct element in your array/objects.
This function would let you enter the week number (array index) as well as the day you want to update.
var array = [
{
"wednesday":{
"notes":"some notes for Wednesday"
},
},
{
"thursday":{
"notes":"some notes for Thursday"
}
}
];
function updateArray(index, day, newNotes) {
array[index][day].notes = newNotes;
}
console.log('before', array);
updateArray(1, 'thursday', 'updated notes');
console.log('after', array);
You can access all your data as so:
const updateObject = (index, empNum) => {
const i = array[index], k = Object.keys(i)[0]
if (!k) {return console.error("Invalid Data at index",index)}
i[k].notes = `Whatever you want with ${empNum}`
}
The function isolates the key given at a certain location and accesses it.
Example: updateObject(0, "15 employees")
If you would rather have ^^ do it by day then your function would look like:
const updateObject = (day, empNum) => {
const i = array.map(r => {
const k = Object.keys(r)[0];if (!k) {return false}
return r[k]
}).filter(r => r)[0]
if (!i) {return console.error("Invalid Day [%s] provided",day)}
i.notes = `Whatever you want with ${empNum}`
}
Not you can use it like: updateObject('tuesday', "15 employees")
I'm filling "ReportToadd" dropdownlist form "ddlLanguage" dropdownlist when select index change through JavaScript and ajax in asp.net mvc.This work fine but take much time to fill child dropdownlis"ReportToadd".it take 4 to 5 second to fill second dropdownlist.How can make it fast.please help and thanks in advance
JavaScript code:
$(function () {
$('select#ddlLanguage').change(function () {
var languageId = $(this).val();
var projectType ='#(TempData["projectType"])';
$.ajax({
url: "/SEI/Report/FillReport",
type: 'POST',
data: JSON.stringify({ languageId: languageId, projectType: projectType }),
dataType: 'json',
contentType: 'application/json',
success: function (data) {
$("#ReportToAdd").html("");
$.each(data, function (key, result) {
$('select#ReportToAdd').append(
'<option value="' + result.Value + '">'
+ result.Text +
'</option>');
});
}
});
});
});
and dropdownlist are:
string projectType = "SEI_ADULT";
#Html.DropDownList("ddlLanguage", SixSeconds.Utils.SelectList<SixSeconds.Models.Language>("Name", ""), new { #id = "ddlLanguage", style = "width:300px;" }) <br />
TempData["projectType"] = projectType;
#Html.DropDownList("ReportToAdd", Enumerable.Empty<SelectListItem>(), new { #id = "ReportToAdd", style = "width:300px;" })
and Json method is like
public JsonResult FillReport(int languageId,string projectType,string selectedValue, bool showCredits = true)
{
DataAccessObject<ReportType> dao = new DataAccessObject<ReportType>();
DataAccessObject<Language> ldao = new DataAccessObject<Language>();
//IEnumerable<ReportType> list = criteria != null ? dao.Filter(criteria) : dao.All().ToList();
IEnumerable<ReportType> list = dao.All().ToList();
IEnumerable<Language> Llist = ldao.All().ToList();
list = list.Where(a => a.ProjectType.ToString() == projectType).ToList();
list = list.OrderBy(r => r.CustomOrder);
List<SelectListItem> result = new List<SelectListItem>();
result.Add(new SelectListItem() { Value = "", Text = "" });
foreach (ReportType t in list)
{
foreach (Language l in t.Languages.Where(a=>a.Id==languageId).ToList())
{
string displayText = t.Name + " (" + l.Name + ")" + (showCredits ? " - " + (t.Code == "BTP" ? 10 : t.Credits) + " " + App_GlobalResources.FieldLabels.Credits : "");
string value = t.Id + "-" + l.Id + "-" + (t.Code == "BTP" ? 10 : t.Credits) + "-" + t.Code + "-" + l.Code.Replace("-", "_");
result.Add(new SelectListItem() { Selected = (selectedValue == value), Value = value, Text = displayText });
}
}
return Json(result);
}
One way of updating your db query is to not use All and pass down the Where.
Also, Llist is never used so you are getting all the Languages from the db for nothing.
try:-
//IEnumerable<Language> Llist = ldao.All().ToList();
IEnumerable<ReportType> list = dao.Where(a => a.ProjectType.ToString() == projectType)
.OrderBy(r => r.CustomOrder).ToList();
instead of :-
IEnumerable<ReportType> list = dao.All().ToList();
IEnumerable<Language> Llist = ldao.All().ToList();
list = list.Where(a => a.ProjectType.ToString() == projectType).ToList();
list = list.OrderBy(r => r.CustomOrder);
This will pass the where and order by to the db instead of doing it in code.
I am getting a 'date' element from a RSS feed. I am having trouble with sorting and displaying the information. Can someone have a look? Thanks!
$('#feedContainer').empty();
$.ajax({
type: 'GET',
url: categoryURL,
dataType: 'xml',
success: function (xml) {
var data = [];
$(xml).find("item").each(function () {
var dateText = $(this).find("Date").text().substr(0,5);
var title = $(this).find("title").text();
var region = date.substr(6);
if (region.length < 3) { region = "ALL"; }
var description = $(this).find("description").text();
var descriptdisplay = description.substr(0, description.indexOf(",")+6); //Parsed DATE from description
if (descriptdisplay.length > 35) { descriptdisplay = "See event for details"; }
//var locationdisplay = description.substr(description.indexOf(",")+6,4); //Parsed the location from description
var category = $(this).find("category").text();
var linkUrl = $(this).find("link").text();
var item={ title: $(this).find("title").text(), dateText: $(this).find("Date").text().substr(0,5), date : new Date( dateText) }
data.push(item);
// var displaytitle = "<a href='" + linkUrl + "' target='_blank'>" + title + "</a>" ;
// $('#feedContainer').append('<h3>'+displaytitle+'</h3><p>'+"Event Date: "+descriptdisplay+'</p><p>'+"Location: "+region+'</p');
data.sort(function(a,b){ return a.date > b.date;});
$.each(data, function(index, item) { $('#feedContainer').append('<h3>'+item.title+'</h3><p>'+"Event Date: "+item.dateText+'</p><p>'+"Location: "+item.date+'</p'); });
});
}
});
You're sorting date objects, try sorting the epoch timestamp instead:
data.sort(function(a,b){
return a.date.getTime() > b.date.getTime();
});