Send a message from html to Servlet java using ajax - java

I have a stupid proplem for send the input from a html page to a servlet using ajax.
Practically I create the message java how I learned, but the servlet doesn't read the input value. I insert my code
<div class="col_9">
<h1>Ricerca Dataset</h1>
<div class="form">
<div class="col_9">
<div class="col_12">
<div class="col_5">Cerca:</div>
<div class="col_6">
<input id=query type="text" name="name" />
</div>
</div>
</div>
<div class="col_3">
<button id="cerca" class="large">Cerca</button>
</div>
</div>
</div>
function cercaNormaleFn() {
$("#cerca").click(function(e) {
$("#center").load("ShowResult.jsp", function() {
var oTable = $('#example').dataTable({
"processing" : true,
"ajax" : {
url : context + "/CercaServlet",
dataSrc : "demo",
type : "Post",
data : "query=" + $("#query").val(),
}
});
alert(query)
});
});
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
System.out.println(request.getAttribute("data"));
}

You may need to add the attribute to your dataTable function:
"serverSide": true
as dataTables.net Server-side processing explains:
With server-side processing enabled, all paging, searching, ordering etc actions that DataTables performs are handed off to a server
A demo from dataTables.net post demo

Related

how to pass datalist values from jsp to servlet

I have written a jsp file and servlet .In jsp I have used data list inside a form .And I want to pass that user input to the servlet.I have posted the code below.
jsp code
<form action="NewServlet1" method="Post" >
<center>
<input type="text" name="website" list="website" placeholder="Enter your website">
<datalist id="website">
<option value="https://www.google.lk/">GOOGLE</option>
<option value="https://www.yahoo.com/">YAHOO</option>
<option value="https://www.hackerrank.com/">HACKER RANK</option>
</datalist><br><br><br>
</center></form>
<div style="width: 400px; height: 400px">
<canvas id="myChart" width="1000" height="1000" ></canvas>
</div>
<center> <div>
<button id="button1" name="button1" onclick="submit()" class="btn btn-primary">submit</button>
</div></center>
<script>
function Test(today, time) {
var ctx = new Chart(document.getElementById("myChart")
, {
type: 'line',
data: {
labels: today,
datasets: [{
data: time,
label: "Web Service 1",
borderColor: "red",
fill: false
}
]
},
options:
{
scales: {xAxes: [{display: true, scaleLabel: {display: true, labelString: 'date and time'}}], yAxes: [{display: true, ticks: {beginAtZero: true, steps: 100, stepValue: 50, max: 6000}}]},
hover: {intersect: false },
title: {display: true, text: 'response time of selected website'},
tooltips: { mode: 'nearest'}
}
});
}
function submit()
{
$.post("NewServlet1",
{
},
function (data)
{
Test(data.today, data.time);
});
}
servlet code
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String website = (String)request.getParameter("website");
But this is not working.Can someone help me to solve this?
First of all you need to submit the form to the servlet which path is mapped to NewServlet1
<form action="NewServlet1" method="Get" >
<center>
<input type="text" name="website" placeholder="Enter your website">
<datalist id="website">
<option value="https://www.google.lk/">GOOGLE</option>
<option value="https://www.yahoo.com/">YAHOO</option>
<option value="https://www.hackerrank.com/">HACKER RANK</option>
</datalist>
</center>
<%
String website= request.getParameter("website"); // it is not needed
request.setAttribute("website",website); // it is not needed
%>
<input type="submit"/> <!--need to add submit button to submit it to the servlet-->
</form>
Now your servlet code is fine which is:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String website = (String)request.getParameter("website");
}
Note : Need to write some value in website text box
Or if you want to get attribute which previously stored in request object then use RequestDispatcher.

User interface does not come out when passing the value to servlet using link <a href>

I'm implementing MVC using JAVA. I want to display the details from db. I'm passing the value using link which direct to the servlet page. The details from the db come out on the screen but the problem is the user interface does not appear. I have already include all of my CSS style files in jsp pages. But when I run the page itself without connecting to servlet, the UI appear nicely.(but without it data from db)
How can I solve this? Help me.
Here are the codes;
1.jsp file(where the input value):
'
Search Patient :
<div class="col-sm-9">
<input type="text" id="empid" name="empid" placeholder="ID" class="col-xs-10 col-sm-5" />
</div>
</div>
<div class="space-4"></div>
<div class="clearfix form-actions">
<div class="col-md-offset-3 col-md-9">
Search
<button class="btn" type="reset">
<i class="ace-icon fa fa-undo bigger-110"></i>
Reset
</button>
</div>
</div>
</form>'
Servlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("13124124");
String forward="";
String action = request.getParameter("action");
if (action.equalsIgnoreCase("view")){
System.out.println("sdfvdsdsg");
forward = "/cms/viewempdetail.jsp";
int empid = Integer.parseInt(request.getParameter("empid"));
Employee employee = empdao.EmployeebyId(empid);
System.out.println(employee.getEmpName());
request.setAttribute("employee", employee);
}
RequestDispatcher view = request.getRequestDispatcher(forward);
view.forward(request, response);
}
}
}
'

getParameters keeps returning null

So, I'm having trouble retrieving information from my the client-side jsp. The javascript executes, and the alert prints, however query becomes null in the java servlet, and null is then written to the logger. I can't seem to figure out why the query is now null.
HTML:
<div id="query">
<div id="querybar">
<form onsubmit="query();return false;" method="get">
<input type="text" id="querytext" placeholder="Run a query" name="querytext">
</form>
<div id="queryimg-container">
<img src="styles/magnifyingglass.png" id="queryimg" alt="" />
</div>
</div>
</div>
JS:
function query() {
$.get('QueryHelper', function(data) {
alert("Somesortofalert");
});
}
Java Servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String query = request.getParameter("querytext");
response.setContentType("text/plain");
#SuppressWarnings("resource")
PrintWriter writer = response.getWriter();
sLogger.info(query);
}
Can anyone see anything wrong? I'm super stumped here.
It'll be null because no parameter by that name is being sent with the Ajax request.
Despite being started by an onsubmit event, $.get() doesn't have any automatic knowledge of the <form>. It's up to you to gather or specify any parameters to be included with the request using the data parameter.
$.get('QueryHelper', { querytext: 'foo bar' }, function (res) {
// ...
});
Provided you have a reference to the <form> or its inputs, you can use .serialize() to prepare the fields' names and values as data.
<form onsubmit="query(this); return false;" method="get">
<!-- ^^^^ -->
function query(form) {
// ^^^^
$.get('QueryHelper', $(form).serialize(), function (res) {
// ^^^^^^^^^^^^^^^^^^^
// ...
});
}

Submit more forms with one button in jsp

I try to submit two forms with one button, but value of first form(input) is null.
test.jsp
<body>
<script>
function submitAllForms(){
console.log($('input[name=valueDateFromFilter]').val());
console.log($('input[name=valueDateToFilter]').val());
document.formDateFromFilter.submit();
document.formDateToFilter.submit();
};
</script>
<form method="post" action="./Servlet" name="formDateFromFilter">
<input class="span2" size="16" type="text" name="valueDateFromFilter">
</form>
<form method="post" action="./Servlet" name="formDateToFilter">
<input class="span2" size="16" type="text" name="valueDateToFilter">
</form>
<a class="btn" href="#" onclick="submitAllForms();"><i class="icon-message"></i></a>
</body>
doPost method in Servlet.jsp
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String a = request.getParameter("valueDateFromFilter");
String b = request.getParameter("valueDateToFilter");
System.out.println(a);
System.out.println(b);
}
In browser console i see values of both strings, but in the server log console value of first string (variable a) is null
This is poor design and probably won't work. The better way to do it would be to build a JSP/servlet that receives both sets of data and calls the other servlets with the appropriate fields programatically on the server side

Ajax call not hitting controller

hi I am trying to Use Ajax with Spring Mvc Porltet In liferay.I Have a Jsp File and Controller Class.I want to insert a data in the form but my controller class is Not Called.So please Help Me to Solve this Problem.When I Click on submit My COntroller class is not called.
my .jsp code as follws:
<%# taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<portlet:defineObjects/>
<portlet:renderURL var="renderOneMethodURL">
<portlet:param name="action" value="renderOne"></portlet:param>
</portlet:renderURL>
<portlet:actionURL var="actionOneMethodURL">
<portlet:param name="action" value="actionOne"></portlet:param>
</portlet:actionURL>
Call RenderOne method
<%-- <form action="${actionOneMethodURL}" method="post">
User Name: <input type="text" name="userName">
<input type="submit">
</form> --%>
<div id="request">
<div id="bigForm">
<h2> REQUEST</h2>
<h3> Enter Request Details :</h3>
<p>Name: <input name="name">
Code: <input name="code" size="6">
Request: <input name="request">
Type: <input name="type" size="6"></p>
<hr></hr>
<div class="block2">
<h2> Attribute Value Pair(Avp)</h2>
<p class="remark"> Recursive structure of avp. You can nest one AVP inside another..</p>
<div data-holder-for="branch"></div>
</div>
<div class="clear"></div>
<p> </p>
<p class="remark" align="right" padding-right:"1cm";>Click here to generate JSON representation of the form</p>
<p align="right">
<input type="submit" id="saveBigForm"></p>
</div>
<style type="text/css">a {text-decoration: none}</style>
<!-- Subforms library -->
<div style="display:none">
<div data-name="branch">
<table>
<td>Name:</td> <td><input name="name"></td>
<td>Code:</td> <td><input name="code"></td>
<td>Vendor:</td> <td><input name="vendor"></td>
<td>Multiplicity:</td><td><input name="multiplicity"></td>
<td>Index:</td><td><input name="index"></td>
<td>CDR-Index:</td><td><input name="cdrIndex"></td>
<tr>
<td >Type:</td><td><input name="type"></td>
<td>Value:</td><td><input name="value"></td>
</tr>
</table>
<div style="margin:10px; border-left:3px solid black" data-holder-for="branch"></div>
</div>
</div>
<div id="popup"></div>
</div>
and my javascript
$('#saveBigForm').click(function(){
var json = $('#bigForm').jqDynaForm('get');
showFormJson(json);
// var myInfoUrl = "<c:out value="${actionOneMethodURL}" />";
$.ajax({
type: "POST",
//url: "http://localhost:9090/first-spring-mvc-portlet//WEB-INF/servlet/view",
//url : myInfoUrl,
url : "${actionOneMethodURL}",
data: JSON.stringify(json),
dataType: "json",
success: function(response){
// we have the response
if(response.status == "SUCCESS"){
$('#info').html("Success........!Request has been added......... ");
}else{
$('#info').html("Sorry, there is some thing wrong with the data provided.");
}
},
error: function(e){
alert('Error: ' + e);
}
});
});
and controller class as follows
package com.myowncompany.test.springmvc.controller;
import java.io.IOException;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.portlet.bind.annotation.ActionMapping;
import org.springframework.web.portlet.bind.annotation.RenderMapping;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.ParamUtil;
#Controller(value = "MyFirstSpringMVCTestController")
#RequestMapping("VIEW")
public class MyFirstSpringMVCTestController {
private static Log log = LogFactoryUtil.getLog(MyFirstSpringMVCTestController.class);
/*
* maps the incoming portlet request to this method
* Since no request parameters are specified, therefore the default
* render method will always be this method
*/
#RenderMapping
public String handleRenderRequest(RenderRequest request,RenderResponse response,Model model){
return "defaultRender";
}
#RenderMapping(params = "action=renderOne")
public String openSaveSearchPopup(RenderRequest request, RenderResponse response, Model model){
return "render1";
}
#RenderMapping(params = "action=renderTwo")
public String openDeeplinkForInfoI(RenderRequest request, RenderResponse response){
return "render2";
}
#RenderMapping(params = "action=renderAfterAction")
public String testRenderMethod(RenderRequest request, RenderResponse response){
log.info("In renderAfterAction method");
return "renderAfterAction";
}
#ActionMapping(params = "action=actionOne")
public void actionOne(ActionRequest request, ActionResponse response) throws IOException {
String userName=ParamUtil.get(request, "userName", "");
log.info("server input stream is :::"+ request.getPortletInputStream().toString());
System.out.println("we ri nnnnnnnnn");
log.info("userName is==>"+userName);
response.setRenderParameter("action", "renderAfterAction");
}
#ActionMapping(params = "action=actionTwo")
public String addMyChannelAction(ActionRequest actionRequest, ActionResponse actionResponse) {
return "action2";
}
}
iam getting the log as follows:
09:36:56,291 INFO [DispatcherPortlet:119] Portlet 'firstspringmvc' configured successfully
09:36:56,300 INFO [localhost-startStop-19][PortletHotDeployListener:454] 1 portlet for first-spring-mvc-portlet is available for use
10:09:49,460 WARN [http-bio-9090-exec-138][404_jsp:121] {msg="/$%7BactionOneMethodURL%7D", uri=/$%7BactionOneMethodURL%7D}
10:09:54,325 WARN [http-bio-9090-exec-139][404_jsp:121] {msg="/$%7BactionOneMethodURL%7D", uri=/$%7BactionOneMethodURL%7D}
Try with jsp core tag,
url : "<c:url value='/VIEW/actionOne' />"
OR
url : "<c:out value='${actionOneMethodURL}' />"
Include JSTL core in JSP i.e.:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
and Change your ajax URL
url : "${actionOneMethodURL}"
to
url : "<c:url value='/VIEW/actionOne' />",
From what you have told us so far I can identify those causes:
your javascript has a problem and is not running at all (open with google chrome or firefox and press F12. Go to the Console tab and tell us if you have any errors there.
since you have a different javascript file, as the warning said, ${actionOneMethodURL}is not defined there. So you can do it like this:
In your HTML (the .jsp file you postet at top):
<script type="text/javascript">
ajaxLink = "${actionOneMethodURL}";
</script>
In your javascript file:
url : window.ajaxLink;
Experiment with this, I have no way to test it may need some tweaks like where you add the script (near the beginning of the document, near the end), and if the " surrounding the ${actionOneMethodURL} are needed.
in .jsp page add
var actionurl =${actionOneMethodURL};
in example.js on ajax call
$.ajax({
type: "POST",
url : actionurl,
data: JSON.stringify(json),
dataType: "json",
success: function(response){
// we have the response
if(response.status == "SUCCESS"){
$('#info').html("Success........!Request has been added......... ");
}else{
$('#info').html("Sorry, there is some thing wrong with the data provided.");
}
},
error: function(e){
alert('Error: ' + e);
}
});

Categories

Resources