//this is my jsp page, i need autocomplete for text box name=empid.
<div class="topcorner" align="right" >
<form action="search.htm" method="POST">
EmpId : <input type="text" name="empid" id="EmpId">
Start Date :<input type="text" name="stDate" />
End Date :<input type="text" name="enDate" />
<br>
<input type="submit" value="Search" name="submit" ><br>
</form>
//My controller method is below
#RequestMapping(value= "/getEmpid", method = RequestMethod.GET )
public #ResponseBody List<UserAttendance> autoComplete(#RequestParam("term") String empId,
#RequestParam("extra") String extra) {
List<UserAttendance> getEmp = adminService.autoComplete(empId);
return getEmp;
}
//service implementation method is
public List<UserAttendance> autoComplete(String empId) {
List<UserAttendance> getEmpid = adminDao.autoComplete(empId);
for(UserAttendance emp : getEmpid ) {
if(emp.getEmpId().contains(empId)){
getEmpid.add(emp);
}
}
return getEmpid;
}
//Dao implementation method is
#Override
public List<UserAttendance> autoComplete(String empId) {
// TODO Auto-generated method stub
String sql = "SELECT EMP_ID FROM attendance WHERE EMP_ID LIKE '%?%'";
List<UserAttendance> getEmp = getSimpleJdbcTemplate().query(sql,
ParameterizedBeanPropertyRowMapper.newInstance(UserAttendance.class), empId);
return getEmp;
}
i am fresher to java spring. I have searched lot of js but not get proper one.
Can any one help me a good jquery method pls.
This is the one that we use on our project, using ajax it´s pretty good
http://jqueryui.com/autocomplete/
some code example
initializeAutocompleteDepartment = function (componentId) {
$("#" + componentId + "SelectBox").autocomplete({
source: function (request, response) {
$.ajax({
url: 'foo/bla/' + request.term + '.do',
dataType: "json",
success: function (data) {
response(data);
}
});
},
messages: {
noResults: '',
results: function () {
}
},
minLength: 2,
select: function (event, ui) {
updateData(ui.item, componentId);
return false;
}
}).data("ui-autocomplete")._renderItem = function (ul, data) {
return $("<li>")
.append("<a>" + data.name + "</a>")
.appendTo(ul);
};
};
I hope below samples help you
<link rel="stylesheet" href="css/jquery-ui.css"></link>
<script type="text/javascript" src="js/jquery-1.11.1.js"></script>
<script type="text/javascript" src="./js/jquery-ui.js"></script>
<script>
$(document).ready(function(){
$("#projectname").autocomplete(
{
source : "BaselineNames?projectname="
+ $("#projectname").val(),
select : function(ui, item) {
$("#projectname").val(item);
}
});
});
</script>
<label for="projectname" class="col-sm-2 control-label">Project
Name</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="projectname"
name="name" placeholder="Project Name Eg : UIIC Android App">
</div>
Related
I have different fields in database and I need to show all the records in jsp but when I am making ajax request to servlet, it is binding all the results to all fields. I want firstname should be bind with firstname, lastname should be bind with lastname. Currently it is binding with frstname with firstanamelastname.
I've tried all level best to solve my problem but I think, the problem is with ajax request which I am making.
<html>
<head></head>
<body>
<div class="form-row">
<div class="col-md-9">
<div class="form-row pad-left">
<div class="col-md-6 mb-1">
<label for="validationCustomUsername"><b>Birth Name:</b>
<span id='birthName'></span>
</div>
<div class="col-md-6 mb-3">
<label for="validationCustomUsername"><b>Initiated Name:</b>
<span id='initiatedName'></span>
</div>
</div>
<!-- SECOND ROW STARTS HERE -->
<div class="form-row pad-left">
<div class="col-md-6 mb-1">
<label for="validationCustomUsername"><b>Place Of Birth: </b>
<span id='placeOfBirth'></span>
</div>
</div>
<div class="form-row pad-left">
<div class="col-md-6 mb-1">
<label for="validationCustomUsername"><b>Caste:</b>
<span id='caste'></span>
</div>
</body>
</html>
Servlet Code
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/json");
int userID = UserDetails.getInstance().getLastRegisteredID();
Connection con = DBConnection.connectDB();
String query = "Select * from PERSONS inner join
PersonsDetails on persons.PersonID=PersonsDetails.PersonId "
+ "where PERSONS.PersonID="+userID;
try {
ResultSet rs = DBConnection.getDBResultSet(con, query);
UserDetails user = new UserDetails();
while(rs.next()) {
String birthName =rs.getString("BirthName");
String initiatedName =rs.getString("InitiatedName");
String placeOfBirth =rs.getString("PlaceOfBirth");
String caste =rs.getString("Caste");
response.getWriter().write(birthName);
response.getWriter().write(initiatedName);
response.getWriter().write(placeOfBirth);
response.getWriter().write(caste);
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
DBConnection.closeDBConnection(con);
}
}
Ajax Call
function userHomeDetails(){
var username = $('#username');
var url = "http://localhost:8080/IskconDevotteeMarriage/page/UserHome"
$(document).ready(function(){
var url=url
$.post("../UserHomeController", function(responseText) {
/*document.getElementById('birthName').innerHTML ="birthName"*/
$('#birthName').html(responseText);
$('#initiatedName').html(responseText);
$('#placeOfBirth').html(responseText);
$('#caste').html(responseText);
alert(responseText);
});
});
}
You can use JSONObject ,firstly add json jar file and then in your servlet class create object of JSONObject like below :
JSONObject ob= new JSONObject();
And then put your parameter like below :
try {
ob.put("birthName",birthName);
ob.put("initiatedName",initiatedName);
ob.put("placeOfBirth",placeOfBirth);
ob.put("caste",caste);
} catch (JSONException e) {
e.printStackTrace();
}
Now ,passed above parameter to your ajax call like below :
response.getWriter().write(obj);
In your ajax call set dataType: "json" and in your function(responseText) you can get this parameter like below :
document.getElementById('birthName').value = responseText.birthName;//setting values to span with id birthName
document.getElementById('initiatedName').value = responseText.initiatedName;
document.getElementById('placeOfBirth').value = responseText.placeOfBirth;
document.getElementById('caste').value = responseText.caste;
Hope this helps !
I am new with Spark Java. I have made a Library Management System with get and post methods written in Java. I have made an HTML form that takes information of user and creates users which gets stored in a ArrayList of objects in Java. When I call get method to return the list of user objects created via ajax, nothing gets returned. Success nor error gives any output.
But when I simply put the url : http://localhost:4567/users
I get the following output:
[{"id":1,"firstName":"Bhavya","lastName":"Chauhan","age":"22","gender":"F","phone":"1234567890"},
{"id":2,"firstName":"Rashi","lastName":"Chauhan","age":"20","gender":"F","phone":"1233455677"}]
I have attached my html and Spark java code. Thanks in advance!
<!DOCTYPE html>
<html>
<head>
<title>Text Input Control</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<meta charset="utf-8"/>
</head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript"></script>
<script>
$(function () {
$("#userGet").click(function(){
alert("Here");
$.ajax({
type: 'GET',
url: 'http://localhost:4567/users',
crossDomain: true,
data: '',
dataType: 'jsonp',
async:false,
success: function(responseData) {
//$("#divid").html(+responseData);
alert("hi");
},
error: function(jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Not connect.\n Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested page not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
});
});
</script>
<body>
<h2>Library Management System </h2>
<button>Get Stuff</button>
<form>
<h3>Manage Users </h3>
<input type=button onClick="location='CreateUser.html'" value='Create User'>
<br><br>
<input type=submit id="userGet" value='Get All Users'>
<br><br>
<input type=button onClick="location='UpdateUser.html'" value='Update User'>
<br><br>
</form>
<form action="http://localhost:4567/books" method="GET">
<h3>Manage Books </h3>
<input type=submit value='Get All Books'>
<br><br>
<input type=button onClick="location='FindBookByName.html'" value='Find Book By Name'>
<br><br>
<input type=button onClick="location='AddBook.html'" value='Add Book'>
<br><br>
<input type=button onClick="location='CheckOutBook.html'" value='Check Out Book'>
<br><br>
</form>
<div id="divid"></div>
</body>
</html>
Here is the Java:
import static spark.Spark.*;
public class UserController extends JsonUtil
{
public UserController(final UserService userService)
{
System.out.println("in user controller");
get("/users", (req, res) -> userService.getAllUsers(), json());
get("/books", (req, res) -> userService.getAllBooks(), json());
post("/users", (req, res) -> userService.createUser(req.body()), json());
post("/users/:id", (req, res) -> userService.updateUser(req.body()),json());
post("/books", (req, res) -> userService.addBook(req.body()), json());
post("/books/:name", (req, res) -> userService.findBookByName(req.body()),json());
post("/checkedOut", (req, res) -> userService.checkOutBook(req.body()), json());
}
}
I am trying to get data from back end server in angular. I have a java servlet which fetches data from database based on html input field and returns the response.
<!DOCTYPE html>
<html ng-app="myApp" >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script>
"use strict";
var app = angular.module('myApp', []);
app.controller('MainCtrl', function ($scope) {
$scope.cityArray = ["hyderabad", "secunderabad", "delhi", "mumbai"];
$scope.submit = function ($event) {
if ($scope.myForm.$invalid) {
// Or some other update
$scope.myForm.$submitted = true;
$event.preventDefault();
}
};
});
app.directive('uniqueUsername', function ($http) {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ngModel) {
element.bind('blur', function (e) {
ngModel.$setValidity('unique', true);
$http.post('CheckUserName.do', element.val()).success(function (data) {
if (data) {
ngModel.$setValidity('unique', false);
}
});
});
}
};
});
</script>
</head>
<body ng-controller="MainCtrl">
<h2 class="text-muted">Registration form</h2>
<div>
<form name="myForm" action="RegistrationServlet.do" method="POST" novalidate>
First name:<input type="text" class="form-control input-sm" name="uname" ng-pattern="/^[a-zA-Z]{3,20}/" ng-model="uname" unique-username="" placeholder="First Name" required/>
<span style="color:red" ng-show="myForm.uname.$error.pattern">First name cannot be less than 3 letters with no digits</span>
<span style="color:red" class="error" ng-if="myForm.$submitted && myForm.uname.$error.required">Please fill field above<br></span><br/>
<span style="color:red" class="hide-while-in-focus" ng-show="myForm.uname.$error.unique">Username already exist<br/></span>
<button class="form-control btn btn-success" type="submit" ng-click="submit($event)">Submit</button>
</form>
</div>
</body>
</html>
The problem is request.getparameter("uname") is always returning null. Right now I can see in the chrome console that angularjs is able to communicate with the servlet but the response is null as username passed is being null.
Here's the java servlet code:
public class CheckUserName extends HttpServlet {
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("application/json");
PrintWriter out = resp.getWriter();
String username = req.getParameter("uname");
System.out.println(username);
try {
Connection con = OracleDBConnection.getConnection();
String selectQuery = "select FIRSTNAME from registration";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(selectQuery);
while (rs.next()) {
String firstName = rs.getString("FIRSTNAME");
if (username.equalsIgnoreCase(firstName)) {
resp.getWriter().write("username already exist");
req.setAttribute("errMsg", "username already exist");
RequestDispatcher rd2 = req.getRequestDispatcher("/index4.jsp");
rd2.forward(req, resp);
} else {
resp.getWriter().write("username available");
// req.setAttribute("errMsg", "");
// resp.sendRedirect("EmailConfirmation.jsp");
}
}
} catch (Exception e) {
System.out.println("DB related Error");
e.printStackTrace();
}
}
}
$http.post() method expects an object and not string. Try changing your code to:
$http.post('CheckUserName.do', {
data: "uname=" + element.val()
}).success(function (data) {
if (data) {
ngModel.$setValidity('unique', false);
}
});
You haven't specify a request parameter name in post method call:
$http.post('CheckUserName.do', element.val()).success
You need to change above line to :
$http.post('CheckUserName.do',{uname:element.val()}).success
Try this,
$http.post(url, {
"uname": value
}).
success(function(data, status, headers, config) {
//success
}).
error(function(data, status, headers, config) {
//error
});
The input you are passing to the service should be like this.
I need to implement the Mercado Pago custom checkout to receive payments in my site. To do it I need to run the javascript code to get the card_token_id, like described in this link: https://developers.mercadopago.com/documentation/custom-checkout?lang=en_US.
But my website, for business restrictions, need to get this card_token_id running into a Java code, into my class. I need to run this javascript code into my Java class, get the result, e use him in a http POST. I already tried use ScriptEngine, but not works.
See below the complete code that works in html.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Pagar</title>
<script src="https://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="https://secure.mlstatic.com/org-img/checkout/custom/1.0/checkout.js"></script>
</head>
<body>
<h1>Fluxo de pagamento personalizado (avançado)</h1>
<form action="" method="post" id="form-pagar-mp">
<input id="amount" type="hidden" value="100"/>
<p>Número do cartão: <input data-checkout="cardNumber" type="text" value="4509953566233704"/></p>
<p>Código de Segurança: <input data-checkout="securityCode" type="text" value="123"/></p>
<p>Mês de vencimento: <input data-checkout="cardExpirationMonth" type="text" value="12"/></p>
<p>Ano de vencimento: <input data-checkout="cardExpirationYear" type="text" value="2020"/></p>
<p>Titular do cartão: <input data-checkout="cardholderName" type="text" value="Joao"/></p>
<p>Número do documento: <input data-checkout="docNumber" type="text" value="19313777584"/></p>
<input data-checkout="docType" type="text" value="CPF"/>
<p id="issuersField">Bancos: <select id="issuersOptions"></select>
<p>Parcelas: <select id="installmentsOption"></select>
<p><input type="submit" value="Concluir pagamento"></p>
</form>
<script type="text/javascript">
/* Troque com a sua public_key */
Checkout.setPublishableKey("TEST-cba0f2d5-c989-4c97-8e61-847121530093");
$("input[data-checkout='cardNumber']").bind("keyup",function(){
var bin = $(this).val().replace(/ /g, '').replace(/-/g, '').replace(/\./g, '');
if (bin.length == 6){
Checkout.getPaymentMethod(bin,setPaymentMethodInfo);
}
});
// Estabeleça a informação do meio de pagamento obtido
function setPaymentMethodInfo(status, result){
$.each(result, function(p, r){
$.each(r.labels, function(pos, label){
if (label == "recommended_method") {
Checkout.getInstallments(r.id ,parseFloat($("#amount").val()), setInstallmentInfo);
Checkout.getCardIssuers(r.id,showIssuers);
return;
}
});
});
};
// Mostre as parcelas disponíveis no div 'installmentsOption'
function setInstallmentInfo(status, installments){
var html_options = "";
for(i=0; installments && i<installments.length; i++){
html_options += "<option value='"+installments[i].installments+"'>"+installments[i].installments +" de "+installments[i].share_amount+" ("+installments[i].total_amount+")</option>";
};
$("#installmentsOption").html(html_options);
};
function showIssuers(status, issuers){
var i,options="<select data-checkout='cardIssuerId'><option value='-1'>Escolha...</option>";
for(i=0; issuers && i<issuers.length;i++){
options+="<option value='"+issuers[i].id+"'>"+issuers[i].name +" </option>";
}
options+="</select>";
if(issuers.length>0){
$("#issuersOptions").html(options);
}else{
$("#issuersOptions").html("");
$("#issuersField").hide();
}
};
$("#issuersOptions").change(function(){
var bin = $("input[data-checkout='cardNumber']").val().replace(/ /g, '').replace(/-/g, '').replace(/\./g, '').slice(0, 6);
Checkout.getInstallmentsByIssuerId(bin,this.value,parseFloat($("#amount").val()),setInstallmentInfo);
});
$("#form-pagar-mp").submit(function( event ) {
var $form = $(this);
Checkout.createToken($form, mpResponseHandler);
event.preventDefault();
return false;
});
var mpResponseHandler = function(status, response) {
var $form = $('#form-pagar-mp');
if (response.error) {
alert("Ocorreu um erro: "+JSON.stringify(response));
} else {
var card_token_id = response.id;
$form.append($('<input type="text" id="card_token_id" name="card_token_id"/>').val(card_token_id));
alert("card_token_id: "+card_token_id);
$form.get(0).submit();
}
}
</script>
</body>
</html>
i cant get the value of a freeMarker variable when i put my code in a external javascript file
here is my page when the javascript code inside, this works i can get the value of my freemarker variable in this way:
<#import "../masterPage.html" as layout>
<#layout.masterPageLay bread1="my bread1" bread2="my bread2">
<#assign title="value 1">
<#assign subtitle="value 2">
<script>
function doAjaxPost()
{
var name= $('#name').val();
var lastName= $('#lastName').val();
var json = {"name" : name, "lastName" : lastName};
console.log(json);
var variableFreeMarker = "${freeMarkValue}";
console.log('this value is: ' + variableFreeMarker);
$.ajax(
{
type: "POST",
url: "myUrl",
data: JSON.stringify(json),
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
beforeSend: function(xhr)
{
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success: function(data)
{
},
error:function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er);
}
/* error: function (xhr, ajaxOptions, thrownError)
{
alert(xhr.status);
alert(xhr.responseText);
alert(thrownError);
}*/
});
}
</script>
<form name="myform">
Name in view: <input type="text" id="name" name="name">
<br>
Last Name in view: <input type="text" id="lastName" name="lastName">
<br>
Show modify name in view: <input type="text" id="modifyname" name="modifyname">
<br>
<input type="button" value="Add Users" onclick="doAjaxPost()">
</form>
<br>
</#layout.masterPageLay>
but if i put my javascript code in a external file in this case myPageScript.js and then call that script in my page i cant get the value of my freeMarker variable this is how i'm calling my script
<script src="../resources/js/scripts/myPageScript.js"></script>
and this is my page that dont work
<#import "../masterPage.html" as layout>
<#layout.masterPageLay bread1="my bread1" bread2="my bread2">
<#assign titulo="value 1">
<#assign subtitulo="value 2">
<script src="../resources/js/scripts/myPageScript.js"></script>
<form name="myform">
Name in view: <input type="text" id="name" name="name">
<br>
Last Name in view: <input type="text" id="lastName" name="lastName">
<br>
Show modify name in view: <input type="text" id="modifyname" name="modifyname">
<br>
<input type="button" value="Add Users" onclick="doAjaxPost()">
</form>
<br>
</#layout.masterPageLay>
this output in my chrome console "${freeMarkValue}" instead of the value of the variable
here are my controllers i'm processing the form using jquery ajax
#RequestMapping(value = "myForm", method = RequestMethod.GET)
public String myForm(Model model) {
model.addAttribute("freeMarkValue", "controll");
return "myForm";
}
#RequestMapping(value = "myForm", method = RequestMethod.POST)
public #ResponseBody String getTags(#RequestBody final String json, Model model)
throws IOException
{
ObjectMapper mapper = new ObjectMapper();
User objetmapped = mapper.readValue(json, User .class);
User person = new User iox();
person.setName(objetmapped .getName());
person.setLastName(objetmapped .getLastName());
);
model.addAttribute("freeMarkValue", "second controller value");
return toJson(objetmapped );
}
private String toJson(User person)
{
ObjectMapper mapper = new ObjectMapper();
try
{
String value = mapper.writeValueAsString(person);
// return "["+value+"]";
return value;
}
catch (JsonProcessingException e)
{
e.printStackTrace();
return null;
}
}
You can move your variable into a script block in the html page.
<#import "../masterPage.html" as layout>
<#layout.masterPageLay bread1="my bread1" bread2="my bread2">
<#assign titulo="value 1">
<#assign subtitulo="value 2">
<script src="../resources/js/scripts/myPageScript.js"></script>
<script>
// This variable can be accessed from myPageScript.js
var variableFreeMarker = "${freeMarkValue}";
</script>
<form name="myform">
Name in view: <input type="text" id="name" name="name">
<br>
Last Name in view: <input type="text" id="lastName" name="lastName">
<br>
Show modify name in view: <input type="text" id="modifyname" name="modifyname">
<br>
<input type="button" value="Add Users" onclick="doAjaxPost()">
</form>
Or add it as a value of a hidden input etc..
<input type="hidden" id="myVal" value="${freeMarkValue}">
Your JS (in a seperate script) would then need to read the value for example using jQuery.
var aValue = $("#myVal").val();
I use the first method for common stuff such as adding a date format string that is specific to the user on to every page. They will have global scope so be careful with naming.