How populate database records into my table ajax - javascript

So i go this information and have a empty table name categorytable so i have to have records stored in categoryList for the below code to work. so what do i write in categoryList which is to fetch the record from my category manager and display the data from sql
</table>
<script>
$(document).ready(function () {
var categoryList = [];
var $courseTableElement = $('#categoryTable');
var $rowElement;
var $cellElement;
var index = 0;
for (index = 0; index < categoryList.length; index++) {
$rowElement = $('<tr></tr>');
$cellElement = $('<td></td>', { text: categoryList[index].CategoryName });
$rowElement.append($cellElement);
$cellElement = $('<td></td>', { text: categoryList[index].CategoryId });
$rowElement.append($cellElement);
$courseTableElement.append($rowElement);
}
});
</script>
public List<Category> getAllCategory(string inUserId)
{
DataSet ds = new DataSet();
List<Category> categoryList = new List<Category>();
string sqlText = "";
using (SqlConnection cn = new SqlConnection())
{
cn.ConnectionString =
ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = cn; //setup the
cn.Open();
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
sqlText = "SELECT CategoryId,CategoryName,CreatedBy,CreatedAt,UpdatedBy,UpdatedAt " +
" FROM Category ";
cmd.CommandText = sqlText;
cmd.Parameters.Add("#inCurrentUserId", SqlDbType.VarChar, 200).Value = inUserId;
da.Fill(ds, "CategoryData");
cmd.CommandText = sqlText;
}//using SqlDataAdapter da
cn.Close();
}//using SQLCommand cmd
}//using SQLConnection cn
foreach (DataRow dr in ds.Tables["CategoryData"].Rows)
{
Category category = new Category();
category.CategoryId = Int32.Parse(dr["CategoryId"].ToString());
category.CategoryName = dr["CategoryName"].ToString();
category.CreatedBy = dr["CreatedBy"].ToString();
category.CreatedAt = DateTime.Parse(dr["CreatedAt"].ToString());
category.UpdatedBy = dr["UpdatedBy"].ToString();
category.UpdatedAt = DateTime.Parse(dr["UpdatedAt"].ToString());
categoryList.Add(category);
}
return categoryList;
}

You just need to make an ajax request to your server and grab that data. I'm making a couple of assumptions.
That getAllCategory is accessible to the frontend via webapi or something of the sort.
That getAllCategory will return proper json.
function getDataFromServer(url, callback){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("get",url);
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readystate === 4 && xmlhttp.status === 200){
//data was retrieved successfully.
callback(JSON.parse(xmlhttp.response));
}
}
xmlhttp.send();
}
$(document).ready(function () {
//the path to action must include the id in querystring
var url = 'path_to_action'
getDataFromServer(url, function(data){
var courseTableElement = $('#categoryTable');
for(var i = 0; i < data.length; i++){
var row = $('<tr></tr>');
var cell1 = $('<td></td>, { text: data[i].CategoryName } );
var cell2 = $('<td></td>, { text: data[i].CategoryId } );
row.append(cell1);
row.append(cell2);
courseTableElement.append(row);
}
}
});

Related

How i can get bigquery table data in google script?

I want to bigquery table data using app script ,I am using this code but i am getting job id, i dont job id i want table data please help me this.
function runQuery() {
DriveApp.getRootFolder();
var projectId = 'imran-338706';
var request = {
query: 'SELECT network_affiliate_name FROM `imran-338706.imranabc.bhk` LIMIT 10',
useLegacySql: false
}
var queryResults = BigQuery.Jobs.query(request, projectId);
var jobId = queryResults.jobReference.jobId;
console.log(queryResults)
}
I verified using the following code for queries returning small amount of data :
function runQuery() {
DriveApp.getRootFolder();
var projectId = ProjectID;
var request = {
query: 'SELECT * from `bigquery-public-data.austin_311.311_service_requests` limit 2',
useLegacySql: false
}
var queryResults = BigQuery.Jobs.query(request, projectId);
var jobId = queryResults.jobReference.jobId;
var rows = queryResults.rows;
var header = "";
for (var i = 0; i < queryResults.schema.fields.length; i++){
header+= " " + queryResults.schema.fields[i].name;
}
console.log(header)
var data = new Array(rows.length);
var string = ""
for (var i = 0; i < rows.length; i++) {
var cols = rows[i].f;
data[i] = new Array(cols.length);
for (var j = 0; j < cols.length; j++) {
data[i][j]= cols[j].v;
string+= " "+ data[i][j]
}
console.log(string);
}
}
It gave the schema and row contents:

Call function on ButtonClick

I am trying to call function from .aspx to my JavaScript.
I try something like this
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Filter" Width="224px" OnClientClick="return BindToData();" />
And here is my JavaScript
<script type="text/javascript">
function GetSelectedReportName() {
return
document.getElementById('<%=ddlReportName.ClientID%>').options[document.getElementById('<%=ddlReportName.ClientID%>').selectedIndex].value;
}
function ShowReport() {
var reportName = GetSelectedReportName();
ASPxWebDocumentViewer1.OpenReport(reportName);
}
</script>
And here is my function which I need to call in ButtonClick
public void BindToData()
{
try
{
string connString = #"Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=DesignSaoOsig1;Integrated Security=True";
SqlConnection conn = new SqlConnection(connString);
string strproc = "TestReport";
using (SqlDataAdapter sda = new SqlDataAdapter(strproc, connString))
{
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand();
sda.SelectCommand.CommandType = CommandType.StoredProcedure;
sda.SelectCommand.Parameters.Add("#Status", SqlDbType.Bit).Value = ddlStatus.SelectedValue == "1" ? true : false;
sda.SelectCommand.Parameters.Add("#OrgJed", SqlDbType.Int).Value = ddlOrgUnit.SelectedValue;
sda.Fill(ds);
XtraReport report = new XtraReport
{
DataSource = ds,
DataMember = ds.Tables[0].TableName
};
string[] arrvalues = new string[ds.Tables[0].Rows.Count];
for (int loopcounter = 0; loopcounter < ds.Tables[0].Rows.Count; loopcounter++)
{
//assign dataset values to array
arrvalues[loopcounter] = ds.Tables[0].Rows[loopcounter]["PrezimeIme"].ToString();
arrvalues[loopcounter] = ds.Tables[0].Rows[loopcounter]["NetworkLogin"].ToString();
arrvalues[loopcounter] = ds.Tables[0].Rows[loopcounter]["Status"].ToString();
arrvalues[loopcounter] = ds.Tables[0].Rows[loopcounter]["OrgUnitID"].ToString();
arrvalues[loopcounter] = ds.Tables[0].Rows[loopcounter]["DT_Creat"].ToString();
arrvalues[loopcounter] = ds.Tables[0].Rows[loopcounter]["DT_Modif"].ToString();
}
ASPxWebDocumentViewer1.OpenReport(report);
ASPxWebDocumentViewer1.DataBind();
//gridview1.DataSource = ds;
//gridview1.DataBind();
}
}
catch (Exception)
{
throw;
}
}
I need to load filtered report in button click, since in JS I only load report, when I click in button I get only unfiltered data, when I debug application I see that I get filtered data, but problem can be only in JS. Any help will be appreciate
Here is reference page which I check:
Link 1
Link 2
Link 3

HTML form send data to google sheet with time stamp

i have success send data to my google sheet from HTML
function submit_form() {
var complete = true;
var error_color = '#FFD9D9';
var fields = ['name','phonenum','monthlysalary','totalamount','types'];
var row = '';
var i;
for(i=0; i < fields.length; ++i) {
var field = fields[i];
$('#'+field).css('backgroundColor', 'inherit');
var value = $('#'+field).val();
if(!value) {
if(field != 'message') {
$('#'+field).css('backgroundColor', error_color);
var complete = false;
}
} else {
row += '"'+value+'",';
}
}
if(complete) {
row = row.slice(0, -1);
var gs_sid = 'xxx';
var gs_clid = 'xxx';
var gs_clis = 'xxx';
var gs_rtok = 'xxx';
var gs_atok = false;
var gs_url = 'https://sheets.googleapis.com/v4/spreadsheets/'+gs_sid+'/values/Google!A1:append?includeValuesInResponse=false&insertDataOption=INSERT_ROWS&responseDateTimeRenderOption=SERIAL_NUMBER&responseValueRenderOption=FORMATTED_VALUE&valueInputOption=USER_ENTERED';
var gs_body = '{"majorDimension":"ROWS", "values":[['+row+']]}';
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://www.googleapis.com/oauth2/v4/token?client_id='+gs_clid+'&client_secret='+gs_clis+'&refresh_token='+gs_rtok+'&grant_type=refresh_token');
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
var response = JSON.parse(xhr.responseText);
var gs_atok = response.access_token;
if(gs_atok) {
var xxhr = new XMLHttpRequest();
xxhr.open('POST', gs_url);
xxhr.setRequestHeader('Content-type', 'application/json');
xxhr.setRequestHeader('Authorization', 'OAuth ' + gs_atok );
xxhr.send(gs_body);
}
};
xhr.send();
}
}
Now i having a problem, i would like to make the google sheets will auto adding timestamp when i send the data into google form. Its anyway to do it?
Thank you

Trying to sort repeater rows with this jQuery

I am trying to sort repeater rows with this jquery . But I am not able to save sort items. Please help me . how can save sorting in database as well as in .aspx page?Thank you in advance
<script language="javascript" type="text/javascript">
$("#defaultList").sortable();
$(document).ready(function () {
$("#defaultList").sortable(
{
update: function (ev, ui) {
var result = $('#defaultList').sortable('toArray');
updateSequenceNumber(result);
}
}
);
});
function updateSequenceNumber(items) {
var originalIdAndSequenceNumber = '';
var index = 0;
for (i = 0; i <= items.length - 1; i++) {
if (items[i].length == 0)
continue;
var item = $('#' + items[i])[0];
originalIdAndSequenceNumber += item.attributes["originalId"].nodeValue + ":" + index.toString();
originalIdAndSequenceNumber += "|";
index = index + 1;
}
persistPositionUsingAjax(originalIdAndSequenceNumber);
}
function persistPositionUsingAjax(originalIdAndSequenceNumber) {
$.ajax(
{
type: "POST",
dataType: "text",
url: "AjaxService.asmx/UpdateSequenceNumber",
data: "s=" + originalIdAndSequenceNumber,
success: function (response) {
}
}
);
}
my ajax method:
[WebMethod]
public string UpdateSequenceNumber(string s)
{
s = s.TrimEnd('|');
string updateQuery = #"update dnn_Table_1 set SortId = {0}
where ImageId = {1}";
StringBuilder sb = new StringBuilder();
string[] originalIdAndSeqNumberArray = s.Split('|');
foreach (var originalIdAndSeqNumberCombined in originalIdAndSeqNumberArray)
{
var tempArray = originalIdAndSeqNumberCombined.Split(':');
int originalId = Convert.ToInt32(tempArray[0]);
int sequenceNumber = Convert.ToInt32(tempArray[1]);
sb.Append(String.Format(updateQuery, sequenceNumber, originalId));
sb.Append(System.Environment.NewLine);
}
UpdateInDatabase(sb.ToString());
return "Hello World";
}
private void UpdateInDatabase(string updateQuery)
{
SqlDataProvider sqd = new SqlDataProvider();
string ConnectionString = sqd.ConnectionString;
SqlConnection conn = new SqlConnection(ConnectionString);
SqlCommand command = new SqlCommand(updateQuery, conn);
command.CommandText = updateQuery;
conn.Open();
command.ExecuteNonQuery();
conn.Close();
}
What status code does the ajax call return?
To me it looks like a 500. You are building an update statement that after a few iterations will look something like this
update dnn_Table_1 set SortId = 3 where ImageId = 2update dnn_Table_1 set SortId = 2 where ImageId = 4update dnn_Table_1 set SortId = 7 where ImageId = 6
That just won't work. Try eihter constructing the SQL update differently or move UpdateInDatabase into the foreach loop.
There might be other issues which I didn't spot, but this might be a starting point.
Hope that helps

Read-Only Button for List Item in Sharepoint

I've got the following Sharepoint problem: I've created a Ribbon Button, which says "Read Only". When I am on a list, and check some items, I want to set those items to read only.
The ribbon button works great and when I am doing an alert or something, I get an answer. So this cannot be the problem. I did the following:
var listitem;
var roleAssgn;
var Assgn;
var selectedItems;
function readonly() {
selectedItems = SP.ListOperation.Selection.getSelectedItems();
var currentListGuid = SP.ListOperation.Selection.getSelectedList();
var context = SP.ClientContext.get_current();
var currentWeb = context.get_web();
var currentList = currentWeb.get_lists().getById(currentListGuid);
for (k in selectedItems) {
listitem = currentList.getItemById(selectedItems[k].id);
context.load(listitem, 'RoleAssignments');
context.executeQueryAsync(Function.createDelegate(this, this.readonlyPerItem), Function.createDelegate(this, this.failed));
}
}
function readonlyPerItem(sender, args) {
var k;
var Assgn;
var r;
context = SP.ClientContext.get_current();
roleAssgn = listitem.get_roleAssignments();
for(r in roleAssgn){
Assgn = roleAssgn[r];
alert("1");
context.load(Assgn, 'RoleDefinitionBindings');
alert("2");
context.executeQueryAsync(Function.createDelegate(this, this.readonlyPerRoleA), Function.createDelegate(this, this.failed));
}
}
function readonlyPerRoleA(sender, args) {
var bindings = Assgn.get_roleDefinitionBindings();
var member = Assgn.get_member();
}
function failed(sender, args) {
alert("FAIL");
}
This works great until it gets to the alerts. Alert-1 is working, but not Alert-2. The Debugger says: The object does not support the property "get_$h".
And that happens in the sp_runtime.js with:
SP.DataRetrievalWithExpressionString.$1Q_0(a.get_$h(),d)
I dont really see a problem. Is this a bug or is it just not possible?
Ok, I used another way to do this and wanted to let you know, how it worked for me. I used a JS in the Ribbon Menu to call another website, which is just an empty site. I added the parameters (listguid, siteurl and the itemid's comma-seperated).
Then that site just prints an "True" or "False". This response will be caught by my Ribbon JS and show some message if it worked or not. This is my Ribbon JS:
<CustomAction
Id="ReadOnlyButton"
RegistrationId="101"
RegistrationType="List"
Location="CommandUI.Ribbon"
Sequence="15"
Rights="ManageLists"
Title="Set Readonly">
<CommandUIExtension>
<CommandUIDefinitions>
<CommandUIDefinition
Location="Ribbon.Documents.Manage.Controls._children">
<Button
Id="Ribbon.Documents.ReadOnly"
Command="ReadOnly"
Sequence="15"
Image16by16="/_layouts/1031/images/formatmap16x16.png"
Image16by16Left="-80"
Image16by16Top="-128"
Image32by32="/_layouts/1031/images/formatmap32x32.png"
Image32by32Left="-160"
Image32by32Top="-256"
Description="Read Only"
LabelText="Read Only"
TemplateAlias="o1"/>
</CommandUIDefinition>
</CommandUIDefinitions>
<CommandUIHandlers>
<CommandUIHandler
Command="ReadOnly"
CommandAction="javascript:
var nid;
function getItemIds()
{
var itemIds = '';
var items = SP.ListOperation.Selection.getSelectedItems();
var item;
for(var i in items)
{
item = items[i];
if(itemIds != '')
{
itemIds = itemIds + ',';
}
itemIds = itemIds + item.id;
}
return itemIds;
}
function handleReadyStateChange()
{
if (client.readyState == 4)
{
if (client.status == 200)
{
SP.UI.Notify.removeNotification(nid);
if(client.responseText == 'True') {
nid = SP.UI.Status.addStatus('The Rights has been set successfully', '', true);
SP.UI.Status.setStatusPriColor(nid, 'green');
} else {
nid = SP.UI.Status.addStatus('Error while setting Rights', '', true);
SP.UI.Status.setStatusPriColor(nid, 'red');
}
window.setTimeout('SP.UI.Status.removeStatus(\'' + nid + '\')', 5000);
}
}
}
function invokeReadOnly()
{
var itemLength = 0;
var params = 'itemids=' + getItemIds();
for (var i=0;i<params.length;i++) { if (',' == params.substr(i,1)) { itemLength++; } }
if(itemLength > 0) {
nid = SP.UI.Notify.addNotification('Rights set for ' + (itemLength +1) + ' elements...', true);
} else {
nid = SP.UI.Notify.addNotification('Set Rights...', true);
}
var site='{SiteUrl}';
var url = site + '/_layouts/ReadOnly.aspx?listId={ListId}';
client = null;
client = new XMLHttpRequest();
client.onreadystatechange = handleReadyStateChange;
client.open('POST', url, true);
client.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
client.setRequestHeader('Content-length', params.length);
client.send(params);
}
invokeReadOnly();"
EnabledScript="javascript:
function enableReadOnly()
{
var items = SP.ListOperation.Selection.getSelectedItems();
return (items.length > 0);
}
enableReadOnly();"/>
</CommandUIHandlers>
</CommandUIExtension>
</CustomAction>
And this is my site behind it (ReadOnly.aspx):
protected void Page_Load(object sender, EventArgs e)
{
string itemidsAll = Page.Request["itemids"];
string listId = Page.Request["listId"];
bool set = true;
if (!String.IsNullOrEmpty(itemidsAll))
{
string[] itemIds = itemidsAll.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
int item = 0;
SPSite _site = null;
SPListItem spitem = null;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
_site = new SPSite(SPContext.Current.Site.ID);
});
using (SPWeb web = _site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
SPList doclib = SPContext.Current.Web.Lists.GetList(new Guid(listId), false);
foreach (string itemId in itemIds)
{
if (Int32.TryParse(itemId, out item))
{
spitem = doclib.GetItemById(item);
set &= SetItem(spitem, SPContext.Current, ref _site);
}
}
web.AllowUnsafeUpdates = false;
}
_site.Dispose();
}
Response.Clear();
Response.Write(set.ToString());
Response.End();
}
The SetItem-Method is for setting the Rights. You can use your own stuff there :)

Categories

Resources