Javascript drop down menu and validate calendar picker - javascript

Ok I have a drop down menu that is dynamically generated by .jsp and populated with data fetched from database.2 dropdown list and 2 datepicker
The problem that I am having is with a JS validation, am not so good with JavaScript but for the purposes of my mini project I have to work with it anyway....
The problem is that with JS I am checking if a user has selected two drop-down fields and two date pickers so the form can be submitted and the list of the searching should be shows below the button else display a warning message indicating that the drop-downs and date pickers have not been filled.
Where should I do the validation of those 4 fields? How to use the'EXECUTE' to call the class from 'SelectOperation.java'(as per attached).
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.hibernate.Session;
import entityBeans.AccessLevel;
import entityBeans.Business;
import entityBeans.CustomerBranch;
import entityBeans.Menu;
import entityBeans.TransactionLog;
import entityBeans.User;
import cmnUtilities.CmnConstants;
public class SelectOperation {
Session session = ConnectionMySQL.getInstance().getConnection();
private static SelectOperation selectData = new SelectOperation();
private SelectOperation()
{
}
public User Select_login_User(String user_id)
{
User loginUser = null;
try
{
loginUser = (User)session.get(User.class,user_id.trim());
}
catch(Exception exception)
{
exception.printStackTrace();
}
return loginUser;
}
public User Chech_User_existence(String user_id)
{
User CheckUser = null;
try
{
CheckUser = (User)session.get(User.class,user_id.trim());
}
catch(Exception exception)
{
exception.printStackTrace();
}
return CheckUser;
}
public List<List<Menu>> Select_User_Menu(int Access_id)
{
List<Menu> UserMenu = null;
List<List<Menu>> Menus = new ArrayList<List<Menu>>();
AccessLevel acl = null ;
try
{
if(session.isOpen())
{
// acl = (AccessLevel)session.get(AccessLevel.class,Access_id.trim());
// StringBuffer AccessLevel = formatedMenuIds(acl.getMenuId());
// System.out.println(AccessLevel);
//UserMenu = (List<Menu>)session.createQuery("from Menu where menuId in ("+menuIds+")").list();
UserMenu = (List<Menu>)session.createQuery("from Menu where menuAccLevel >='"+Access_id+"'").list();
List<Menu> MainModule = new ArrayList<Menu>();
List<Menu> SubModule = new ArrayList<Menu>();
for(Menu seperateMenu : UserMenu)
{
if((seperateMenu.getMenuId().length()) == CmnConstants.MAIN_MENU)
{
MainModule.add(seperateMenu);
}
if((seperateMenu.getMenuId().length()) == CmnConstants.SUB_MENU)
{
SubModule.add(seperateMenu);
}
}
for(Menu disp1 : MainModule)
{
List<Menu> finaly = new ArrayList<Menu>();
finaly.add(disp1);
for(Menu disp2 : SubModule)
{
if(disp2.getMenuId().startsWith(disp1.getMenuId()))
{
finaly.add(disp2);
}
}
Menus.add(finaly);
}
System.out.println(Menus);
}
else
{
System.out.println("session closed");
}
}
catch(Exception exception)
{
exception.printStackTrace();
}
return Menus;
}
//METHOD RETURNS ALL ACCESS LEVEL CODE AND IT'S DESCRIPTION
public List<AccessLevel> getAllAccessLevel()
{
List<AccessLevel> accessList = null;
try
{
accessList = (List<AccessLevel>)session.createQuery("from AccessLevel").list();
System.out.println(accessList);
}
catch(Exception exception)
{
exception.printStackTrace();
}
return accessList;
}
//METHOD TO SELECT ALL BRANCH IDS
public List<CustomerBranch> getAllCustomerBranch()
{
List<CustomerBranch> branchList = null;
try
{
branchList = (List<CustomerBranch>)session.createQuery("from CustomerBranch").list();
System.out.println(branchList);
}
catch(Exception exception)
{
exception.printStackTrace();
}
return branchList;
}
//METHOD TO SELECT ALL TRANSACTION_LOG DETAILS
public List<TransactionLog> getAllTransactionLog()
{
List<TransactionLog> TxnList = null;
try
{
TxnList = (List<TransactionLog>)session.createQuery("from TransactionLog").list();
System.out.println(TxnList);
}
catch(Exception exception)
{
exception.printStackTrace();
}
return TxnList;
}
//METHOD TO SELECT ALL BUSINESS
public List<Business> getAllBusiness()
{
List<Business> BusinessList = null;
try
{
BusinessList = (List<Business>)session.createQuery("from Business").list();
System.out.println(BusinessList);
}
catch(Exception exception)
{
exception.printStackTrace();
}
return BusinessList;
}
public Business SelectBusiness_Id(String business_id)
{
Business CheckBusiness_id = null;
try
{
CheckBusiness_id = (Business)session.get(Business.class,business_id.trim());
}
catch(Exception exception)
{
exception.printStackTrace();
}
return CheckBusiness_id;
}
public CustomerBranch SelectBranch_Id(String branch_id)
{
CustomerBranch CheckBranch_id = null;
try
{
CheckBranch_id = (CustomerBranch)session.get(CustomerBranch.class,branch_id.trim());
}
catch(Exception exception)
{
exception.printStackTrace();
}
return CheckBranch_id;
}
public TransactionLog FromDateSel(String txn_date)
{
TransactionLog transDateFrom = null;
try
{
transDateFrom = (TransactionLog)session.get(TransactionLog.class,txn_date.trim());
}
catch(Exception exception)
{
exception.printStackTrace();
}
return transDateFrom;
}
public TransactionLog ToDateSel(String txn_date)
{
TransactionLog transDateTo = null;
try
{
transDateTo = (TransactionLog)session.get(TransactionLog.class,txn_date.trim());
}
catch(Exception exception)
{
exception.printStackTrace();
}
return transDateTo;
}
// Will returns all menu ids
/*public StringBuffer formatedMenuIds(String text)
{
String[] val = text.split(",");
StringBuffer sb = new StringBuffer();
for(String cc :val)
{
sb.append("'"+cc+"'"+",");
}
if(sb.toString().endsWith(","))
{
sb.delete(sb.length()-1, sb.length());
}
return sb;
}*/
public static SelectOperation getInstance()
{
return selectData;
}
}
I think i just need so more javascript to do this i just dont know how. Thanks for your help in advance.
<% #page import = "allDatabaseOperations.SelectOperation" %>
<% #page import = "java.util.List" %>
<% #page import = "entityBeans.TransactionLog" %>
<% #page import = "entityBeans.Business" %>
<% #page import = "entityBeans.CustomerBranch" %>
<% #page language = "java"
contentType = "text/html; charset=ISO-8859-1"
pageEncoding = "ISO-8859-1" %>
< !DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd" >
< html >
< head >
< link rel = "stylesheet"
href = "../styles/style.css"
type = "text/css" / >
<%
List < TransactionLog > Allbranches = SelectOperation.getInstance().getAllTransactionLog();
List < Business > Businesslevel = SelectOperation.getInstance().getAllBusiness();
List < CustomerBranch > CustBranch = SelectOperation.getInstance().getAllCustomerBranch(); %>
< link rel = "stylesheet"
href = "//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" >
< script src = "//code.jquery.com/jquery-1.10.2.js" > < /script>
<script src="/ / code.jquery.com / ui / 1.11.4 / jquery - ui.js "></script>
<link rel="
stylesheet " href=" / WebContent / styles / style.css ">
<script>
$(function() {
$( "#
fromdate " ).datepicker({
showOn: "
button ",
buttonImage: ".. / .. / images / calendar.png ",
buttonImageOnly: true,
buttonText: "
Select date "
});
});
$(function() {
$( "#
todate " ).datepicker({
showOn: "
button ",
buttonImage: ".. / .. / images / calendar.png ",
buttonImageOnly: true,
buttonText: "
Select date "
});
});
</script>
</head>
<body>
<form>
<table align="
center " style="
background - color: #F5D0A9;
padding: 70px;
border - top: 1px;
">
<tr>
<%-- added by Maihani on 181115(Wed) --%>
<td>
Business Id :-
</td>
<%--<td> <input type="
text " name="
BusinessId " size = "
46 "/> --%>
<td> <select name="
Business ">
<%for(Business business : Businesslevel) {%>
<option value=" <%= business.getBusinessId() %> "><%=business.getBusinessName()%></option>
<%}
%>
</select><%-- </td>--%>
</td>
</tr>
<td>
Branch Id :
</td>
<td>
<select name="
CustomerBranch ">
<%for(CustomerBranch custBranch : CustBranch) {%>
<option value=" <%= custBranch.getBranchId() %> "><%=custBranch.getBranchName()%></option>
<%}
%>
</select>
</td>
</tr>
<tr>
<td>
From Date :
</td>
<td>
<%-- <input type="
text " name="
BrachId " size = "
46 "/> --%>
<input type="
text " id="
fromdate ">
</td>
</tr>
<tr>
<td>
To Date :
</td>
<td>
<%--<input type="
text " name="
BrachId " size = "
46 "/> --%>
<input type="
text " id="
todate ">
</td>
</tr>
<tr>
<td>
</td>
<td align="
center "><input type="
submit " value="
Search Transaction "/></td>
</tr>
<tr >
<td colspan="
2 ">
<table align="
center ">
<tr bgcolor="
#333333">
<td><font color= "#FFFFFF" > User ID < /font></td >
< td > < font color = "#FFFFFF" > Branch ID < /font></td >
< td > < font color = "#FFFFFF" > Transaction Code < /font></td >
< td > < font color = "#FFFFFF" > Transaction Date < /font></td >
< td > < font color = "#FFFFFF" > Transaction Time < /font></td >
< /tr>
<%for(TransactionLog txn : Allbranches){%>
<tr bgcolor="#F2F2F2">
<td><%=txn.getUserId()%></td >
< td > <%= txn.getBranchId() %> < /td>
<td><%=txn.getTxnCode() %></td >
< td > <%= txn.getTxnDate() %> < /td>
<td><%=txn.getTxnTime() %></td >
< /tr>
<%} %>
</table >
< /td>
<td></td >
< /tr>
</table >
< /form>
</body >
< /html>

On the submit button, you can call a JavaScript function that in turn validates the values of your 4 input types and based on the validation result, you can continue with the form submit or show error message
<input type="submit" onclick="validateForm()" value="Search Transaction" />
<script>
function validateForm(){
var ip1 = $("#firstdropdownId").val();
var ip2 = $("#otherdropdownId").val();
var date1 = $("#firstdateId").val();
var date2 = $("#otherdateId").val();
if(ip1 == null || ip1.length.trim() == 0 || ip2 == null || ip2.length.trim() == 0 || idt1 == null || dt1.length.trim() == 0 || dt2 == null || dt2.length.trim() == 0){
$("#errorMessageDiv").show();
return false;
}
else{
$("#errorMessageDiv").hide();
return true;
}
}
</script>
Or if you want to validate from java end, you can make an ajax call by passing the parameters as the input values, which will return the validate status of your form.

Related

Update table with data after value selected from the dropdownlist (asp.net mvc)

I am just starting to work with asp.net mvc and I am trying to understand the logic between views and controllers.
I have the table with the data that I am getting from the db shown on my page and I am also have the dropdown on my page. I would like to update my table according to the value selected from the dropdown (for example if user selects T3) the data for T3 shows in the table.
I can't quite understand how I can pass the value selected from the dropdown and how to the controller and how to update my sql query with this new value. Is it suppose to be in the same index method or it should be the different one. I would appreciate any help and ideas. Thank you in advance.
Here is my model:
public class TestModel
{
public int id { get; set; }
public string name { get; set; }
public string serial{ get; set; }
public string pr { get; set; }
}
Here is my Controller: First sql string I am using to get data for the dropdown and the second one to get data for the table itself.
public class TestController : Controller
{
public List<TestModel> Test = new List<TestModel>();
public List<TableModel> Table = new List<TableModel>();
public IActionResult Index()
{
try
{
String connectionString = "bbbb";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
String sql2 = "SELECT * FROM db WHERE detail = 1";
using (SqlCommand command = new SqlCommand(sql2, connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
TestModel test= new TestModel();
test.id = Convert.ToInt32("" + reader[0]);
test.name = "" + reader[1];
test.serial = "" + reader[3];
test.pr = "" + reader[4];
Test.Add(test);
}
}
}
String sql = "SELECT * FROM bb1";
using (SqlCommand command1 = new SqlCommand(sql, connection)) {
using(SqlDataReader reader1 = command1.ExecuteReader())
{
while (reader1.Read())
{
TableModel tablemod = new TableModel();
tablemod.id = Convert.ToInt32("" + reader1[0]);
tablemod.tr = "" + reader1[2];
tablemod.pr = "" + reader1[4];
tablemod.req = "" + reader1[5];
tablemod.test = "" + reader1[6];
tablemod.method = "" + reader1[7];
tablemod.sport = "" + reader1[8];
tablemod.timer = "" + reader1[9];
tablemod.ra = "" + reader1[10];
tablemod.calib = "" + reader1[12];
Table.Add(tablemod);
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("exception:" + ex.ToString());
}
ViewData["dropdown"] = TestCell;
ViewData["table"] = Table;
return View();
}
}
And here is the view:
<!doctype html>
<html lang="eng">
<head>
some styles go there
</head>
<body>
<div class="table">
<div>
<select asp-for="#Model.id" asp-items="(#ViewData["dropdown"] as IEnumerable<SelectListItem>)" id="UserId" class="form-control " >
<span asp-validation-for="#Model.id"></span>
#foreach (var item in #ViewData["dropdown"] as IEnumerable<TestModel>)
{
<option class="others" value="#item.id&&#item.serial&&#item.pr">#item.fname</option>
}
</select>
</div>
<div><input id="serial" type="text"/></div>
<div><input id="pr" type="text"/></div>
</div>
</div>
<table class="table ">
<thead>
<th data-field="tr" data-sortable="true">TR</th>
<th data-field="pr" data-sortable="true">Priority</th>
<th data-field="req" data-sortable="true">Requestor</th>
<th data-field="test" data-sortable="true">Test Name</th>
<th data-field="method" data-sortable="true">Description</th>
<th data-field="sport" data-sortable="true">Failed Part</th>
<th data-field="timer" data-sortable="true">Emission</th>
<th data-field="ra" data-sortable="true">Rating</th>
<th data-field="calib" data-sortable="true">Calibration</th>
</thead>
<tbody>
#foreach (var item in #ViewData["table"] as IEnumerable<TableModel>)
{
<tr>
<td>#item.trnum</td>
<td>#item.priority</td>
<td>#item.requestor</td>
<td>#item.testname</td>
<td>#item.description</td>
<td>#item.failed</td>
<td>#item.emission</td>
<td>#item.rating</td>
<td>#item.calibration</td>
<td>#item.eas</td>
<td>#item.recorder</td>
</tr>
}
</tbody>
</table>
</div>
</body>
</html>
<script type="text/javascript">
var $table = $('#fresh-table')
var $alertBtn = $('#alertBtn')
$(function () {
$table.bootstrapTable({
classes: 'table table-hover table-striped',
toolbar: '.toolbar',
search: true,
showRefresh: true,
showToggle: true,
showColumns: true,
pagination: true,
height: $(window).height(),
striped: true,
sortable: true,
pageSize: 10,
pageList: [8, 10, 25, 50, 100],
formatShowingRows: function (pageFrom, pageTo, totalRows) {
return ''
},
formatRecordsPerPage: function (pageNumber) {
return pageNumber + ' rows visible'
}
})
$(window).resize(function () {
$table.bootstrapTable('resetView', {
height: $(window).height(),
})
})
})
$(function () {
$('#fresh-table').bootstrapTable()
})
$("#UserId").change(function () {
var selectedid = $("#UserId option:selected").val().split("&&");
var serialNumber = selectedid[1];
var projectNumber = selectedid[2];
$('#serialNumber').val(serialNumber);
$('#projectNumber').val(projectNumber);
});
</script>

Get checkbox values with different class name in the same div id - jquery mvc

I am trying to get the values of checkboxes which are in the same divid but have different class name.
<tr>
<td colspan="4" align="center">
<div id="divEntities" style="width:100%;height:150px;overflow-y:scroll;align:center;">
<table cellspacing="2" cellpadding="2" width="95%" align="center" border="1">
#{
var i = 0;
while (i < Model.CompanyMaster.Count)
{
<tr>
<td style="width:50%" hidden="hidden"><input type="checkbox" class="EntityCheck" id="chkCompanyId" /> #Model.CompanyMaster[i].COMPANYID</td>
#if ((i + 1) < Model.CompanyMaster.Count)
{
<td><input type="checkbox" class="EntityCheck" /> #Model.CompanyMaster[i + 1].COMPANY_NAME</td>
<td><input type="checkbox" class="CurrentYear" /> #DateTime.Now.Year </td>
<td><input type="checkbox" class="PreviousYear" /> #DateTime.Now.AddYears(-1).Year </td>
<td><input type="checkbox" class="LastYear" /> #DateTime.Now.AddYears(-2).Year </td>
}
else
{
<td></td>
}
</tr>
i = i + 1;
}
}
</table>
</div>
</td>
</tr>
With above code, I am able to populate data in a table with multiple checkboxes, but unable to get the value of the checkbox where the class name is something other than EntityCheck. Below is my jQuery function:
function GetSelectedEntities() {
var entities = "";
$("#divEntities").find('td').each(function (i, el) {
var checkbox = $(this).find('input.EntityCheck');
//var check1 = $(this).find('CurrentYear');
//var check2 = $(this).find('PreviousYear');
//var check3 = $(this).find('LastYear');
var check1 = $('.CurrentYear').val();
var check2 = $('.PreviousYear').val();
var check3 = $('.LastYear').val();
if (checkbox != undefined && $(checkbox).length > 0 && $(checkbox).prop('checked') == true) {
var EntityData = jQuery.trim($(this).text());
if (entities == "") {
entities = EntityData;
}
else {
entities = entities + "|" + EntityData;
}
}
});
return entities;
}
jQuery function is invoked on a button click event:
<button style="font:normal 9pt Arial;height:30px;width:100px;border-radius:5px; border:none; background-color:royalblue; color:white" id="btnAdd" onclick="GetSelectedEntities(event);">
Add
</button>
I tried by giving the same class name to all the checkboxes but the problem was that I was able to get the values of the year checkbox, even if the CompanyName was not selected. I need the year values only if the CompanyName checkbox is checked and it's corresponding years. I also tried by giving the id='' to the year checkbox, but could not get the values.
I am unable to figure where I am going wrong. What is that I need to change in my jQuery to get the expected result?
Something like this would work:
$('#btnAdd').on('click', function(){
var checked = $('table').find('input:checked');
checked.each(function(){
alert($(this).closest('td').text());
//do your stuff here..
});
});
Se working fiddle: https://jsfiddle.net/c8n4rLjy/
I had to make changes to get the desired solution. Please find the solution below:
<tr>
<td colspan="4" align="center">
<div id="divEntities" style="width:100%;height:150px;overflow-y:scroll;align:center;">
<table cellspacing="2" cellpadding="2" width="95%" align="center" border="1">
#{
var i = 0;
while (i < Model.CompanyMaster.Count)
{
<tr>
<td style="width:50%" hidden="hidden"><input type="checkbox" class="EntityCheck" id="chkCompanyId" /> #Model.CompanyMaster[i].COMPANYID</td>
#if ((i + 1) < Model.CompanyMaster.Count)
{
<td><input type="checkbox" class="EntityCheck" /> #Model.CompanyMaster[i + 1].COMPANY_NAME</td>
<td><input type="checkbox" class="chkYear" /> #DateTime.Now.Year </td>
<td><input type="checkbox" class="chkYear" /> #DateTime.Now.AddYears(-1).Year </td>
<td><input type="checkbox" class="chkYear" /> #DateTime.Now.AddYears(-2).Year </td>
}
else
{
<td></td>
}
</tr>
i = i + 1;
}
}
</table>
</div>
</td>
</tr>
jQuery:
function GetSelectedEntities() {
var entities = "";
var CompanySelected = false;
var counter = 0;
$("#divEntities").find('td').each(function (i, el) {
counter = counter + 1
var checkbox = $(this).find('input.EntityCheck');
var checkboxyear = $(this).find('input.chkYear');
if (counter == 2) {
if (checkbox != undefined) {
if ($(checkbox).prop('checked') == true) {
CompanySelected = true;
var EntityData = jQuery.trim($(this).text());
if (entities == "") {
entities = EntityData;
}
else {
entities = entities + "-" + EntityData;
}
}
else {
CompanySelected = false;
}
}
}
if (counter > 2) {
if (CompanySelected == true) {
if (checkboxyear != undefined) {
if ($(checkboxyear).prop('checked') == true) {
var EntityData = jQuery.trim($(this).text());
entities = entities + "|" + EntityData;
}
}
}
}
if(counter == 5)
{
counter = 0;
}
});
return entities;
}

Download file from JSP with Javascript

The context: I have a JSP presenting an HTML page. Here I can choose files from a table (populated via MySQL). clicking on a row: the file is loaded from the DB (via MySQL query), then built via stream, then it should be downloaded. I'm able to build a file from a stream, but I can't enable the correct procedure for download it. The software is running on local, so there's no a client/server architecture (I'm aware Javascript is problematicfor this) I read many questions here about using Javascript, href links, jquery, but nothing seems to work.
Can someone provide a "classic example" or proper implementation for this? Sorry if my description is a little vague, I'll provide further details if necessary. Have a look to my jsp (Please ignore the code parts not related). Note: Some errors are due to uncoplete deleting of my efforts
`<%# page import="org.jdom2.Element"%>
<%# page
import="org.yawlfoundation.yawl.resourcing.rsInterface.WorkQueueGatewayClient"%>
<%# page import="org.jdom2.output.XMLOutputter"%>
<%# page import="org.jdom2.output.Format"%>
<%# page import="org.jdom2.input.SAXBuilder"%>
<%# page import="java.io.StringReader"%>
<%# page import="java.io.*"%>
<%# page import="java.sql.Connection"%>
<%# page import="java.sql.DriverManager"%>
<%# page import="java.sql.PreparedStatement"%>
<%# page import="java.sql.ResultSet"%>
<%# page import="java.sql.SQLException"%>
<%# page import="java.sql.Statement"%>
<%# page import="java.util.ArrayList"%>
<%# page import="java.util.List"%>
<%# page import="java.util.Map"%>
<%# page import="org.jdom2.Element"%>
<%# page import="org.yawlfoundation.yawl.elements.data.YParameter"%>
<%# page import="java.sql.*"%>
<%# page import="java.util.Enumeration"%>
<%
String username = "";
String password = "password";
String columns = "columns";
String data1 = "<tr>";
String taskFlag = "void";
String clickedDOC = "";
String link = "";
String jDocTitle = "dummy jDocTitle";
String varName = "username";
String varName2 = "addDocument";
String varName3 = "addRequest";
String varName4 = "evaluateRequest";
String varName5 = "removeDocument";
String varName6 = "removeRequest";
String varName7 = "exit";
String wqURL = "http://localhost:8080/resourceService/workqueuegateway";
String error = "error";
boolean isModified = false;
boolean addDocument = false;
String redirectURL = (String) session.getAttribute("redirectURL");
if (redirectURL == null) {
redirectURL = request.getParameter("source");
session.setAttribute("redirectURL", redirectURL);
}
String submit = request.getParameter("submit");
System.out.println("submit: " + submit);
WorkQueueGatewayClient wqClient = new WorkQueueGatewayClient(wqURL);
String itemXML = (String) session.getAttribute("itemXML");
//if (itemXML == null) {
String itemid = request.getParameter("workitem");
String handle = request.getParameter("handle");
itemXML = wqClient.getWorkItem(itemid, handle);
session.setAttribute("itemXML", itemXML);
session.setAttribute("workitem", itemid);
session.setAttribute("handle", handle);
//}
if ((submit != null) && submit.equals("Add Document")) { // VALUTARE SE IL TASK TERMINA E VA RIAVVIATO (A TERMINE ADD) O SE RIMANE
ATTIVO (E DISPONIBILE DOPO ADD)
System.out.println("AddDocument clicked");
taskFlag = "addDocument";
addDocument = true;
isModified = true;
System.out.println("isModified: " + isModified);
/* session.removeAttribute("itemXML");
session.removeAttribute("workitem");
session.removeAttribute("handle");
session.removeAttribute("redirectURL"); */
redirectURL += "?complete=true";
response.sendRedirect(response.encodeURL(redirectURL));
return;
}
Element wir = new SAXBuilder().build(new StringReader(itemXML)).getRootElement();
Element updatedData = wir.getChild("updateddata");
Element data = (updatedData.getContentSize() > 0) ? updatedData : wir.getChild("data");
Element wirData = data.getChildren().get(0);
System.out.println("itemXML: " + itemXML);
if (!wqClient.successful(itemXML)) {
error = itemXML;
System.out.println("incipit error itemXML: " + itemXML);
} else { // wqClient.successful(itemXML)
if (wir != null) { //NIENTE DA INSERIRE NELL' IF
if (wirData != null) {
Element usernameXML = wirData.getChild(varName);
//Element taskFlagXML = wirData.getChild("taskFlag");
Element addDocumentXML = wirData.getChild("addDocument");
//addDocumentXML.removeContent();
// System.out.println("addDocumentXML: " + addDocumentXML.getText());
/*Element addRequestXML = null;
Element evaluateRequestXML = null;
Element removeDocumentXML = null;
Element removeRequestXML = null;
Element exitXML = null; */
if (usernameXML != null) {
username = usernameXML.getText();
//addDocument.removeContent();
//taskFlagXML.setText(taskFlag);
addDocumentXML.setText("true");
itemid = (String) session.getAttribute("workitem");
handle = (String) session.getAttribute("handle");
String dataString = new XMLOutputter(Format.getCompactFormat()).outputString(wirData);
String result = wqClient.updateWorkItemData(itemid, dataString, handle);
System.out.println("itemXML2: " + itemXML);
if (wqClient.successful(result) && isModified) { // QUI OPZIONE COMPLETAMENTO VALIDO
System.out.println("isModified 3: " + isModified);
/* session.removeAttribute("itemXML");
session.removeAttribute("workitem");
session.removeAttribute("handle");
session.removeAttribute("redirectURL"); */
redirectURL += "?complete=true";
response.sendRedirect(response.encodeURL(redirectURL));
} else { // wqClient.successful(result))
error = result;
System.out.println("not wqClient.successful(result): " + error);
}
} else { //dataitem != null && dataitem2 != null
error = "dataitems null";
System.out.println(error);
System.out.println("itemXML: " + itemXML);
System.out.println("inputs: " + username + " , " + password);
System.out.println("wirdata: " + wirData);
}
} else {//wirData
error = "This workitem does not contain any data for updating.";
System.out.println(error);
}
} else {
System.out.println("inputs null: ");
}
}
System.out.println("SQL start");
String queryAllDocuments = "SELECT title, file FROM appuser, document WHERE appuser.username = '" + username
+ "' AND appuser.role = document.applicantRole";
String queryAllRequests = "SELECT * FROM request WHERE request.applicantUsername = '" + username +"'";
String queryPendingRequests = "SELECT * FROM request WHERE request.applicantUsername = '" + username
+ "' AND request.status = 'pending' ";
String queryAllEvaluatingRequests = "SELECT * FROM request WHERE request.evaluetorUsername = '" + username+"'";
String queryEvaluatingPendingRequests = "SELECT * FROM request WHERE request.evaluetorUsername = '"
+ username + "' AND request.status = 'pending' ";
String queryGetDoc = "SELECT file FROM document WHERE document.title =";
Class.forName("com.mysql.jdbc.Driver");
Connection connection1 = DriverManager
.getConnection("jdbc:mysql://localhost:3306/mydb?autoReconnect=true&useSSL=false",
"root", "root");
Statement statement1 = connection1.createStatement();
ResultSet resultSet1;
resultSet1 = statement1.executeQuery(queryAllDocuments);
System.out.println("resultSet1: "+resultSet1.first());
ResultSet resultSet2;
Statement statement2 = connection1.createStatement();
ResultSetMetaData rsmd;
rsmd = resultSet1.getMetaData();
System.out.println("rsmd: "+rsmd.getColumnCount());
int columnCount = rsmd.getColumnCount();
int index = 1;
int titleIndex = 1; // unica colonna doc
boolean flag = false;
while(flag){
jDocTitle = String.valueOf(request.getAttribute("docTitle")); // click su docTitle
if(jDocTitle.equals(null) ){
System.out.println("jDocTitle: "+jDocTitle);
queryGetDoc+= "'"+jDocTitle+"'";
resultSet2 = statement2.executeQuery(queryGetDoc);
System.out.println("resultSet2: "+resultSet2.first());
if(resultSet2!=null || !resultSet2.first()){
//resultSet2.first();
//costruisci file da query
System.out.println("jDocTitle1: "+jDocTitle);
File file = new File(jDocTitle);
file.createNewFile();
FileOutputStream fop = new FileOutputStream(file);
InputStream is = resultSet2.getBinaryStream(1);
byte[] buffer = new byte[1024];
int len;
for (int i = is.read(); i != -1; i = is.read()) {
fop.write(i);
}
is.close();
fop.close();
}
}else{
jDocTitle = "dummy docTitle";
System.out.println("docTitle null");
}
flag = false;
}
// <html xmlns="http://www.w3.org/1999/xhtml">
%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<script type="text/javascript">
function downloadFunction(){
var doc = document.getElementById("availableDocument").value;
doc = window.location= file;
alert(doc);
var xhttp = new XMLHttpRequest();
if(!doc){
doc = "no doc clicked";
}else
{
document.getElementById(doc).innerHTML = this.responseText;
xhttp.send();
}
flag = true;
}
</script>
<form name="userDataForm" method="post" action="" >
<h1>Welcome User</h1>
<h3> </h3>
<h3> </h3>
<h3>Available Documents</h3>
<table id= "docTable" style="height: 21px; float: left;" width="380">
<tbody>
<tr>
<%
for (int i = 1; i < columnCount; i++) {
System.out.println(rsmd.getColumnName(i));
%><td><b>
<%=rsmd.getColumnName(i)%>
</b></td>
<% }%>
</tr>
<%
int i = 1;
resultSet1.first();
while (!resultSet1.isAfterLast()) {
for (; i != columnCount; i++) {
%>
<tr id="<%resultSet1.getString(i);%>">
<td>
<a id="availableDocument" href="#"; onclick=downloadFunction('<%=resultSet1.getString(i)%>')><%=resultSet1.getString(i)%></a>
</td>
<% }
if ( i % columnCount == 0)out.println("</tr><tr>");%>
<%resultSet1.next();}%>
</tr>
</tbody>
</table>
<p> </p>
<p> </p>
<h3> </h3>
<h3>Submitted Requests</h3>
<table style="height: 21px; float: left;" width="380">
<tbody>
<tr>
<td> </td>
<td style="width: 20px;"> </td>
</tr>
</tbody>
</table>
<p> </p>
<h3> </h3>
<h3> </h3>
<h3>Received Requests</h3>
<table style="height: 21px; float: left;" width="380">
<tbody>
<tr>
<td> </td>
<td style="width: 20px;"> </td>
</tr>
</tbody>
</table>
<input type="submit" name="submit" value="Add Document" /> <input
type="submit" name="submit" value="Add Request" />
</form>
</body>
</html>`

How can I call c# method from Jquery Ajax in WebForm?

I am new to the coding and i am trying to call my c# method through jquery ajax because my form action is not allowing my OnClick() event to run, I cannot remove form action because, my form comes from proprietary software and gives form action automatically every time, i tried to change it to default again but that doesn't work. So now I am trying to run my C# code through Jquery Ajax. If you have better way to solve it please suggest.
Your help is appreciated, Thank You in advance
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="HTMLtoPDF.aspx.cs"
Inherits="HTMLtoPDF.HTMLtoPDF" %>
<!DOCTYPE html>
<!--[if IE 9]><html class="lt-ie10" lang="en" > <![endif]-->
<html class="no-js" lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=9" />
<title>Incomplete Grade Application</title>
</head>
<body>
<form action="xyz.aspx" id="form1" runat="server" method="post" name="form1">
/// Web Form ///
<div class="row">
<div class="col-sm-12">
<label class="control-label" style="margin-top:0px;margin-left:20px">Please use your mouse/finger sign below:</label>
<div id="esignature"></div>
<input type="hidden" id="bitmap" name="bitmap" value="" />
</div>
</div>
<div class="row">
<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">
<button type="button" class="btn btn-danger btn-xs" id="clear">Clear Signature</button>
</div>
<div class="col-lg-2 col-lg-offset-6 col-md-2 col-md-offset-6 col-sm-2 col-sm-offset-6 col-xs-2 col-xs-offset-6">
<div class="pull-right">
<input type="submit" class="btn btn-danger" id="reject-button" name="button" value="Reject" />
</div>
</div>
<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">
<input type="button" ID="submit" class="btn btn-success" value="Approve" />
<button id="hiddenButton" runat="server" onserverclick="btnClick_Click" style="display:none;" ></button>
</div>
</div>
<hr style="background-color:#750D17;height:1px" />
<div class="row">
<div class="col-lg-12">
<input type="text1" class="form-control" id="reject-reason" name="reject-reason">
<p class="help-block">Reject Reasons (if rejected)</p>
</div>
</div>
</div>
</div>
<br />
<br />
</form>
<script src="https://code.jquery.com/jquery-2.1.4.min.js" type="text/javascript"></script>
<script src="https://code.jquery.com/jquery-2.1.4.min.js" type="text/javascript"></script>
<script src="https://code.jquery.com/jquery-migrate-1.3.0.js"></script>
<script src="https://workflow.stratford.edu/Content/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
<!--[if lt IE 9]>
<script src='https://workflow.stratford.edu/Content/jSignature/flashcanvas.js' type='text/javascript'></script>
<![endif]-->
<script src='https://workflow.stratford.edu/Content/jSignature/jSignature.min.js'></script>
<script type="text/javascript">
var isEmpty = function (element) {
if ($("#" + element).val() == "" || $("#" + element).val() == null) {
return true;
} else {
return false;
}
};
var arrayCheck = function (array) {
for (var i = 0; i < array.length; i++) {
if (array[i] == false) {
return false;
}
};
return true;
};
function arrayAssign(array, num) {
for (var i = 0; i < num; i++) {
array[i] = false;
};
return array;
};
function validationCheck(array, number, element) {
if (isEmpty(element)) {
$("#" + element).parent(".form-group").addClass("has-error");
array[number] = false;
} else {
$("#" + element).parent(".form-group").removeClass("has-error");
array[number] = true;
}
};
var pass1 = [];
$(document).ready(function () {
if ($.browser.msie) {
if (parseInt($.browser.version) < "9.0") {
alert("Sorry! This form does not support your current IE version, please use Firefox/Google Chrome to submit.");
}
}
var preSig = $('#stu-sig-bit').val();
$('#stu-sig').attr('src', preSig);
var fakeVari = $("#typea").val();
$("#esignature").jSignature({
"background-color": "transparent",
"decor-color": "transparent",
"color": "#1489FF",
});
$("#clear").click(function () {
$("#esignature").jSignature("reset");
});
$("input[type=text]").attr("readonly", true);
$("textarea1").attr("readonly", true);
//$("input[type=radio]").attr("disabled", "disabled");
$("#reject-reason").attr("readonly", false);
$("#submit").click(function () {
$("#bitmap").val($("#esignature").jSignature("getData"));
arrayAssign(pass1, 2);
pass1[2] = false;
validationCheck(pass1, 0, "remaining_work");
validationCheck(pass1, 1, "deadline_date");
pass1[2] = true;
if (!arrayCheck(pass1)) {
return false;
}
else if ($("#esignature").jSignature("getData", "native").length == 0) {
alert("Please sign at bottom of the form.");
return false;
} else {
$("#iso_sig").val($("#bitmap").val());
$("#iso_decision").val("no");
var date = new Date();
var month = date.getMonth() + 1;
var day = date.getDate();
var temp = (month < 10 ? "0" : "") + month + "/" + (day < 10 ? "0" : "") + day + "/" + date.getFullYear();
$("#iso_date").val(temp);
var answer = confirm('Are you sure you want to approve the case?');
if (answer == true) {
document.getElementById('<%= hiddenButton.ClientID %>').click();
} else {
return false;
}
}
});
$("#reject-button").click(function () {
$("#bitmap").val($("#esignature").jSignature("getData"));
if (isEmpty("reject-reason")) {
alert("Please write down the reason why you reject the request.");
return false;
} else if ($("#esignature").jSignature("getData", "native").length == 0) {
alert("Please sign at bottom of the form.");
return false;
} else {
$("#iso_sig").val($("#bitmap").val());
$("#iso_decision").val("no");
var date = new Date();
var month = date.getMonth() + 1;
var day = date.getDate();
var temp = (month < 10 ? "0" : "") + month + "/" + (day < 10 ? "0" : "") + day + "/" + date.getFullYear();
$("#iso_date").val(temp);
var answer = confirm('Are you sure you want to reject the case?');
if (answer == true) {
} else {
return false;
}
}
});
});
</script>
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnClick_Click(object sender, EventArgs e)
{
DownloadAsPDF();
}
public void DownloadAsPDF()
{
try
{
string strHtml = string.Empty;
string pdfFileName = Request.PhysicalApplicationPath + "\\files\\" + "CASEID6.pdf";
//string testPath = Server.MapPath("~/files/test.pdf");
string template = File.ReadAllText(Server.MapPath("~/Incomplete-Pdf-temp.html"));
CreatePDFFromHTMLFile(template, pdfFileName);
Response.Redirect("SendEmail.aspx");
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
public void CreatePDFFromHTMLFile(string HtmlStream, string FileName)
{
try
{
object TargetFile = FileName;
string ModifiedFileName = string.Empty;
string FinalFileName = string.Empty;
GeneratePDF.HtmlToPdfBuilder builder = new GeneratePDF.HtmlToPdfBuilder(iTextSharp.text.PageSize.A4);
GeneratePDF.HtmlPdfPage first = builder.AddPage();
first.AppendHtml(HtmlStream);
byte[] file = builder.RenderPdf();
File.WriteAllBytes(TargetFile.ToString(), file);
iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(TargetFile.ToString());
ModifiedFileName = TargetFile.ToString();
ModifiedFileName = ModifiedFileName.Insert(ModifiedFileName.Length - 4, "1");
iTextSharp.text.pdf.PdfEncryptor.Encrypt(reader, new FileStream(ModifiedFileName, FileMode.Append), iTextSharp.text.pdf.PdfWriter.STRENGTH128BITS, "", "", iTextSharp.text.pdf.PdfWriter.AllowPrinting);
reader.Close();
if (File.Exists(TargetFile.ToString()))
File.Delete(TargetFile.ToString());
FinalFileName = ModifiedFileName.Remove(ModifiedFileName.Length - 5, 1);
File.Copy(ModifiedFileName, FinalFileName);
if (File.Exists(ModifiedFileName))
File.Delete(ModifiedFileName);
}
catch (Exception ex)
{
throw ex;
}
}
}
}
You would implement a web-service, or you would utilize a handler file. This generic handler is often used, since it doesn't require a form. Once you utilize the template you'll have a file that should appear as follows:
public class SampleHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
}
public bool IsReusable
{
get { return false; }
}
}
From your primary application, or form, you would execute your ajax as follows:
<script type="text/javascript">
$.ajax({
url: '<% Page.ResolveUrl("/SampleHandler.ashx") %>',
method: 'post',
...,
success : function (response) {
// Handle .ashx response.
}
});
</script>
That is one of the simplest approaches. As it will allow you to separate your logic, compared to the declaration of a method in your code behind decorated in a [WebMethod] attribute.

Javascript Dynamic Table

I'm having trouble the following table should read r1 c1, r1 c2, r2 c1, r2 c2 and so on in each box within the table and user should only be able to pick up to 12 rows and 12 columns anything over that should display an error message. Here is my code so far.
<!DOCTYPE html>
<!-- written by Angela Bauer on 1/23/2013-->
<!-- saved from url=(0014)about:internet -->
<html>
<head>
<meta charset = "utf-8">
<title> Dynamic Table </title>
<script type = "text/javascript">
var width = 500;
var height = 500;
function CreateTable(txtRows, txtCols, hold)
{
if(validNumber(txtRows) && validNumber(txtCols)
&& (hold != null) && (hold.canHaveChildren))
{
hold.innerHTML = "";
var table = document.createElement("table");
table.border = 3;
table.borderColor = "Blue";
table.height = height;
table.width = width;
var row = null;
var cell = null;
hold.appendChild(table);
for(i=0; i<txtRows; i++)
{
row = appendR(table)
for(j=0; j<txtCols; j++)
{
cell = appendC(row);
cell.innerText = j;
cell = null;
}
row = null;
}
}
}
function appendR(table)
{
if(table != null)
{
return table.insertRow();
}
else
{
alert("Error while creating table. Cause: Container Table is null!");
}
}
function appendC(aRow)
{
if(aRow != null)
{
return aRow.insertCell();
}
else
{
alert("Error while creating table. Cause: Container row is null!");
}
}
function validNumber(ipNum)
{
if(isNaN(ipNum))
{
alert("Invalid Number!");
return false;
}
else if(ipNum <= 1)
{
alert("You can only enter a number from 1 - 12!");
return false;
}
else
{
return true;
}
}
</script>
</head>
<body>
<table>
<tr>
<td> How many Rows would you like: </td>
<td><input type=text name=txtRows value=1 /></td>
</tr>
<tr>
<td> How many Columns would you like: </td>
<td><input type=text name=txtCols value=1 /> </td>
</tr>
<tr>
<td colspan=10 align=right><input type=button name=cmdCreate value="Create Table"
onClick="CreateTable(txtRows.value, txtCols.value, divHolder)" /></td>
</tr>
</table>
<div id=divHolder></div>
</body>
</html>
As gdoron put you need to ask a question but im taking a punt and guess you want you code fixed.
Below is a working copy of you code. There was a ton of stuff wrong including
No ID's on the input boxes
No " used for the value of items within the HTML form
.insertRow was missing a parameter
.insertCell was missing a parameter
The validNumber function was producing an error if you entered the
number 1.
canHaveChildren is only valid in IE i have removed it but if your
script is going to be used in IE only then add it back
Things to be avoid for best practice:
using the words table, row etc as var names.
I guessing your new at this so my advice is to install Firefox and the firebug add on as it would have told you half the errors you were getting.
Also if its not doing what you want add alerts to sections of the code and work out where it is getting to or not getting to.
Hopefully this will get you on track.
<html>
<head>
<meta charset = "utf-8">
<title> Dynamic Table </title>
<script type = "text/javascript">
var width = 500;
var height = 500;
function createTable(txtRows, txtCols, hold) {
// alert (txtRows+", "+txtCols+", "+hold);
// alert (hold.canHaveChildren);
// Removed as its an IE only javascript ---- && (hold.canHaveChildren)
if(validNumber(txtRows) && validNumber(txtCols) && (hold != null) ) {
// alert ("is valid");
hold.innerHTML = "";
var table1 = document.createElement("table");
table1.border = 3;
table1.borderColor = "Blue";
table1.height = height;
table1.width = width;
var row1 = null;
var cell1 = null;
hold.appendChild(table1);
for(i=0; i<txtRows; i++) {
// alert ("first for");
row1 = appendR(table1, i);
for(j=0; j<txtCols; j++) {
// alert ("second for");
cell1 = appendC(row1, j);
cell1.innerText = j;
cell1 = null;
}
row1 = null;
}
}
}
function appendR(table1, i) {
if(table1 != null) {
return table1.insertRow(i);
} else {
alert("Error while creating table. Cause: Container Table is null!");
}
}
function appendC(aRow, j) {
if(aRow != null) {
return aRow.insertCell(j);
} else {
alert("Error while creating table. Cause: Container row is null!");
}
}
function validNumber(ipNum) {
if(isNaN(ipNum)) {
alert("Invalid Number!");
return false;
} else if(ipNum > 12) {
alert("You can only enter a number from 1 - 12!");
return false;
} else if(ipNum < 1) {
alert("You can only enter a number from 1 - 12!");
return false;
} else {
return true;
}
}
</script>
</head>
<body>
<table>
<tr>
<td> How many Rows would you like: </td>
<td><input id="txtRows" type="text" name="txtRows" value="1" /></td>
</tr>
<tr>
<td> How many Columns would you like: </td>
<td><input id="txtCols" type="text" name="txtCols" value="1" /> </td>
</tr>
<tr>
<td colspan=10 align=right><input type=button name=cmdCreate value="Create Table"
onClick="createTable(txtRows.value, txtCols.value, divHolder)" /></td>
</tr>
</table>
<div id="divHolder"></div>
</body>

Categories

Resources