Jquery executes Error section by default - Servlet - javascript

I am new to Ajax and JQuery. I am attempting to insert data into my database without submitting the form. The data gets inserted into the table but:
I am not able to get either the Error Message or Success Message on My jsp. It Comes as [object Object]
Looks like the success section of the Jquery is not executed at all
My Jquery:
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function () {
//On Button Click
$("#countrybutton").click(function () {
//Get Text box values
var country = $("#country").val();
var continent = $("#continent").val();
var region = $("#region").val();
var population = $("#population").val();
var capital = $("#capital").val();
$.ajax({
url: 'do?MOD=BOK&ACT=domcountry&country=' + country + "&continent=" + continent + "&region=" + region + "&population=" + population + "&capital=" + capital,
dataType: "json",
type: "Post",
success: function (result) {
$("#message").text(result);
//Clear Textbox data
$("#country").val('');
$("#continent").val('');
$("#region").val('');
$("#population").val('');
$("#capital").val('');
},
error: function (responseText) {
$("#message").text(responseText);
}
});
});
});
</script>
My JSP
<table width="100%" border="0" align="left" cellpadding="5" cellspacing="1">
<th colspan="5" align="left" scope="col"></th>
<tr>
<td colspan="2" id="message" style="color: red; font-size: 14px;"></td>
</tr>
<tr>
<td> </td>
<td>Country Name</td>
<td style="color: red">*</td>
<td><label>
<input name="country" value="${country}" onkeyup="this.value = this.value.toUpperCase();" type="text" id="country"/>
</label></td>
<td> </td>
<td>Continent Name</td>
<td style="color: red">*</td>
<td><label>
<input name="continent" value="${continent}" onkeyup="this.value = this.value.toUpperCase();" type="text" id="continent"/>
</label></td>
</tr>
<tr>
<td> </td>
<td>Region</td>
<td style="color: red">*</td>
<td><label>
<input name="region" value="${region}" onkeyup="this.value = this.value.toUpperCase();" type="text" id="region"/>
</label></td>
<td> </td>
<td>Population</td>
<td style="color: red">*</td>
<td><label>
<input name="population" value="${population}" type="text" id="population"/>
</label></td>
<td></td>
</tr>
<tr>
<td> </td>
<td>Capital</td>
<td style="color: red">*</td>
<td><label>
<input name="capital" value="${capital}" type="text" id="capital"/>
</label></td>
<td> </td>
</tr>
</table>
</div>
<div>
<table width="100%" border="0" align="left" cellpadding="5" cellspacing="1">
<th colspan="5" align="left" scope="col"></th>
<tr>
<td> </td>
<td><div align="right">
<input type="reset" name="Submit2" value="Reset" class="redButton" />
</div></td>
<td><label>
<input name="Submit" class="redButton" type="button" id="countrybutton" onclick="MM_validateForm('country', '', 'R', 'continent', '', 'R', 'region', '', 'R', 'population', '', 'R',
'capital', '', 'R');
return document.MM_returnValue" value="Submit" />
<td> </td>
</tr>
</table>
And My servlet section:
response.setContentType("application/json");
String country = request.getParameter("country");
String continent = request.getParameter("continent");
String region = request.getParameter("region");
int population = Integer.parseInt(request.getParameter("population"));
String capital = request.getParameter("capital");
String returnMessage;
if (Countries.addCountry(country, continent, region, population, capital)) {
returnMessage = "Record Inserted.";
} else {
returnMessage = "Unable to Insert Record.";
try {
throw new InsertException("Unable to Insert record");
} catch (InsertException ex) {
log.debug(ex.getMessage());
}
}
new Gson().toJson(returnMessage, response.getWriter());
response.sendRedirect("index.jsp");
What am I missing?

Try remove this line:
response.sendRedirect("index.jsp");
and to get exception in Ajax error, you will need set http code 500 in response, add this inside your "else":
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
Servlet final:
response.setContentType("application/json");
String country = request.getParameter("country");
String continent = request.getParameter("continent");
String region = request.getParameter("region");
int population = Integer.parseInt(request.getParameter("population"));
String capital = request.getParameter("capital");
String returnMessage;
if (Countries.addCountry(country, continent, region, population, capital)) {
returnMessage = "Record Inserted.";
} else {
returnMessage = "Unable to Insert Record.";
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
try {
throw new InsertException("Unable to Insert record");
} catch (InsertException ex) {
log.debug(ex.getMessage());
}
}
new Gson().toJson(returnMessage, response.getWriter());

Related

Handling multiple forms in a single page [AngularJS]

So I have this page where a user should be able to log details for multiple projects he had applied to . Each project has multiple milestones and each milestone has a form where the user is able to log in the details . I designed the page and all but the problem is when the user updates one form , it reflects on all the forms present in the page.
This is my html where i display the form to the user.
<form>
<table>
<thead>
<tr>
<th>Date</th>
<th>Task Name</th>
<th>Hours</th>
</tr>
</thead>
<p> {{project.id}}--{{milestone.id}} </p>
<tbody ng-repeat="taskDetail in ::taskDetails">
<tr>
<td style="width:25px;">
<input type="text" ng-model="taskDetail.date" required/>
</td>
<td>
<input type="text" ng-model="taskDetail.taskname" required/>
</td>
<td>
<input type="text" ng-model="taskDetail.hours" required/>
</td>
<td>
<input type="hidden" ng-model="taskDetail.milestone_id" value="{{ ::milestone.id }}" required/>
</td>
<td>
<button class="remove" ng-show="$last" ng-click="removeLast()">Remove</button>
</td>
</tr>
</tbody>
<tr>
<td></td>
<td>
<button ng-click="addRow()">Add Row</button>
</td>
<td>
<button ng-click="savetask()"> Save </button>
</td>
</tr>
</table>
and the corresponding action is done in the controller by
$scope.taskDetails = [{
'date': '',
'taskname': '',
'hours': '',
'milestone_id': ''
}];
$scope.addRow = function (taskDetail) {
$scope.taskDetails.push({
'date': "",
'taskname': "",
'hours': "",
'milestone_id': ""
});
};
$scope.removeLast = function () {
var lastItem = $scope.taskDetails.length - 1;
$scope.taskDetails.splice(lastItem);
};
$scope.savetask = function (id) {
console.log("Details= " + id);
myFrm = document.getElementById(frmId);
$http.put('/api/v1/projects/'+ :project_id '/milestones/' +:milestone_id' /timetracker', { timetracker: $scope.taskDetails
})
.then(function(data) {
console.log($scope.taskDetails)
flash.setMessage('Successfully logged your time', true);
}, function(data) {
flash.setMessage('Error updating bank account', false);
})
};
});
Milestone ID is unique for each form.

Angular JS Filed to Get Input text value and Does not Post to Wcf Service

I am trying to catch input text value into Angular JS Application. I am using javaScript to display the current date and time into text filed and text box is able to get the current get and time. I am trying to post the input values to wcfr service when I click the submit button but the problem is it's unable to post the date and time to wcf service. I checked in Google Chrome in console Window and it is not posting current date and time...
Here is My HTML Code:
#{
Layout = null;
}
<!DOCTYPE html>
<html ng-app="WebClientModule">
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/Scripts/angular.min.js"></script>
<script src="~/RegistrationScript/CreateCurrentAccount.js"></script>
<script>
function myFunction() {
document.getElementById('account_creation_date').placeholder= Date();
}
</script>
</head>
<body onload="myFunction()">
<table id="tblContainer" data-ng-controller="Web_Client_Controller">
<tr>
<td></td>
</tr>
<tr>
<td>
<table style="border: solid 4px Red; padding: 2px;">
<tr>
<td></td>
<td>
<span>Account Creation Date</span>
</td>
<td>
<input type="text" id="account_creation_date" placeholder=" " data-ng-model="Account_Creation_Date" required="" />
</td>
</tr>
<tr>
<td></td>
<td>
<span>Account Type</span>
</td>
<td>
<input type="text" id="account_type" required data-ng-model="Account_Type" require="" />
</td>
</tr>
<tr>
<td></td>
<td>
<span>Branch Sort Code</span>
</td>
<td>
<input type="text" id="branch_sort_code" data-ng-model="Branch_Sort_Code" required="" />
</td>
</tr>
<tr>
<td></td>
<td>
<span>Account Fee</span>
</td>
<td>
<input type="text" id="account_fee" required data-ng-model="Account_Fee" require="" />
</td>
</tr>
<tr>
<td></td>
<td>
<span>Account Balance</span>
</td>
<td>
<input type="text" id="account_balance" data-ng-model="Account_Balance" required="" />
</td>
</tr>
<tr>
<td></td>
<td>
<span> Over Draft Limit</span>
</td>
<td>
<input type="text" id="over_draft_limit" required data-ng-model="Over_Draft_Limit" require="" />
</td>
</tr>
<tr>
<td></td>
<td>
<span> Account Holder Id</span>
</td>
<td>
<input type="text" id="account_holder_id" required data-ng-model="Account_Holder_Id" require="" />
</td>
</tr>
<tr>
<td></td>
<td></td>
<td>
<input type="button" id="Login" value="Login" data-ng-click="login()" />
</td>
</tr>
</table>
<div style="color: red;">{{msg}}</div>
</td>
</tr>
</table>
</body>
</html>
<script src="~/RegistrationScript/CreateCurrentAccount.js"></script>
Here is Script file code.
///// <reference path="../angular.min.js" />
var app = angular.module("WebClientModule", [])
.controller('Web_Client_Controller', ["$scope", 'myService', function ($scope, myService) {
$scope.OperType = 1;
//1 Mean New Entry
//To Clear all input controls.
function ClearModels() {
$scope.OperType = 1;
$scope.Account_Creation_Date = "";
$scope.Account_Type = "";
$scope.Branch_Sort_Code = "";
$scope.Account_Fee = "";
$scope.Account_Balance = "";
$scope.Over_Draft_Limit = "";
$scope.Account_Holder_Id = "";
}
$scope.login = function () {
var User = {
Account_Creation_Date: $scope.Account_Creation_Date,
Account_Type: $scope.Account_Type,
Branch_Sort_Code: $scope.Branch_Sort_Code,
Account_Fee: $scope.Account_Fee,
Account_Balance: $scope.Account_Balance,
Over_Draft_Limit: $scope.Over_Draft_Limit,
Account_Holder_Id: $scope.Account_Holder_Id
};
myService.AuthenticateUser(User).then(function (pl) {
console.log(pl.data)
if (pl.data) {
$scope.msg = "Account Created Successfully";
window.location.href = "/Register/Index";
}
else {
$scope.msg = "Account is not Created !";
console.log("Some error Occured" + err);
}
}, function (err) {
$scope.msg = "Account is not Created !";
console.log("Some error Occured" + err);
});
};
}]);
app.service("myService", function ($http) {
this.AuthenticateUser = function (User) {
return $http.post("http://localhost:52098/HalifaxIISService.svc/CreateCurrentAccountDetail", JSON.stringify(User));
}
})
Here is the vlaues are catched in Network Tab..
{"Account_Type":"Business","Branch_Sort_Code":"11-00-11","Account_Fee":"12.0","Account_Balance":"12300","Over_Draft_Limit":"123000","Account_Holder_Id":"2"}
Here is the Screen Shot When I run the Application..

object HTMLInputElement JavaScript error

So basically, I'm doing a webpage to calculate my school marks but I can't get it to print the result at the input value... Instead, it prints [object HTMLInputElement]
Here's my JavaScript code:
<script type="text/javascript"> </script>
<script>
window.onload = function () {
var quran = document.getElementById('quran').value;
var islamic = document.getElementById('islamic').value;
var arabic = document.getElementById('arabic').value;
var english = document.getElementById('english').value;
var games = document.getElementById('games').value;
var pc = document.getElementById('pc').value;
var maths = document.getElementById('maths').value;
var chem = document.getElementById('chem').value;
var phys = document.getElementById('phys').value;
var bio = document.getElementById('bio').value;
var social = document.getElementById('social').value;
var result = Number(quran) + Number(islamic) + Number(arabic) + Number(english) + Number(games) + Number(pc) + Number(maths) + Number(chem) + Number(phys) + Number(bio) + Number(social);
}
function resultFunc() {
document.getElementById('result').value = result;
}
</script>
And here's the table with the inputs:
<table class="rwd-table">
<tr>
<th>المادة الدراسية</th>
<th>الدرجة العظمى</th>
<th>درجة الطالب</th>
</tr>
<tr>
<td data-th="Movie Title">القرآن الكريم</td>
<td data-th="Genre">20</td>
<td data-th="Year"> <input value="" id="quran" style="width: 70px;" type="text"/> </td>
</tr>
<tr>
<td data-th="Movie Title">التربية الإسلامية</td>
<td data-th="Genre">40</td>
<td data-th="Year"> <input value="" id="islamic" style="width: 70px;" type="text"/> </td>
</tr>
<tr>
<td data-th="Movie Title">اللغة العربية</td>
<td data-th="Genre">60</td>
<td data-th="Year"> <input value="" id="arabic" style="width: 70px;" type="text"/> </td>
</tr>
<tr>
<td data-th="Movie Title">اللغة الإنجليزية</td>
<td data-th="Genre">60</td>
<td data-th="Year"> <input value="" id="english" style="width: 70px;" type="text"/> </td>
</tr>
<tr>
<td data-th="Movie Title">البدنية</td>
<td data-th="Genre">20</td>
<td data-th="Year"> <input value="" id="games" style="width: 70px;" type="text"/> </td>
</tr>
<tr>
<td data-th="Movie Title">الحاسوب</td>
<td data-th="Genre">20</td>
<td data-th="Year"> <input value="" id="pc" style="width: 70px;" type="text"/> </td>
</tr>
<tr>
<td data-th="Movie Title">الرياضيات</td>
<td data-th="Genre">80</td>
<td data-th="Year"> <input value="" id="maths" style="width: 70px;" type="text"/> </td>
</tr>
<tr>
<td data-th="Movie Title">الكيمياء</td>
<td data-th="Genre">60</td>
<td data-th="Year"> <input value="" id="chem" style="width: 70px;" type="text"/> </td>
</tr>
<tr>
<td data-th="Movie Title">الفيزياء</td>
<td data-th="Genre">60</td>
<td data-th="Year"> <input value="" id="phys" style="width: 70px;" type="text"/> </td>
</tr>
<tr>
<td data-th="Movie Title">الأحياء</td>
<td data-th="Genre">40</td>
<td data-th="Year"> <input value="" id="bio" style="width: 70px;" type="text"/> </td>
</tr>
<tr>
<td data-th="Movie Title">الإجتماعيات</td>
<td data-th="Genre">40</td>
<td data-th="Year"> <input value="" id="social" style="width: 70px;" type="text"/> </td>
</tr>
<tr>
<th>المجموع</th>
<th>500</th>
<th> <input style="width: 70px; background-color: gray;" id="result" value="" readonly /> </th>
</tr>
<tr>
<th style="font-size: 20px;">النسبة</th>
<th></th>
<th> <input style="width: 70px; background-color: gray;" value="" readonly /> </th>
</tr>
<tr>
<th></th>
<th> <input onClick="resultFunc()" type="submit" id="submit" value="اضغط هنا لحساب النسبة المئوية" /> </th>
<th></th>
</tr>
</table>
Sorry for the Arabic words, just look at the code :)
I've even tried to print the result in a cell instead of an input tag, but it gave me a similar error instead of printing the result...
The issue appears to be due to the calculation occurring during the window.onload event. In order to calculate the values you should be able to move the code from the onload event to the resultFunc function and it will allow you to calculate the total when you click the button.
function resultFunc() {
var quran = document.getElementById('quran').value;
var islamic = document.getElementById('islamic').value;
var arabic = document.getElementById('arabic').value;
var english = document.getElementById('english').value;
var games = document.getElementById('games').value;
var pc = document.getElementById('pc').value;
var maths = document.getElementById('maths').value;
var chem = document.getElementById('chem').value;
var phys = document.getElementById('phys').value;
var bio = document.getElementById('bio').value;
var social = document.getElementById('social').value;
var result = Number(quran) + Number(islamic) + Number(arabic) + Number(english) + Number(games) + Number(pc) + Number(maths) + Number(chem) + Number(phys) + Number(bio) + Number(social);
document.getElementById('result').value = result;
}
Also note the reason why you get [object HTMLInputElement] is due to the scoping of the variable result. Since you declare var result in resultFunc the value is immediately lost. [object HTMLInputElement] is rendered, because window.result is also a shortcut to the element in the HTML document with the id of result.

How to send data of array from java to jsp and set the data to variable in jsp?

This is JAVA
public class Dest_id extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
String destination = request.getParameter("destination");
String product = request.getParameter("product");
String currency = request.getParameter("currency");
String destQuery = "DESTINATION LIKE '" + destination + "%'";
String prodQuery = "PRODUCT = '" + product + "'";
String currQuery = "MOST_INFL_CURRENCY = '" + currency + "'";
if (destination != null)
destination = destination.toUpperCase();
ResultSet rs;
int bil = 1;
String destID[] = null;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bababa","root","");
Statement stmt = con.createStatement();
rs = stmt.executeQuery("select * from icx_pricing_desk where " + destQuery.toUpperCase() + " AND " + currQuery + " AND " + prodQuery);
while (rs.next()) {
System.out.println(bil + "|" + rs.getString("DESTINATION") + "|" + rs.getString("PRODUCT") + "|" + rs.getString("MOST_INFL_CURRENCY"));
destID[bil] = rs.getString("DEST_ID");
bil++;
}
con.close();
} catch(Exception e) { System.out.println(e); }
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println(destID);
}
}
This is my JSP page
<body>
<h1>Pricing Index</h1>
<br>
<div id="main_search">
<form name="m_search" method="GET" action="../../Dest_id" id="m_search">
<table class="searchTable" cellpadding="10" cellspacing="2" border="0" width="100%">
<tr>
<td rowspan="3" valign="top">Product</td><td rowspan="3" valign="top">:</td>
<td rowspan="3" valign="top">
<input type="checkbox" name="product" class="prod_checkbx" value="Bilateral-VC">Bilateral-VC<br>
<input type="checkbox" name="product" class="prod_checkbx" value="Bilateral Non-VC">Bilateral Non-VC<br>
<input type="checkbox" name="product" class="prod_checkbx" value="Budget Domestic">Budget Domestic<br>
<input type="checkbox" name="product" class="prod_checkbx" value="Budget High">Budget High<br>
<input type="checkbox" name="product" class="prod_checkbx" value="Budget International">Budget International<br>
</td>
</tr>
<tr>
<td valign="top">Destination</td>
<td valign="top">:</td>
<td valign="top"><input id="destination" type="text" style="text-transform: uppercase;" name="destination"/></td>
</tr>
<tr>
<td valign="top">Currency</td>
<td valign="top">:</td>
<td valign="top">
<select id="currency" name="currency">
<option value="RM">RM</option>
<option value="SDR">SDR</option>
<option value="USD">USD</option>
</select>
</td>
</tr>
<tr>
<td colspan="9" align="center">
<input type="submit" value="SeArCh" id="search" name="search" class="button orange small" style="cursor:pointer;"/>
</td>
<td>lol</td>
</tr>
</table>
</form>
</div>
<script type="text/javascript">
var form = $('#m_search');
form.submit(function () {
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
success: function (data) {
var result=data;
//$('#result').attr("value",result);
$('#result').html(result);
}
});
return false;
});
</script>
<div id="search_crit">
<table class="searchTable" cellpadding="10" cellspacing="2" border="0" width="100%">
<tr><td></td></tr>
</table>
</div>
<div id="search_result" style="overflow: auto;">
<h2>Floor Price Edit</h2>
<div id="result"></div>
<br />
So I want to know how to assign the data from java to JSP page. The data from java is a primary key which is I want to use it to display details based on the PK in JSP page. Such as:
<sql:query var="dest_result" dataSource="${db}">SELECT * from table WHERE DEST_ID = '<div id="result"></div>'</sql:query>
<c:forEach var="row" items="${dest_result.rows}">
<tr bgcolor="#DEB887">
<td><c:out value="${row.DEST_ID}"/></td>
<td><c:out value="${row.DESTINATION}"/></td>
<td><c:out value="${row.PRODUCT}"/></td>
<td><c:out value="${row.MOST_INFL_CURRENCY}"/></td>
</tr>
</c:forEach>
Well... mostly like this. But if you have better idea please help.

Need to load dialog popup with Database value

I need to open a jquery dialog popup with data loaded from database. I am able to see the result data in controller but not able view the same in dialog popup.
Any help on this pls?
Here is my code:
popup.jsp
<div id="addDeployment" style="display: none">
<table id="addDep">
<tbody>
<tr>
<td width="50%"><label id="AddDeployedCityLab">Deployed City</label></td>
<td width="50%"><input type="text" name="AddDeployedCity" id="AddDeployedCity" value="" /></td>
</tr>
<tr>
<td width="50%"><label id="AddDeployedStateLab">Deployed State</label></td>
<td width="50%"><input type="text" name="AddDeployedState" id="AddDeployedState" value=""></td>
</tr>
<tr>
<td width="50%"><label id="AddDeployedTerrirotyLab">Territory Name</label></td>
<td width="50%"><input type="text" name="AddDeployedTerriroty" id="AddDeployedTerriroty" value=${territoryName}></td>
</tr>
<tr>
<td width="50%"><label id="AddDeployedEffDateLab">Effective Date</label></td>
<td width="50%"><input type="text" name="AddDeployedEffDate" id="AddDeployedEffDate" value=${effectiveDate}></td>
</tr>
<tr>
<td width="50%"><label id="AddDeployedExpDateLab">Expiry Date</label></td>
<td width="50%"><input type="text" name="AddDeployedExpDate" id="AddDeployedExpDate" value=${expiryDate}></td>
</tr>
<tr>
<td width="50%"><label id="AddDeployedZipLab">Zipcodes</label></td>
<td width="50%">
<select id="AddDeployedZip" multiple="multiple">
</select>
</td>
</tr>
</tbody>
</table>
</div>
jQuery Code:
$("#addDeploymentBut").click(function(){
var usw=$("#DeployGrid").jqGrid("getCell",deployVal,"usw");
var deploymentTyp=$("#DeployGrid").jqGrid("getCell",deployVal,"deploymentTyp");
var territory=$("#DeployGrid").jqGrid("getCell",deployVal,"territoryName");
var effDate=$("#DeployGrid").jqGrid("getCell",deployVal,"effectiveDate");
var expDate=$("#DeployGrid").jqGrid("getCell",deployVal,"expiryDate");
var passParam="/Scheduling/deploymentAddModal?deployType="+deploymentTyp+"&usw="+usw+"&territory="+territory+"&effDate="+effDate+"&expDate="+expDate;
$("#addDeployment").dialog({
title: "Add Deployment",
width: 430,
height: 320,
modal: true,
open: function () {
/*$("#addDeployment").load(passParam,function(event){
event.preventDefault();
}); */
$.ajax({
type : "POST",
url : passParam,
async : false,
dataType: "json",
success : function(data) {
$("#addDeployment").load("deploymentAddModal.jsp");
}
});
},
buttons: {
Close: function() {
$("#addDeployment").dialog('close');
}
}
});
})
another jsp
<input type="button" id="addDeploymentBut" value="Add" />
look at id="addDeployment" I see that it is always display:none
remove display:none thru javascript. like display:inline
document.getElementById('addDeployment').style.display = 'block';
document.getElementById('addDeployment').style.display = 'inline';

Categories

Resources