I am very new to ajax concept,I want to submit a form without refresh the page
ajax
function ajaxFunction() {
if(xmlhttp) {
var txtname = document.getElementById("txtname");
xmlhttp.open("POST","Listservlet",true);
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("txtname=" + txtname.value);
}
}
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
document.fname.message.innerHTML=xmlhttp.responseText;
}
else {
alert("Error during AJAX call. Please try again");
}
}
}
JSP
<form name="fname" action="Listservlet" method="post">
<input type="text" name="txtname" id="txtname" />
<input type="button" value="Submit" onclick="ajaxFunction();" />
<div id="message"></div>
</form>
servlet
public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
String name = null;
PrintWriter out = response.getWriter();
if(request.getParameter("txtname") != null) {
name = request.getParameter("txtname");
}
else {
name = "";
}
out.println("You have successfully made Ajax Call:" + name);
}
This ajax idea I got from google, bt it is not working,
While clicking on the button,nothing it showing.
Please help me.
replace
document.fname.message.innerHTML=xmlhttp.responseText;
by
document.getElementById("message").innerHTML=xmlhttp.responseText;
General Steps to find out where goes wrong:
use browser debugger to tell if ajax request was successfully sent;
debug your receiving Servlet, to tell if request was actually delivered to your Servlet;
use browser debugger to tell if the response text is desired one;
for your issue I think you need to
change
document.fname.message.innerHTML=xmlhttp.responseText;
to
document.getElementById("message").innerHTML = xmlhttp.responseText;
Also remember Close your ouputstream
Related
I use Servlet 3.0, PrimeFaces 6.0, WildFly 8.2, Eclipse Neon, Mozilla or Chrome browsers. Despite following these nice links below:
Oracle Tutorial on File Upload
GitHub: getting the original file name example
I am still not able to determine the actual file name of an uploaded file. My problem is that in the below mentioned servlet the method call:
String fileNamer = getFileName(filePart);
gives me back NULL for the file name, i.e. fileNamer is null. What am I doing wrong? Please help:
1.) Here is my controller (servlet):
#WebServlet("/fileUpload")
#MultipartConfig
public class ImageUploadServlet extends HttpServlet {
private String getFileName(Part part) {
for (String cd : part.getHeader("content-disposition").split(";")) {
if (cd.trim().startsWith("filename")) {
return cd.substring(cd.indexOf('=') + 1).trim()
.replace("\"", "");
}
}
return null;
}
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {
HttpSession session = request.getSession(false);
Long savedKundeId = (Long) session.getAttribute(NewCustomerBean.SESSION_ATTRIBUTE_CUST_ID);
Part filePart = null;
PrintWriter pw = null;
try {
filePart = request.getPart("uploadImageForNewCustomerformId");
String fileNamer = getFileName(filePart);
// rest of code not shown here
2.) My view (Prime Faces 6.0 facelet):
<h:form id="newCustomerformId">
<!-- rest of code not shown -->
<p:commandButton type="submit" value="Create Customer"
icon="ui-icon-check"
actionListener="#{newCustomerBean.saveNewCustomer}"
update = "#form"
oncomplete="ajaxUploadFile();"/>
</h:form>
<h:form id="uploadImageForNewCustomerformId"
enctype="multipart/form-data">
<div id="dropzone">
<img id="librarypreview" src='' alt='library'
style="width: 280px; height: 160 px;" /> <select name="top5"
id="flist" size="5" onchange="previewFile()">
</select>
<output id="list"> </output>
</div>
<input id="fileInput" type="file" name = "file"></input>
<span id="uploadStatusId"></span>
</h:form>
3.) My Java Scipt function for ajax-uploading the file:
function ajaxUploadFile() {
var form = document.getElementById('uploadImageForNewCustomerformId');
if (form == null)
return;
var formData = new FormData(form);
for (var i = 0; i < fileList.length; i ++){
//append a File to the FormData object
formData.append("file", fileList[i], fileList[i].name);
}
var uploadStatusOutput = document.getElementById("uploadStatusId");
var request = new XMLHttpRequest();
request.open("POST", "/javakurs3-biliothek-jsf-mobile/fileUpload");
request.responseType = 'text';
request.onload = function(oEvent) {
if (request.readyState === request.DONE) {
if (request.status === 200) {
if (request.responseText == "OK") {
form.action = "/javakurs3-biliothek-jsf-mobile/pages/customers.jsf";
form.submit();
return;
}
}
uploadStatusOutput.innerHTML = "Error uploading image";
} // request.readyState === request.DONE
}; // function (oEvent)
request.send(formData);
};
I was finally was able to solve the problem. As BalusC correctly put it, I am not only doing a preview of the image using Java Script, but also uploading it using Java script. This caused confusion, as PrimeFaces supports an image preview and an image upload using their custom, own tag, as shown here .
p:fileUpload showcase
The problem using this p:fileUpload is that it has its own button for the image submission, or upload. However, I want to both submit my newly entered customer data AND upload the image using EXACTLY ONE button and button click.
The solution to my requirement is that I used the following code in my ImageUploadServlet
for (Part fPart : request.getParts()){
if (fPart.getName()!=null && fPart.getName().equals("file") && StringUtils.isNotEmpty(fPart.getSubmittedFileName())){
fileNamer = fPart.getSubmittedFileName();
filePart = fPart;
break;
}
}
instead of the code I mentioned in my question:
private String getFileName(Part part) {
for (String cd : part.getHeader("content-disposition").split(";")) {
if (cd.trim().startsWith("filename")) {
return cd.substring(cd.indexOf('=') + 1).trim()
.replace("\"", "");
}
}
return null;
}
My aim is to provide the ability to sending comments or reviews on the site. When I get the parameter from the form they are properly added to my reviews database. But the problem is that the URL contains the paramaters. So when I fill the form and press the submit button, there are a new record in the database, but the comment is not shown on the page at once. Also when I refresh the page, the same record is duplicated in the database. I want user to fill the forms, press the button and then redirect to the same page with his comment or review. Here is my servlet doGet method code:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
Query query = new Query();
Object allReviews = query.getAllReviews();
request.setAttribute("allReviews", allReviews);
RequestDispatcher rd = request.getRequestDispatcher("reviews.jsp");
rd.forward(request, response);
if (request.getParameter("sendReviewButton") != null){
String userName = request.getParameter("reviewName");
String eMail = request.getParameter("reviewMail");
String reviewList = request.getParameter("reviewText");
query.addReview(userName, eMail, reviewList);
}
}
And my form in jsp:
<form action = "${pageContext.request.contextPath}/Reviews" method="get">
<p>Your name: <input type="text" size="107" name="reviewName" required></p>
<p>Your e-mail: <input type="text" size="90" name="reviewMail" required></p>
<p>Your review:</p>
<p><textarea rows="15" cols="135" name="reviewText" ></textarea></p>
<input type="submit" value="Send" name="sendReviewButton" class="btn btn-primary btn-lg" id="send-btn">
</form>
you should probably use POST and not GET, so that the data is not seen on the URL and the browser warns the user if she reloads the page
Add the new review before you get the list of reviews, so you get the updated list
use sendRedirect to the reviews.jsp page so that the url is the short one. This should render point 2 moot as you're going to list the review after you've added the new one.
I added the else statement. So the new review is correctly added, it is shown on the page immediately. When I refresh the page the record in the database is NOT duplicated:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
Query query = new Query();
if (request.getParameter("sendReviewButton") != null){
String userName = request.getParameter("reviewName");
String eMail = request.getParameter("reviewMail");
String reviewList = request.getParameter("reviewText");
query.addReview(userName, eMail, reviewList);
Object allReviews = query.getAllReviews();
request.setAttribute("allReviews", allReviews);
response.sendRedirect("/ScopeSoftware/Reviews");
}else {
Object allReviews = query.getAllReviews();
request.setAttribute("allReviews", allReviews);
RequestDispatcher rd = request.getRequestDispatcher("reviews.jsp");
rd.forward(request, response);
}
}
You are forwarding to the JSP page, but this does not solve the refresh problem. The solution is - as you already said in your question - to redirect to the JSP:
response.sendRedirect("reviews.jsp"); // url of the JSP page.
This sends a HTTP redirect back to the browser and the browser then does a new GET to reviews.jsp.
how to get servlet response message in javascript variable is there any possible way to get response message in java script?
Html:
<form method="post" id="importForm">
Name<input type="text" name="name"/>
<input type="submit" onclick="importScenarioFromServer();">
</form>
javascript:
function importScenarioFromServer(){
var result = document.forms["importForm"].submit();
}
servlet:
int numberOfRecs = db.setDBValue(dMap);
if (numberOfRecs == 1) {
String result = "success";
response.getWriter().print(result);
}
This can be implemented using ajax either in javascript or by using jquery.
we can serialise form in ajax hit and then can get response data from servlet in success event callback function. below is example...
function getData()
{
var client;
var data;
var url_action="/temp/getData";
if(window.XMLHttpRequest)
{
client=new XMLHttpRequest();
}
else
{
client=new ActiveXObject("Microsoft.XMLHTTP");
}
client.onreadystatechange=function()
{
if (client.readyState==4 && client.status==200)
{
document.getElementById("response").innerHTML=client.responseText;
}
};
data="name="+document.getElementById("name").value+"&file="+document.getElementById("filname").value;
client.open("POST",url_action,true);
client.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
client.send(data);
}
Servlet post method
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out=response.getWriter();
log.info("Good");
out.println("Good to go");
}
I have a html page and a java application with Thymeleaf templating engine and I'm looking for a tutorial to make a request to the server and render only part of the page based on response.
At this moment, I have some buttons having a link of the same page with a different parameter, my div is created based on attribute articleList (which I receive from the server based on button_id)
HTML:
button 1
button 2
<div class="" th:each="article : ${articleList}">
<p th:text="${article.getText()}">Article</p>
Java:
public class NodController implements IGTVGController {
public void process(
final HttpServletRequest request, final HttpServletResponse response,
final ServletContext servletContext, final TemplateEngine templateEngine)
throws Exception {
final WebContext ctx = new WebContext(request, response, servletContext, request.getLocale());
Integer button_id = Integer.valueOf(request.getParameter("button_id"));
List<String> articleList = getArticleList(button_id);
request.getSession().setAttribute("articleList",articleList);
templateEngine.process("/index", ctx, response.getWriter());
}
I want my buttons to process my index controller and only change the div with the articles and not refresh the entire page.
I have tried using ajax but I didn't find code examples for server-side that I could understand, so I don't know how to process the request and I don't know how to use servlets. Also I didn't manage to send any request to my current controller.
I have also found in thymeleaf api this method:
public final void process(String templateName, IContext context,
IFragmentSpec fragmentSpec, Writer writer)
where IFragmentSpec should "select a fragment of a template to be processed (once read and parsed), discarding the rest of the template" but I couldn't find more information about it as how to use it or if it is what I'm looking for.
this is the javascript code
//get text 1 by ajax
function getText1(urlstarted) {
xmlHttp = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
xmlHttp = new XMLHttpRequest();
if (xmlHttp.overrideMimeType) {
// set type accordingly to anticipated content type
//http_request.overrideMimeType('text/xml');
xmlHttp.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) { // IE
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!xmlHttp) {
alert('Cannot create XMLHTTP instance');
return false;
}
var url=urlstarted+"/jsp/viewText1.jsp"; //put the link to ur Ajax page here
xmlHttp.onreadystatechange = startAjaxingText;
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
function startAjaxingText() {
if (xmlHttp.readyState != 4) {
document.getElementById('image').style.display='block' ;
document.getElementById('result').style.display='none' ;
}
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
document.getElementById('image').style.display='none' ;
document.getElementById('result').style.display='block';
document.getElementById('result').innerHTML = xmlHttp.responseText;
} else {
alert("There was a problem with the request.");
}
}
}
//get text 2 by ajax
function getText2(urlstarted) {
xmlHttp = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
xmlHttp = new XMLHttpRequest();
if (xmlHttp.overrideMimeType) {
// set type accordingly to anticipated content type
//http_request.overrideMimeType('text/xml');
xmlHttp.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) { // IE
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!xmlHttp) {
alert('Cannot create XMLHTTP instance');
return false;
}
var url=urlstarted+"/jsp/viewText2.jsp"; //put the link to ur Ajax page here
xmlHttp.onreadystatechange = startAjaxingText2;
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
function startAjaxingText2() {
if (xmlHttp.readyState != 4) {
document.getElementById('image').style.display='block' ;
document.getElementById('result').style.display='none' ;
}
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
document.getElementById('image').style.display='none' ;
document.getElementById('result').style.display='block';
document.getElementById('result').innerHTML = xmlHttp.responseText;
} else {
alert("There was a problem with the request.");
}
}
}
now your buttons will look like this
<input name="button_1" id="button_1" type="button" value="button_1" onclick="getText1('<%=request.getContextPath()%>');" />
<input name="button_2" id="button_2" type="button" value="button_2"
onclick="getText2('<%=request.getContextPath()%>');" />
your div will look like
<div id="image" style="display:none"><img src="<%= request.getContextPath()%>/images/ajax-loader.gif" alt="Loading...."/> </div>
<div id="result" style="display:none"></div></td>
your viewText1.jsp page that doing ajax part
out.println("text1");//or any logic u want
your viewText2.jsp page that doing ajax part
out.println("text2");//or any logic u want
note that : the result of viewText1.jsp or viewText2.jsp must be a text either a table or paragraphs
Client-side implementation
You will have to use AJAX to load content from the server dynamically.
Consider designing your frontend as SPA. Look into AngularJS or Knockout.
Also, you can use old-school approach by using something like jQuery AJAX if this is just a small area of your application.
Separation of concerns
I strongly suggest to consider the idea to separate concerns by using server as a REST service and frontend as a client. This is the best practice for large applications if you want to keep them maintainable and scalable.
You should look for tutorials of how to implement REST with your server-side technology. It's very common practice so I think you should be able to find one.
If you have any questions I will be glad to update this answer.
I have a form on my jsp page. In this form i choose a file (zip archive) and after click submmit call servlet to upload this file. For file upload im use Apache Commons FileUlpoad library. After upload im unzip archive. Them i do redict to this jsp.
jsp code:
<form action="Upload_Servlet" method="post" enctype="multipart/form-data">
<div id="up">
<input id="fileUpload1" type="file" name="filename1"value="Browse..."/>
</div>
<div>
<input id="btnSubmit" type="submit" value="Загрузить">
<input type="button" id="del" onclick="deleting()" value="Удалить">
</div>
</form>
servlet code:
public class uploadfile extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
System.out.println(response.getCharacterEncoding());
response.setCharacterEncoding("UTF-8");
System.out.println(response.getCharacterEncoding());
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
writer.println("wtpwebapps<br/>");
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) {
writer.println("<HTML>");
writer.println("<HEAD <TITLE> Upload4 </TITLE> </HEAD>");
writer.println("<BODY>");
writer.println("<FORM action = \"Upload_Servlet\" method = \"post\" enctype = \"multipart/form-data\">");
writer.println("<INPUT type = file name = ufile>");
writer.println("<INPUT type = submit value = \"Attach\">");
writer.println("<h1>its not multipart</h1>");
writer.println("</FORM>");
writer.println("</BODY>");
writer.println("</HTML>");
return;
}
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> list=null;
String mifpath= "1";
String path = " ";
String mif = " ";
String from = "\\\\";
String to ="/";
String error="";
try{
list = upload.parseRequest(request);
Iterator<FileItem> it = list.iterator();
response.setContentType("text/html");
while ( it.hasNext() )
{
FileItem item = (FileItem) it.next();
File disk = new File("C:/uploaded_files/"+item.getName());
path = disk.toString();
String code = new String(path.substring(path.lastIndexOf("."), path.length()).getBytes("ISO-8859-1"),"utf-8");
if (code.equalsIgnoreCase(".zip"))
{
mifpath=path;
mif = mifpath.replaceAll(from, to);
item.write(disk);
error=unzip.unpack(mif, "C:/uploaded_files");
}
else
{
error = "Выбранный файл не является архивом zip";
}
}
}
catch ( Exception e ) {
log( "Upload Error" , e);
}
request.setAttribute("error", error);
request.getRequestDispatcher("/Home.jsp").forward(request, response);
// String redictedURL="http://localhost:8080/redicted_test/Home.jsp";
// response.sendRedirect(redictedURL);
writer.close();
}
}
Now i want to do this on the portal. Its mean that i dont want to reload my jsp after I upload a file. So i have to use Jquery. And i have some questions:
How to submit form to use jquery in my case?
My servlet code will be work in portlet?
How to send parametrs to jps from portlet?
Using Jquery it can be done easily:
Set a click event on the submit button (or on the form submit).
Post data to servlet:
$.ajax({
url : base_url + 'Upload_Servlet',
type : "post",
data:$('form').serialize(),
cache : false,
success : function(data) {
//do some stuff
},
error : function(xhr, status, err) {
//do error stuff
},
timeout : 3000
});
//End ajax call
After the servlet is done, just use the response writer to write an aswer back (If it contains a lot of data, I'd recommend sending a response in the form of json, see here) and then the success callback is called and you can do whatever you like with this data.
IMPORTANT: Since you are submitting a form, you need to use e.preventDefault() so the form will not be actually submitted but rather be handeled by your ajax.