Banking API queried by Javascript - api

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).

Related

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

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.

Controller is not returning Viewbag value to the View

I have a controller named CallAllocation, and a View CallAllocation.
At first when the page loads only two dropdown appears with a submit button. On submission, page gets filled with rest of the details based on the selection from the two dropdowns. To achieve that I have made the following code:
Please focus on ViewBag.IsValid condition
My Controller be like
[HttpGet]
public ActionResult CallAllocation()
{
ViewBag.UserName = User.Identity.Name.ToString();
try
{
var NatureList = (from a in dataContext.CallNatures
select a);
Allocation Allocate = new Allocation();
Allocate.CallNaturelist = NatureList.ToList();
ViewData["SelectedTicket"] = 0;
Allocate.CallTicketList = null;
ViewBag.IsValid = "";
return View(Allocate);
}
catch (Exception ex)
{
TempData["ErrMsg"] = ex.Message;
return RedirectToAction("ShowError");
}
}
My View be like
#using (Html.BeginForm("CallAllocation", "Home", FormMethod.Post, new { id = "FrmCallAllocate"}))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary()
#Html.Raw(ViewBag.ErrMsg)
<div class="row ">
<div class="col-sm-12">
#if (ViewBag.IsVaild == "True")
{
#Html.DropDownListFor(m => m.SelectedCallNature, new SelectList(Model.CallNaturelist, "CallNatureID", "Description"),
"Select Nature", new { style = "width:250px", #class = "dropdown1", #readonly = "readonly;" })
#Html.DropDownList("CallTicket", new SelectList(string.Empty, "CallTicketNumber", "CallTicketNumber"), "Select Call Ticket",
new { style = "width:250px", #class = "dropdown1" , #readonly = "readonly;" })
<input type="submit" value="Get Ticket" style="background-color:#C5C5C5"/>
}
else
{
#Html.DropDownListFor(m => m.SelectedCallNature, new SelectList(Model.CallNaturelist, "CallNatureID", "Description"),
"Select Nature", new { style = "width:250px", #class = "dropdown1" })
#Html.DropDownList("CallTicket", new SelectList(string.Empty, "CallTicketNumber", "CallTicketNumber"), "Select Call Ticket",
new { style = "width:250px", #class = "dropdown1"})
<input type="submit" value="Get Ticket" style="background-color:#C5C5C5"/>
}
</div>
</div>
}
As you can see Controller sends ViewBag value "", and it should enter else condition of the View. But it is bypassing both the conditions.
Please help me understand why the controller is unable to send Viewbag value to the view. I have made similar cases but it's working in rest.
I have tried clearing the cache too.
Please note that my View is a strongly-typed View.

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);
}
}

File upload using dropzon.js

I'm trying to upload files using dropzone.js
View:
#using (Html.BeginForm("SaveMethod", "ControllerName", FormMethod.Post, new { enctype = "multipart/form-data", #class = "dropzone", id = "js-upload-form" }))
........................
<div class="form-inline">
<div class="form-group">
<input type="file" name="MainFile" id="js-upload-files"/>
</div>
<div class="upload-drop-zone" id="drop-zone">
Just drag and drop files here
</div>
<div class="dropzone-previews"></div>
</div>
JS:
var formData = null;
formData = new FormData($form[0]);
dropZone.ondrop = function (e) {
e.preventDefault();
this.className = 'upload-drop-zone';
startUpload(e.dataTransfer.files)
}
dropZone.ondragover = function () {
this.className = 'upload-drop-zone drop';
return false;
}
dropZone.ondragleave = function () {
this.className = 'upload-drop-zone';
return false;
}
var startUpload = function (files) {
for (var i = 0; i < files.length; i++) {
formData.append(files[i].name, files[i]);
}
}
Controller:
[HttpPost]
public JsonResult SaveMethod(TaskManage objTaskManage, HttpPostedFileBase files)
{
}
Now, after submit, i want to have files that was dropped on drop area along with the files attached in upload control. Here, what happens is files giving me null and when i use Request.Files["MainFile"] i get only the files dropped on dropzone area, it doesn't show me the file i have upload to control.
I'm not able to find out the issue. Any help is really appreciated.
File upload in ASP.NET MVC using Dropzone JS and HTML5
You can download the latest version from the official site here http://www.dropzonejs.com/ and also we can install using the nuget package manage console by the following command Package Manager Console
PM> Install-Package dropzone
Now create a bundle for your script file in BundleConfig.cs
bundles.Add(new ScriptBundle("~/bundles/dropzonescripts").Include(
"~/Scripts/dropzone/dropzone.js"));
Similarly add the dropzone stylesheet in the BundleConfig.cs
bundles.Add(new StyleBundle("~/Content/dropzonescss").Include(
"~/Scripts/dropzone/css/basic.css",
"~/Scripts/dropzone/css/dropzone.css"));
Now add the bundle reference in your _Layout page
View Page:
<div class="jumbotron">
<form action="~/Home/SaveUploadedFile" method="post" enctype="multipart/form-data" class="dropzone" id="dropzoneForm" style="width: 50px; background: none; border: none;">
<div class="fallback">
<input name="file" type="file" multiple />
<input type="submit" value="Upload" />
</div>
</form>
</div>
Controller:
public ActionResult SaveUploadedFile()
{
bool isSavedSuccessfully = true;
string fName = "";
try{
foreach (string fileName in Request.Files)
{
HttpPostedFileBase file = Request.Files[fileName];
//Save file content goes here
fName = file.FileName;
if (file != null && file.ContentLength > 0)
{
var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\WallImages", Server.MapPath(#"\")));
string pathString = System.IO.Path.Combine(originalDirectory.ToString(), "imagepath");
var fileName1 = Path.GetFileName(file.FileName);
bool isExists = System.IO.Directory.Exists(pathString);
if (!isExists)
System.IO.Directory.CreateDirectory(pathString);
var path = string.Format("{0}\\{1}", pathString, file.FileName);
file.SaveAs(path);
}
}
}
catch(Exception ex)
{
isSavedSuccessfully = false;
}
if (isSavedSuccessfully)
{
return Json(new { Message = fName });
}
else
{
return Json(new { Message = "Error in saving file" });
}
}
Now add the following script to your view page at the and in script tag.
//File Upload response from the server
Dropzone.options.dropzoneForm = {
init: function () {
this.on("complete", function (data) {
//var res = eval('(' + data.xhr.responseText + ')');
var res = JSON.parse(data.xhr.responseText);
});
}
};
Here you can see the response from server.

formData.append() not working - checked in Chrome,Mozilla, IE

Am using Jquery FormData for the first time, but seems am missing something. In the JS - postAjax method, when new FormData() is called, it just skips the remaining lines and goes to the end of the function without any errors. What am I doing wrong here?
template.js //script files in this order
<script src="js/jquery-2.1.0.js"></script>
<script src="js/jquery.form.js"></script>
<script src="js/bootstrap.js"></script>
<script src="js/bootstrapValidator.js"></script>
<script src="js/hemoncCBCFunctions.js"></script>
<script src="js/validations.js"></script>
JSP
<form name ="newSectionSubmitForm" id="newSectionSubmitForm" class="form-horizontal" role="form" method="post" ENCTYPE="multipart/form-data">
<table>
<tr>
<td>
<input type="file" id='imageFile0' name='imageFile0' class="form-control" />
</td>
</tr>
</table>
<form>
JS
function submitNewSection(targetUrl, form) {
postAjaxData(null, 'content', targetUrl, form, null, null);
}
function postAjaxData(initiatingElement, targetElement, targetUrl, form,
additionalParamMap, successCallback) {
var $targetElement = $('#' + targetElement);
var serializedFormData;
serializedFormData = $('#' + form).serialize();
for ( var j in additionalParamMap) {
serializedFormData += "&" + j + "=" + additionalParamMap[j];
}
alert('serialized form data ' + serializedFormData);
var formData = new FormData(serializedFormData);//**exits the function no errors**
formData.append("file", $('#imageFile0').files[0]);
alert('serialized form data ' + formData);
$.ajax({
type : "POST",
cache : false,
data : formData,
url : targetUrl,
success : function(data) {
processRedirect(data);
$targetElement.html(data);
$targetElement.show();
if (successCallback != null) {
successCallback(data);
}
},
error : function(xhr, httpRequest, textStatus, errorThrown) {
var errorId = xhr.getResponseHeader("errorId");
var errorMsg = xhr.getResponseHeader("errorMessage");
if (errorId != null && errorId != undefined) {
$("#page_error").html(
"An unexpected error has occurred. Error Id: "
+ errorId);
} else {
$("#page_error").html("An unexpected error has occurred.");
}
},
});
Controller File (however the code does not reach here)
#RequestMapping(value = "/submitNewSection.html")
public String submitNewSection( MultipartHttpServletRequest req, HttpServletRequest request, Model model) {
Iterator<String> itr = req.getFileNames();
MultipartFile mpf = req.getFile(itr.next());
System.out.println("file name " + mpf.getOriginalFilename() +" uploaded!");
}
Thanks so much.