Records Not Displaying in jquery.datatables using server side pagination processing - mvc.jquery.datatables

i am trying to get jquery.datatables working using server side processing and pagination. I used the following example article as a guide because its close to the version VS2017 that i am using-
https://www.c-sharpcorner.com/article/filtering-jquery-data-table-server-side-using-mvc-and-entity-framework/
When I run the application i get the following error:
DataTables warning: table id=tblrtr - Requested unknown parameter 'Id' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4
and an empty grid that shows 10 blank lines and the right page count.
I have debugged the code and it finds all the records and values, and indeed the finalresult variable does return the contents of the 10 rows- but they dont seem to make it to the datatable grid.
Here is the controller code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using RTMGMTTest.Models;
namespace RTMGMTTest.Controllers
{
public class ReportsToRecordsController : Controller
{
private readonly RTMGMTContext _context;
public ReportsToRecordsController(RTMGMTContext context)
{
_context = context;
}
// GET: ReportsToRecords
public async Task<IActionResult> Index()
{
//return View(await _context.ReportsToRecords.ToListAsync());
return View();
}
[HttpPost]
public JsonResult RTRList(DTParameters param)
{
int TotalCount = 0;
var filtered = this.GetRTRFiltered(param.Search.Value, param.SortOrder, param.Start, param.Length, out TotalCount);
var RTRList = filtered.Select(o => new ReportsToRecords()
{
Id = o.Id,
ReportingId = o.ReportingId,
Title = o.Title,
Name = o.Name,
ReportsToId = o.ReportsToId,
EmployeeId = o.EmployeeId
});
DTResult<ReportsToRecords> finalresult = new DTResult<ReportsToRecords>
{
draw = param.Draw,
data = RTRList.ToList(),
recordsFiltered = TotalCount,
recordsTotal = filtered.Count
};
return Json(finalresult);
}
and
//for server side processing
public List<ReportsToRecords> GetRTRFiltered(string search, string sortOrder, int start, int length, out int TotalCount)
{
var result = _context.ReportsToRecords.Where(p => (search == null
|| (p.ReportingId != null && p.ReportingId.ToLower().Contains(search.ToLower())
|| p.Title != null && p.Title.ToLower().Contains(search.ToLower())
|| p.Name != null && p.Name.ToLower().Contains(search.ToLower())
|| p.ReportsToId != null && p.ReportsToId.ToLower().Contains(search.ToLower())
|| p.EmployeeId!= null && p.EmployeeId.ToLower().Contains(search.ToLower())
))).ToList();
TotalCount = result.Count;
result = result.Skip(start).Take(length).ToList();
switch (sortOrder)
{
case "ReportingId":
result = result.OrderBy(a => a.ReportingId).ToList();
break;
case "Title":
result = result.OrderBy(a => a.Title).ToList();
break;
case "Name":
result = result.OrderBy(a => a.Name).ToList();
break;
case "ReportsToId":
result = result.OrderBy(a => a.ReportsToId).ToList();
break;
case "EmployeeId":
result = result.OrderBy(a => a.EmployeeId).ToList();
break;
default:
result = result.AsQueryable().ToList();
break;
}
return result.ToList();
}
The view page looks as follows:
#model IEnumerable<RTMGMTTest.Models.ReportsToRecords>
#{
ViewData["Title"] = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<p>
<a asp-action="Create">Create New</a>
</p>
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.3.1.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" />
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
if ($.fn.DataTable.isDataTable('#tblrtr')) {
$('#tblrtr').dataTable().fnDestroy();
$('#tblrtr').dataTable().empty();
}
var complete = $('#tblrtr').DataTable(
{
"serverSide": true,
"destroy": true,
"processing": true,
"ajax":
{
url: "/ReportsToRecords/RTRList",
method: "POST"
},
"columns": [
{ "data": "Id"},
{ "data": "ReportingId" },
{ "data": "Title" },
{ "data": "Name" },
{ "data": "ReportsToId" },
{ "data": "EmployeeId" }
]
}
);
/// Following code is for filter input to apply filter only on Enter
var itm = $("#tblrtr_filter input")
itm.unbind();
itm.keyup(function (e) {
//enter or tab
if (e.keyCode == 13) {
complete.search(this.value).draw();
}
});
});
</script>
<table class="table" id="tblrtr">
<thead>
<tr>
<th>
Id
</th>
<th>
ReportingId
</th>
<th>
Title
</th>
<th>
Name
</th>
<th>
ReportsToId
</th>
<th>
EmployeeId
</th>
<th></th>
</tr>
</thead>
<tbody></tbody>
</table>
Does anyone know what would cause the data returned from the controller to not display and cause the resulting message? Thanks.

Related

Memory Leak vue axios

I am building User Interface with Vue - created with #vue/cli 4.1.2.
Very Simple with not many components. Menu on the left side and results (in a table on the right side). Http requests are made with axios, and the results (responses) are approximately 1000 rows * 6 cols (cca 200KB sized objects). I am using Vuex and Router. However, the HEAP size keeps growing with every request I made. As if all the data downloaded(and much more) never gets released from memory. From initial 18MB heap size increases to cca100 MB with app 10 requests.
I tried to isolate the problem with turning off store, changing the template part (in fact, not showing anything at all but the number of records) but have no idea what is causing this. Tried to make values of gridData and gridColumns null before each reuest, but nothing helps. It seems that all the data get stored in memory and never release. Did try to analyze with google dev tools, but could not resolved that.
The component that is responsible for performing/and displaying requests is as follows:
<template>
<main>
<form id="search">Search <input
name="query"
v-model="searchQuery"
/></form>
<pre>cParamsRecord: {{ cParamsRecord }}</pre>
<pre>cActiveGrid: {{ cActiveGrid }}</pre>
<pre>cActiveRSet: {{ cActiveRSet }}</pre>
<div id="tbl">
<thead>
<tr>
<th
v-for="(col, index) in gridColumns"
:key="index"
>
{{ col }}
</th>
</tr>
</thead>
<tbody>
<tr
v-for="(entry, index) in gridData"
:key="index"
#click="setActiveRow(entry)"
v-bind:class="{ active: entry == cActiveRow }"
>
<td
v-for="(col, index) in gridColumns"
:key="index"
>
{{ entry[col] }}
</td>
</tr>
</tbody>
<span>Num of records here: {{ propertyComputed }} </span>
</div>
</main>
</template>
<script>
import { rSetParams } from "#/playground/mockData.js";
import api_service from "#/services/api_service";
import * as types from "#/store/types.js";
export default {
name: "pGrid1",
components: {},
data () {
return {
searchQuery: "",
gridData: null,
gridColumns: null,
rSetParams: rSetParams,
property: "Blank"
};
},
computed: {
cActiveRSet: {
get () {
return this.$store.getters[types.ACTIVE_R_SET];
},
set (value) {
this.$store.commit(types.ACTIVE_R_SET, value);
}
},
cActiveGrid: {
get () {
return this.$store.getters[types.ACTIVE_GRID];
},
set (value) {
this.$store.commit(types.ACTIVE_GRID, value);
}
},
cRSetParams: {
get () {
return this.$store.getters[types.R_SET_PARAMS];
},
set (value) {
this.$store.commit(types.R_SET_PARAMS, value);
}
},
cActiveRow: {
get () {
return this.$store.getters[types.ACTIVE_ROW];
},
set (value) {
this.$store.commit(types.ACTIVE_ROW, value);
}
},
cParamsRecord: {
get () {
return this.$store.getters[types.PARAMS_RECORD];
},
set (value) {
this.$store.commit(types.PARAMS_RECORD, value);
}
},
},
methods: {
//function that makes http read http request and stores data locally into
//component data (this.gridData and this.gridColumns
async getRData () {
this.gridData = null
this.gridColumns = null
console.log(
"starting getRData for grid: ",
this.cActiveGrid,
" and routine set: " + this.cActiveRSet
);
if (this.cActiveRSet && this.cActiveGrid) {
var queryData;
try {
this.$store.commit(types.IS_LOADING, true);
const routine = this.cActiveRSet + "_" + this.cActiveGrid + "r";
console.log("routine: ", routine);
const r1 = await api_service.getRData(routine);
//const result = await r1
queryData = r1;
this.gridData = queryData.data;
console.log(this.gridData);
this.gridColumns = this.getTblHeadersFromResults(this.gridData);
//store data into the right vuex variable (in this case R1_DATA)
if (this.cActiveGrid == 1) {
this.$store.commit(types.R1_DATA, queryData.data);
} else if (this.cActiveGrid == 2) {
this.$store.commit(types.R2_DATA, queryData.data);
} else if (this.cActiveGrid == 3) {
this.$store.commit(types.R3_DATA, queryData.data);
}
this.$store.commit(types.IS_LOADING, false);
return queryData;
} catch (e) {
this.$store.commit(types.IS_LOADING, false);
console.error(e);
}
} else {
console.log(
"async getRData not run because there's no cActiveRSet or no cActiveGrid"
);
}
},
//function for defining active row in a table - - when we click on the row, row object get stored into cActiveRow
setActiveRow (row) {
console.log("in setActiveRow and row is: ", row);
this.$store.commit(types.ACTIVE_ROW, row);
this.createParamsRecordForNextGrid();
this.getRDataForNextGrid();
},
//creating tblHeaders object from first line of results
getTblHeadersFromResults (res) {
var tblHeadersRaw = Object.keys(res[0]);
return tblHeadersRaw;
},
//combining values from our record(clicked) - iecActiveRow with rParams to get appropriate record for using it when making http request
createParamsRecordForNextGrid () {
console.log("starting func createParamsRecord");
var nextGrid = this.cActiveGrid + 1;
var rR = this.cActiveRSet + "_" + nextGrid.toString() + "r"; //creating the name of our routine here
//const rR = "r_00305"
console.log("rR: ", rR);
//console.log("rSetParams: " + JSON.stringify(rSetParams))
var rParams = this.cRSetParams.filter(r => r.i9_routine_name == rR); //onyl get the params for our routine from i9 (rSetParams)
console.log("rParams: ", rParams);
// eslint-disable-next-line no-unused-vars
var paramsRecord = {};
console.log(this.cActiveRow);
var cActiveRowObj = this.cActiveRow;
for (var key in cActiveRowObj) {
//console.log(key)
for (var i = 0; i < rParams.length; i++) {
var rParamsObj = rParams[i];
//console.log("rParamsObj.i9_header_db: ", rParamsObj.i9_header_db, " ************** key from cActiveRow: ", key)
if ("p_" + key == rParamsObj.i9_header_db) {
//console.log("matching key with rParamsObj: ", key, rParamsObj.i9_header_db)
//console.log("value: ", cActiveRowObj[key])
paramsRecord[rParamsObj.i9_header_db] = cActiveRowObj[key];
}
}
}
this.$store.commit(types.PARAMS_RECORD, paramsRecord);
return paramsRecord;
}
//create types String - based on cActiveGrid we create types string so that we can store table data into the right variable in this.$store
},
watch: {
cActiveRSet: {
// eslint-disable-next-line no-unused-vars
handler () {
this.getRData();
},
immediate: true
}
}
};
</script>
After

JsonRequestBehaviour.AllowGet Not Working

i am working for JQuery Datatables server side. While creating the json object, to return back, it doesn't allow JsonRequestBehaviour.AllowGet. If code is exactly same what below is, then i am not able to get data in client side.
HTML :
<table class="table table-striped table-bordered table-hover" id="EmployeeTable">
<thead>
<tr>
<th>LastName</th>
</tr>
</thead>
<tbody></tbody>
</table>
JQuery:
$('#EmployeeTable').DataTable({
"processing" : true, // for show progress bar
"serverSide" : true, // for process in server side
"filter" : false, // to disable search box
"orderMulti" : false,// for disable multiple columns at once
"ajax" : {
"url" : "/Employee/GetEmployeeDataTable",
"type" : "post",
"datatype" : "json"
},
"columns" : [
{ "data": "LastName", "orderable": true }
]
});
Server Side:
[HttpPost]
public ActionResult GetEmployeeDataTable()
{
// Get Parameters
//get start(paging start index) and length(page size for paging)
var draw = Request.Form["draw"].FirstOrDefault();
var start = Request.Form["start"].FirstOrDefault();
var length = Request.Form["length"].FirstOrDefault();
//get sort column values
var sortColumn = Request.Form["columns[" + Request.Form["order[0][column]"].FirstOrDefault()+"][name]"].FirstOrDefault();
var sortColumnDir = Request.Form["order[0][dir]"].FirstOrDefault();
int pageSize = length != null ? Convert.ToInt32(length) : 0;
int skip = start != null ? Convert.ToInt32(start) : 0;
int totalRecords = 0;
var employees = getDataService.GetAllEmployees().Select(x => new {
x.LastName
}).ToList();
if(!(string.IsNullOrEmpty(sortColumn) && string.IsNullOrEmpty(sortColumnDir)))
{
employees.OrderBy(x => sortColumn + " " + sortColumnDir);
}
totalRecords = employees.Count();
var data = employees.Skip(skip).Take(pageSize).ToList();
var result = Json(new
{ draw = draw,
recordsFiltered = totalRecords,
recordsTotal = totalRecords,
data = data
});
return result;
}
But if i put like following
var result = Json(new
{ draw = draw,
recordsFiltered = totalRecords,
recordsTotal = totalRecords,
data = data
},JsonRequestBehaviour.AllowGet);
then i can't find this thing in mvc core. Please help me what should i do.
In asp.net core, the Json method does not have an overload which takes JsonRequestBehavior. So you may simply call the Json method with the data you want to pass.
var result = Json(new
{ draw = draw,
recordsFiltered = totalRecords,
recordsTotal = totalRecords,
data = data
});
return result;

Remember selected checkboxes across paginated pages

I am displaying data in a table and doing some paging and sorting. I have a checkbox for everyrow.
When I move from one page to another, I will like to keep the checkboxes checked if they were checked.
I dont want the checked boxes to uncheck as I navigate from page to page. How do i achieve that?
Here is my jquery.
<script type="text/javascript">
$(document).ready(function () {
$(".header").click(function (evt) {
var sortfield = $(evt.target).data("sortfield");
if ($("#SortField").val() == sortfield)
{
if($("#SortDirection").val()=="ascending")
{
$("#SortDirection").val("descending");
}
else
{
$("#SortDirection").val("ascending");
}
}
else
{
$("#SortField").val(sortfield);
$("#SortDirection").val("ascending");
}
evt.preventDefault();
$("form").submit();
});
$(".pager").click(function (evt) {
var pageindex = $(evt.target).data("pageindex");
$("#CurrentPageIndex").val(pageindex);
evt.preventDefault();
$("form").submit();
});
});
</script>
Here is my html page
<body>
<h1>List of Customers</h1>
#{
PageSortOnlineEx.Models.SortingPagingInfo info = ViewBag.SortingPagingInfo;
}
#using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
#Html.Hidden("SortField", info.SortField)
#Html.Hidden("SortDirection", info.SortDirection)
#Html.Hidden("PageCount", info.PageCount)
#Html.Hidden("PageSize", info.PageSize)
#Html.Hidden("CurrentPageIndex", info.CurrentPageIndex)
<table border="1" cellpadding="10">
<tr>
<th>Select</th>
<th>CustomerID</th>
<th>CompanyName</th>
<th>ContactName</th>
<th>Country</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>#Html.CheckBox("select", false)</td>
<td>#item.CustomerID</td>
<td>#item.CompanyName</td>
<td>#item.ContactName</td>
<td>#item.Country</td>
</tr>
}
<tr>
<td colspan="4">
#for (var i = 0; i < info.PageCount; i++)
{
if (i == info.CurrentPageIndex)
{
<span>#(i + 1)</span>
}
else
{
#(i + 1)
}
}
</td>
</tr>
</table>
}
</body>
Here is my controller code
public ActionResult Index()
{
using (NorthwindEntities db = new NorthwindEntities())
{
SortingPagingInfo info = new SortingPagingInfo();
info.SortField = "CustomerID";
info.SortDirection = "ascending";
info.PageSize = 10;
info.PageCount = Convert.ToInt32(Math.Ceiling((double)(db.Customers.Count() / info.PageSize)));
info.CurrentPageIndex = 0;
var query = db.Customers.OrderBy(c => c.CustomerID).Take(info.PageSize);
ViewBag.SortingPagingInfo = info;
List<Customer> model = query.ToList();
return View(model);
}
}
[HttpPost]
public ActionResult Index(SortingPagingInfo info)
{
using (NorthwindEntities db = new NorthwindEntities())
{
IQueryable<Customer> query = null;
switch (info.SortField)
{
case "CustomerID":
query = (info.SortDirection == "ascending" ? db.Customers.OrderBy(c => c.CustomerID) : db.Customers.OrderByDescending(c => c.CustomerID));
break;
case "CompanyName":
query = (info.SortDirection == "ascending" ? db.Customers.OrderBy(c => c.CompanyName) : db.Customers.OrderByDescending(c => c.CompanyName));
break;
case "ContactName":
query = (info.SortDirection == "ascending" ? db.Customers.OrderBy(c => c.ContactName) : db.Customers.OrderByDescending(c => c.ContactName));
break;
case "Country":
query = (info.SortDirection == "ascending" ? db.Customers.OrderBy(c => c.Country) : db.Customers.OrderByDescending(c => c.Country));
break;
}
query = query.Skip(info.CurrentPageIndex * info.PageSize).Take(info.PageSize);
ViewBag.SortingPagingInfo = info;
List<Customer> model = query.ToList();
return View(model);
}
}

how to Filter webgrid in mvc4 based on textbox input and dropdownList input

I am still in learning curve of mvc4 . I know how to bind a webgrid in mvc4 . But my doubt is can anyone share me the idea how to bind webgrid based on filter conditions from textbox input and dropdownList input. For eg : If textbox has a date "11/15/2013" and dropdownList has the doctor name "Charles" then i need to show in gridview the list of patients who has appointment with doctor " charles " on "11/15/2013" .
code
<div id="gridContent">
#grid.GetHtml(
fillEmptyRows: true,
tableStyle: "webGrid",
alternatingRowStyle: "alternate-row",
headerStyle: "grid-header",
footerStyle: "grid-footer",
mode: WebGridPagerModes.All,
firstText: "<< First",
previousText: "< Prev",
nextText: "Next >",
lastText: "Last >>",
columns: new[] {
grid.Column("PatientID"),
grid.Column("PatientName"),
grid.Column("Age"),
grid.Column("DOB"),
grid.Column("Sex"),
grid.Column("Phone"),
grid.Column("Mobile"),
grid.Column("City"),
grid.Column("PinCode"),
// grid.Column("Dr_Remarks",header:"Remarks",style:"left"),
//grid.Column("Dr_Add1",
// header: "Bed Count",style:"right"
//),
grid.Column("",
header: "Actions",
format: #<text>
#Html.ActionLink("Edit", "EditPatient", new { id = item.PatientID }, htmlAttributes: new { #class = "link" })
|
#Html.ActionLink("Delete", "PatientList", new { id = item.PatientID },
htmlAttributes: new { #class = "link", onclick = "return confirm('Are you sure you wish to delete this record?');" })
</text>
)
})
</div>
**controller**
public ActionResult PatientList(int page = 1, string sort = "Dr_Id", string sortDir = "ASC", int id = 0)
{
if (id != 0)
{
bool isDelete = false;
isDelete = rdm_Patient.DeletePatient(id);
return View(GetPatient(page, sort, sortDir));
}
else
{
return View(GetPatient(page, sort, sortDir));
}
}
private PatientPageViewModel GetPatient(int page = 1, string sort = "Dr_Id", string sortDir = "ASC")
{
const int patientPerPage = 5;
var numPatient = rdm_Patient.CountPatient();
sortDir = sortDir.Equals("desc", StringComparison.CurrentCultureIgnoreCase) ? sortDir : "asc";
var validColumns = new[] { "PatientID", "PatientName" };
if (!validColumns.Any(c => c.Equals(sort, StringComparison.CurrentCultureIgnoreCase)))
sort = "PatientID";
var doctors = rdm_Patient.getpatientpage(page, patientPerPage, "it." + sort + " " + sortDir);
var data = new PatientPageViewModel()
{
numberOfPatient = numPatient,
patientPerPage = patientPerPage,
Patient = doctors,
};
return data;
}
As I understand of your question you need filtering in your WebGrid that doesn’t include any kind of tool to perform it. So, you have to do it manually.
You should take into account the following points:
Firstly, include a form in the View where the query criteria is collected in order to send it to the controller.
Secondly, prepare the Controller so it can receive this criteria and make it reach the Model.
Thirdly, in the Model, simply apply this criteria when counting the total amount of rows, and when obtaining the data to be displayed in the grid page.
Jose M. Aguilar in his post describes all steps which can help you to design your view and controller.
Index.cshtml:
#model MvcApplication1.Models.Employee
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<table>
<tr>
<td>
#Html.DropDownList("lstdepartment", Model.Department_List)
</td>
</tr>
<tr>
<td>
<div id="EmployeeViewGrid">
#Html.Partial("EmployeeView",Model.Employee_Grid)
</div>
</td>
</tr>
</table>
<script type="text/javascript">
$('#lstdepartment').change(function (e) {
e.preventDefault();
var url = '#Url.Action("Filter")';
$.get(url, { department: $(this).val() }, function (result) {
debugger;
$('#EmployeeViewGrid').html(result);
});
});
</script>
Partial view:
#model List< MvcApplication1.Models.Employee>
#{
ViewBag.Title = "EmployeeView";
}
<h2>EmployeeView</h2>
<div id="gridposition" style="overflow: scroll; height: 300px; overflow-x: hidden;">
#{
var grid1 = new WebGrid(source: Model, canPage: true, rowsPerPage: 5, ajaxUpdateContainerId: "gridContent");
#grid1.GetHtml(mode: WebGridPagerModes.All, tableStyle: "webGrid",
headerStyle: "header",
alternatingRowStyle: "alt",
selectedRowStyle: "select",
rowStyle: "description",
htmlAttributes: new { id = "positionGrid" },
fillEmptyRows: false,
columns: grid1.Columns(
grid1.Column("EmployeeId", header: "EmployeeId"),
grid1.Column("EmpName", header: "EmpName"),
grid1.Column("Age", header: "Age"),
grid1.Column("Department", header: "Department"),
grid1.Column("Salary", header: "Salary")))
}
</div>
Controller:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication1.Models;
namespace MvcApplication1.Controllers
{
public class EmployeeController : Controller
{
private EmployeeDatabaseEntities1 db = new EmployeeDatabaseEntities1();
//
// GET: /Employee/
public ActionResult Index()
{
Employee _model = new Employee();
//_model.Employee_Grid = db.tbl_Employee.ToList();
var departmentlist = db.tbl_department.ToList();
_model.Department_List = (from d in departmentlist
select new SelectListItem
{
Value = d.department_id.ToString(),
Text = d.department_name
}).ToList();
var qq = (from e in db.tbl_Employee
join d in db.tbl_department on e.Department_id equals d.department_id
select new Employee
{
Department_id=e.Department_id,
EmployeeId=e.EmployeeId,
EmpName=e.EmpName,
Age=e.Age,
Department=d.department_name
}).ToList();
_model.Employee_Grid = qq;
return View("Index", _model);
}
public ActionResult Filter(string department)
{
int? department_id = Convert.ToInt32(department);
var qq = (from e in db.tbl_Employee
join d in db.tbl_department on e.Department_id equals d.department_id
where e.Department_id == department_id
select new Employee
{
Department_id = e.Department_id,
EmployeeId = e.EmployeeId,enter code here
EmpName = e.EmpName,
Age = e.Age,
Department = d.department_name
}).ToList();
return PartialView("EmployeeView",qq);
}
}
}

Banking API queried by Javascript

I am finalising a college project and I am stuck.
I have created an API in netbeans and it is working fine.
Returing e.g.
<?xml version="1.0" encoding="UTF-8"?>
<accountholder>
<accountnumber>45672</accountnumber>
<address>234 THE BANK, DUBLIN 1</address>
<balance>763.32</balance>
<email>JOHANN#SMITH.COM</email>
<firstname>JOHANN</firstname>
<id>1</id>
<lastname>SMITH</lastname>
<pinnumber>1234</pinnumber>
</accountholder>
Now I am trying to create a javascript to return data when searching by Id.
<script language="javascript" type="text/javascript">
var request = null;
function createRequest() {
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("MsXML2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = null;
}
}
}
if (request == null)
alert("Error creating request object!");
}
function getMessage()
{
createRequest();
var accountholderid = document.getElementById("Id").value;
id=eval(accountholderid);
var url = "http://localhost:8080/BankProjectApi/webresources/bankprojectapi.accountholder/"+id;
request.onreadystatechange = handleResponse;
request.open("GET", url, true);
request.send(null);
}
function handleResponse() {
if (request.readyState==4 && request.status==200)
{
var xmlDocument=request.responseXML;
var firstname = xmlDocument.getElementsByTagName("firstname");
var lastname = xmlDocument.getElementsByTagName("lastname");
var accountnumber = xmlDocument.getElementsByTagName("accountnumber");
for(var i=0; i<firstname.length; i++) {
var firstname = firstname[i].childNodes[0].nodeValue;
var lastname = lastname[i].childNodes[0].nodeValue;
var accountnumber= accountnumber[i].childNodes[0].nodeValue;
document.getElementById('lastname').value=firstname;
document.getElementById('firstname').value=lastname;
document.getElementById('accountnumber').value=accountnumber;
}
}
}
</script>
In the body I have an input textfield with a button with an on click:
<td>Enter Account holder ID : </td>
<td><input type="text" id="playerid" size="10"/>
<input type="button" value="Get Details" onclick="getMessage()"/>
</tr>
<tr>
<td>Account holder Last Name : </td>
<td> <input type="text" id="lastname" size="10"/> </td>
</tr>
<tr>
<td>Account holder First Name : </td>
<td> <input type="text" id="firstname" size="10"/> </td>
</tr>
<tr>
<td>Account number : </td>
<td> <input type="text" id="accountnumber" size="10"/> </td>
</tr>
What am I missing as it is not returning anything :(
I believe your id value for the 'accountholderid' was looking for 'Id' instead of 'playerid'.
May I ask why you are calling 'eval' on the value? Do you need parseInt?
(function () {
var request = null;
function createRequest() {
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject('MsXML2.XMLHTTP');
} catch (othermicrosoft) {
try {
request = new ActiveXObject('Microsoft.XMLHTTP');
} catch (failed) {
request = null;
}
}
}
if (request === null) {
alert('Error creating request object!');
}
}
function getMessage() {
createRequest();
var accountholderid = document.getElementById('playerid').value,
id = eval(accountholderid),
url = 'http://localhost:8080/BankProjectApi/webresources/bankprojectapi.accountholder/' + id;
request.onreadystatechange = handleResponse;
request.open("GET", url, true);
request.send(null);
}
function handleResponse() {
if (request.readyState === 4 && request.status === 200) {
var xmlDocument = request.responseXML,
firstname = xmlDocument.getElementsByTagName('firstname'),
lastname = xmlDocument.getElementsByTagName('lastname'),
accountnumber = xmlDocument.getElementsByTagName('accountnumber');
for(var i = 0, max = firstname.length; i < max; i += 1) {
var firstname = firstname[i].childNodes[0].nodeValue,
lastname = lastname[i].childNodes[0].nodeValue,
accountnumber = accountnumber[i].childNodes[0].nodeValue;
document.getElementById('lastname').value = firstname;
document.getElementById('firstname').value = lastname;
document.getElementById('accountnumber').value = accountnumber;
}
}
}
}());
Also, I did a quick refactoring of your code to aid in my assessing the issue, adhere to more community conventions as well as avoid common JS pitfalls. (ex. closure, missing var declarations, ===, curlys everywhere, single variable pattern, and some others).