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.
Related
I've been working on a little project with Java Spring. I've already set the table structure in Navicat to be able "null" values. I have also set the model to be able to null values.
But still, I can't input null values into the column and received this error messages.
FYI: I'm using Spring Tool Suite 3.9.7 IDE
Field error in object 'sertifikasihapus' on field 'modified_on': rejected value [];
codes [typeMismatch.sertifikasihapus.modified_on,typeMismatch.modified_on,typeMismatch.java.sql.Timestamp,typeMismatch];
arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [sertifikasihapus.modified_on,modified_on];
arguments [];
default message [modified_on]];
default message [Failed to convert property value of type 'java.lang.String' to required type 'java.sql.Timestamp' for property 'modified_on';
nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [#javax.persistence.Column java.sql.Timestamp] for value '';
nested exception is java.lang.IllegalArgumentException: Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]]]
<script>
$('#idBtnHapusHapus').click(function() {
var vDataRole = $('#idFrmHapusSertifikasi').serialize();
var angka = $('#Id').val();
var nama = $('#idNamaSertifikasi').val();
if ($("#idModifiedOn").val().length < 1) {
$('#idModifiedOn').val(null);
debugger;
$.ajax({
url : './hapussertifikasi/' + angka,
type : 'Put',
data : vDataRole,
dataType : "json",
success : function(model) {
debugger;
window.location = './sertifikasi'
},
error : function(model) {
debugger;
}
});
} else {
debugger;
$.ajax({
url : './hapussertifikasi/' + angka,
type : 'Put',
data : vDataRole,
dataType : "json",
success : function(model) {
debugger;
window.location = './sertifikasi'
},
error : function(model) {
debugger;
}
});
}
});
</script>
<div class="col-xs-12">
<div class="row">
<form id="idFrmHapusSertifikasi" method="post">
<input type="hidden" class="form-control" id="Id" name="id"
placeholder="">
<input type="hidden" class="form-control"
id="idNamaSertifikasi" name="certificate_name" placeholder="">
<input type="hidden" class="form-control" id="idBulanBerlaku"
name="valid_start_month" placeholder="">
<input
type="hidden" class="form-control" id="idTahunBerlaku"
name="valid_start_year" placeholder="">
<input
type="hidden" class="form-control" id="idPenerbit" name="publisher"
placeholder="">
<input type="hidden" class="form-control"
id="idBulanBerlakuS" name="until_month" placeholder="">
<input
type="hidden" class="form-control" id="idTahunBerlakuS"
name="until_year" placeholder="">
<input type="hidden"
class="form-control" id="idCatatan" name="notes" placeholder="">
<input type="hidden" class="form-control" id="idCreateOn"
name="createOn" placeholder="">
<input type="hidden"
class="form-control" id="idCreateBy" name="createBy" placeholder="">
<input type="hidden" class="form-control" id="idModifiedOn"
name="modified_on" placeholder="">
<input type="hidden"
class="form-control" id="idModifiedBy" name="modified_by"
placeholder="">
</form>
<div class="col-xs-2">
<i class="glyphicon glyphicon-trash center" style="font-size: 50px"></i>
</div>
<div class="col-xs-8">
<div class="clTulisanHapus center" id="idTulisanHapus">
<p>Anda Yakin ingin menghapus Sertifikasi</p>
<!-- I WANTED THE CERTIFICATE NAME TO BE HERE -->
<div th:each="item:${oneprofil}">
<b><p th:text="${item.certificate_name}+' ?'"></p></b>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-offset-8">
<div class="btn-group">
<input type="hidden" id="idDataId"> <input type="hidden"
id="idDataNama">
<button type="button" id="idBtnHapusBatal" data-dismiss="modal"
class="btn clBtnMdlHapus">Tidak</button>
<button type="button" id="idBtnHapusHapus" data-id="${item.id}"
class="btn clBtnMdlHapus">Ya</button>
</div>
</div>
Looks like your value is not null but an empty String (""). You can use the keyword null without any "quotation marks".
For more info, see this question:
in practice you can simply pretend that it's "merely a special literal that can be of any reference type".
[Failed to convert property value of type 'java.lang.String' to
required type 'java.sql.Timestamp' for property 'modified_on';
You are receiving the value as an empty string instead of null which leads to type mismatch and causing the issue.
From HTML I see that you are sending it as for hidden parameter. There is an alternative way to automatically set the creation date and modified date in Spring Boot.
Use below in Entity
#PrePersist
protected void prePersist() {
createdAt = set value here
}
#PreUpdate
protected void preUpdate() {
modifiedOn = set valye here
}
Hibernate
#CreationTimestamp - Documentation
#UpdateTimestamp - Documentation
Spring Data JPA
#CreatedDate - Documentation
#LastModifiedDate - Documentation
I want to send data from a form to a Servlet using Ajax, but when I made a check about the data that was being serialized using the jQuery .serialize() function, I noticed that it wasn't taking the value of the file field. In a previous test I got an error with a message like this: the request was rejected because there was no multipart data found
The following is the form HTML code:
<form id="frmCrcnCaso" class="form-horizontal" enctype="multipart/form-data">
<input id="txtNoVlt" name="txtNoVlt" type="text" class="form-control">
<input id="txtNmr" name="txtNmr" type="text" class="form-control">
<input id="txtFchOfc" name="txtFchOfc" type="date" class="form-control">
<input id="flAcvAjt" name="flAcvAjt" type="file" class="form-control"/>
</form>
<button id="btnGuardar" type="button" class="btn btn-lg btn-primary">
Guardar
</button>
And this is the javascript code:
$("#btnGuardar").on("click",function(){
ValidarGuardado();
});
function ValidarGuardado(){
...
// Activar el guardado
Guardar();
}// </editor-fold>
function Guardar(){
$(...).append("...
<button id='btnGdrCaso' type='button' class='btn btn-primary'><i class='fa fa-check'></i> Guardar</button>\n\
...");
$(...).modal();
$("#btnGdrCaso").on("click",function(){
...
var datosCaso = $("#frmCrcnCaso").serialize();
...
$.ajax({
url: "GuardarCaso" // Servlet name,
type: "POST",
contentType : false,
data: datosCaso,
success:function(r){
if(r === "1"){
...
}else if(r === "2"){
...
}else{
...
}
},
error:function(r){
...
}
});
});
}
Code to post PayPal form.
<body>
<form accept-charset="utf-8"
action="https://www.sandbox.paypal.com/au/cgi-bin/webscr" id="frm"
method="post">
<input type="hidden" name="business"
value="aaaa-facilitator#gmail.com"> <input
type="hidden" name="cancel_return"
value="http://localhost:8080/abc-jaxrs/web/cancel_redirection"> <input type="hidden"
name="cmd" value="_xclick"> <input type="hidden"
name="charset" value="utf-8"> <input type="hidden"
name="currency_code" value="USD"> <input type="hidden"
name="notify_url" value="http://localhost:8080/abc-jaxrs/web/success_redirection"> <input
type="hidden" name="return" value="http://localhost:8080/abc-jaxrs/web/success_redirection"> <input
type="hidden" name="item_name" value="123"> <input
type="hidden" name="amount" value="0.1">
</form>
<p style="text-align: center">
<h4>Redirecting To PayPal...</h4>
<script>
$(this.document).ready(function() {
$('.loaderparent').show();
var frm = $("form");
frm.submit();
});
</script>
Code to retrieve data from data from Java controller.
#RequestMapping(value = "/success_redirection", method = RequestMethod.GET)
public ModelAndView successRedirection(HttpServletRequest request, HttpServletResponse response) {
String itemName = (String) request.getAttribute("item_name"); // or
String itemNname = request.getParameter("item_name");
}
But getting itemName value as null in both cases.
So how to retrieve success/failure data from PayPal in JAVA.
Ensure enabling the Instant Payment Notification (IPN) from paypal account setting along with the success URL.
My Profile > My Selling Tools> Instant payment notifications >update then like below.
I am trying to insert a record into MySQL database using HTML form. I am using AJAX to call web services in Java. But it is not working. It gives an alert saying false. When I tried with POSTMAN it works fine. But using AJAX it's not working.
Can anybody help me? Thanks in advance.
Code in Add.jsp
<body>
<form id="submit">
Username:<br>
<input type="text" name="username"><br>
Email:<br>
<input type="email" name="email"><br><br>
Password:<br>
<input type="text" name="password"><br><br>
<input type="submit" value="Submit">
</form>
</body>
<script type="text/javascript">
$(document).ready(function() {
$("#submit").submit(function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "http://localhost:8080/WebService/webresources/users/insert",
data: formToJSON(),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data)
{
alert('Success');
},
error: function(jqXHR, textStatus, errorThrown)
{
alert('Error: ' + textStatus);
}
});
});
});
function formToJSON()
{
return JSON.stringify
({
"username": $('#username').val(),
"email": $('#email').val(),
"password": $('#password').val()
});
};
</script>
Code in Service
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Path("/insert")
public boolean insertUsers(String content)
{
Gson g = new Gson();
Users u = (Users) g.fromJson(content, Users.class);
UsersDAO dao = new UsersDAO();
return dao.insertUsers(u);
}
You have to add id for all the input fields.
Try this.
<body>
<form id="submit">
Username:<br>
<input type="text" id="username" name="username"><br>
Email:<br>
<input type="email" id="email" name="email"><br><br>
Password:<br>
<input type="text" id="password" name="password"><br><br>
<button id="submit">Save</button>
</form>
</body>
And in this, You have to change this,
$("#submit").submit(function(event)
into this,
$("#submit").click(function(event)
I am trying to propagate the value in input type[text] whenever user is selecting one option from select box.
I have a form containing one select option and 3 input type(text) field. What i am trying to do here whenever user select one option from select box depending upon that option value some data i want to fetch from database and propagate to the same page in input type and then after clicking on submit button i want to store the data in database.
I have used ajax call for the same but the problem is that on selecting option value i am able to get the particular data but i am not able to get the same data in jsp input type, each time i need to reload the page manually.
userdetail.jsp
//imports are here
<html>
<head>
</head>
<body>
<script src="js/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".name").change(function(){
var name = $(this).val();
if(name.length >= 1){
$(".status").html("<font color=gray> Checking availability...</font>");
$.ajax({
type: "POST",
url: "getparamfromdb.do",
data: "name="+name,
success: function(msg){
$(".status").ajaxComplete(function(event, request, settings){
$(".status").html(msg);
});
}
});
}
else{
$(".status").html("<font color=red>Username should be atleast <b>5</b> character long.</font>");
}
});
});
</script>
<div class="add">
<form:form method="post" action="addHealthParam.do" >
<table style="margin-top:-6%; margin-left:8%;">
Parameter Name:<br>
<select name="name" class="name">
<option value="select">Select</option>
<option value="Glucose, Serum">Glucose, Serum</option>
<option value="Uric Acid, Serum">Uric Acid, Serum</option>
<option value="Platelets">Platelets</option>
<option value="NRBC">NRBC</option>
</select>
Parameter Current Reading:
<input type="text" name="current_reading"/>
Unit of Measurement:
<select name="measurementunit" >
<option>
<c:forEach var="healthp" items="${paramvalue}">
${healthp.measurementunit}
</c:forEach>
</option>
</select>
Reference Range(Minimum):
<input type="text" name="minrange" value="
<c:forEach var="healthp" items="${paramvalue}">
${healthp.minrange}
</c:forEach>" >
Reference Range(Maximum):<br>
<input type="text" name="maxrange"
value="
<c:forEach var="healthp" items="${paramvalue}">
${healthp.maxrange}
</c:forEach>">
<input type="submit" value="Submit"/>
</body>
</html>
Controller class:-
imports are here
#Controller
#SessionAttributes
public class HealthParameterController {
#Autowired
BharatService service;
#Autowired
HibernateTemplate hibernateTemp;
List<HealthParameter> healthparam=null;
// to store the value in database.
#RequestMapping(value="/addHealthParam.do",method=RequestMethod.POST)
public String addHealthParam(#ModelAttribute("addhealthparam")HealthParamMVC addhealthparam,BindingResult result,HttpSession session){
// code to store the value in database
}
// execute through ajax call
#RequestMapping(value="/getparamfromdb.do",method=RequestMethod.POST)
public String gettingParam(#ModelAttribute("addhealthparam")
HealthParamMVC addhealthparam,BindingResult result,
HttpServletRequest req,HttpSession session){
System.out.println("In gettingParam ");
String name=addhealthparam.getName();
List<ParameterFromDB> li=service.getParamfromDb(name);
// further getting value from database based on name.
Iterator it=li.iterator();
while(it.hasNext()){
Object ob=it.next();
ParameterFromDB db= (ParameterFromDB) ob;
}
session.setAttribute("paramvalue", li);
// i have tried it with request also
//request.setAttribute("paramvalue", li);
return "userdetails";
}
}
Here is some modify code. please check and let me know it's working or not.
<html>
<head>
</head>
<body>
<script src="js/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".name").change(function(){
var name = $(this).val();
if(name.length >= 1){
$(".status").html("<font color=gray> Checking availability...</font>");
$.ajax({
type: "POST",
url: "getparamfromdb.do",
data: "name="+name,
success: function(msg){
$(".status").ajaxComplete(function(event, request, settings){
var json = eval(msg);
$(".status").html(msg);
var minRange = json.MINRANGE;
vat maxRange = json.MAXRANGE;
$('#minrange').val(minRange);
$('#maxRange').val(maxRange);
});
}
});
}
else{
$(".status").html("<font color=red>Username should be atleast <b>5</b> character long.</font>");
}
});
});
</script>
<div class="add">
<form:form method="post" action="addHealthParam.do" >
<table style="margin-top:-6%; margin-left:8%;">
Parameter Name:<br>
<select name="name" class="name">
<option value="select">Select</option>
<option value="Glucose, Serum">Glucose, Serum</option>
<option value="Uric Acid, Serum">Uric Acid, Serum</option>
<option value="Platelets">Platelets</option>
<option value="NRBC">NRBC</option>
</select>
Parameter Current Reading:
<input type="text" name="current_reading"/>
Unit of Measurement:
<select name="measurementunit" >
<option>
<c:forEach var="healthp" items="${paramvalue}">
${healthp.measurementunit}
</c:forEach>
</option>
</select>
Reference Range(Minimum):
<input type="text" id="minrange" value="
<c:forEach var="healthp" items="${paramvalue}">
${healthp.minrange}
</c:forEach>" >
Reference Range(Maximum):<br>
<input type="text" id="maxrange"
value="
<c:forEach var="healthp" items="${paramvalue}">
${healthp.maxrange}
</c:forEach>">
<input type="submit" value="Submit"/>
</body>
</html>
i use response object here. you need to get that.
imports are here
#Controller
#SessionAttributes
public class HealthParameterController {
#Autowired
BharatService service;
#Autowired
HibernateTemplate hibernateTemp;
List<HealthParameter> healthparam=null;
// to store the value in database.
#RequestMapping(value="/addHealthParam.do",method=RequestMethod.POST)
public String addHealthParam(#ModelAttribute("addhealthparam")HealthParamMVC addhealthparam,BindingResult result,HttpSession session){
// code to store the value in database
}
// execute through ajax call
#RequestMapping(value="/getparamfromdb.do",method=RequestMethod.POST)
public String gettingParam(#ModelAttribute("addhealthparam")
HealthParamMVC addhealthparam,BindingResult result,
HttpServletRequest req,HttpSession session){
JSONObject json = new JSONObject();
JSONArray jsonArray = new JSONArray();
System.out.println("In gettingParam ");
String name=addhealthparam.getName();
List<ParameterFromDB> li=service.getParamfromDb(name);
// further getting value from database based on name.
Iterator it=li.iterator();
while(it.hasNext()){
Object ob=it.next();
ParameterFromDB db= (ParameterFromDB) ob;
String minRange = ""; // Create what you want to display in Minrange Text Box
String maxRange = ""; // Create what you want to display in Maxrange Text Box
}
json.put("MINRANGE",minRange);
json.put("MAXRANGE",maxRange);
//Get a RESPONCE object here.
PrintWriter out = response.getWriter();
out.print(json.toString());
session.setAttribute("paramvalue", li);
// i have tried it with request also
//request.setAttribute("paramvalue", li);
return "userdetails";
}
}