i have written a small code which inclued 2 jsp pages and
1) test2.jsp --> i have made a dropdown in this page
2) test3.jsp --> displays a welcome message when the person selects an option from the dropdown ,
he will migrate to this page without refreshing test2.jsp
for this i have used ajax jquery
when i click on the submit button nothing happens , please help me with this
i have also put the org.json.jar file in the libraries
test2.jsp code
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//malsup.github.com/jquery.form.js"></script>
<script>
function check()
{
$.ajax({
url: "test3.jsp",
type: "GET",
success: function() {
alert("succes");
},
error: function() {
alert( "Sorry, there was a problem!" );
}
});
}
</script>
</head>
<body>
<h1>Hello World!</h1>
<br>
<form method="post" action="test2.jsp">
<select name="city">
<option value="dropdown">select city</option>
<option value="jal">Jalandhar</option>
<option value="ggn">Gurgaon</option>
<option value="noida">Noida</option>
<option value="amrtsr">Amritsar</option>
<option value="bombay">Bombay</option>
</select>
<input type="submit" value="Submit" onclick="check()">
</form>
test3.jsp code
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>welcome</h1>
</body>
</html>
The function should return false to prevent form submittion
<script>
function check() {
$.ajax({
url: "test3.jsp",
type: "GET",
success: function() {
alert("succes");
},
error: function() {
alert( "Sorry, there was a problem!" );
}
});
return false;
}
</script>
It should be
<input type="button" value="Submit" onclick="check()">
instead of
<input type="submit" value="Submit" onclick="check()">
because submit input type call form's action that is test2.jsp.
call your javascript function on change event of drop down
onchange="check()"
and navigate through firebug and check your consol it will show you your whole ajax request
Related
I'm develop simple Spring boot app using Thymeleaf and want to display selected "user" from Combobox1 at the "userName" text field. How i can made it?
<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<title>Добавить цитату</title>
</head>
<body>
<form th:action="#{/addQuote}"
th:object="${personForm}" method="POST">
<p><b>Имя</b><br>
<div>
<input name = "userName" type="text" size="38" th:field="*{name}" >
<a style="position:fixed;left:0px;top:0px;margin: 0;border-width:0;z-
index:255"></a>
</div>
<textarea name="comment" cols="40" rows="6" th:field="*{text}" >
</textarea>
<p><input type="reset" value="Отменить">
<input type="submit" value="+"></p>
<select name="Combobox1" size="1" id="Combobox1"
style="position:absolute;left:17%;top:4%;width:199px;height:20px;z-
index:3;" >
<option th:each="user : ${users}"
th:value="${user}"
th:utext="${user}"/>
</select>
</form>
<div th:if="${errorMessage}" th:utext="${errorMessage}"
style="color:red;font-style:italic;">
</div>
</body>
</html>
Option 1:
Add Id in your userName input tag
<input id="userName" name = "userName" type="text" size="38" th:field="*{name}" />
Add script
<script>
function check() {
document.getElementById("userName").value=document.getElementById("Combobox1").value;
}
</script>
Call script function
<select id="Combobox1" onChange="check();">
Option2:
Another option with Jquery
$(function() {
$("#Combobox1").on("change",function() {
alert();
$("#userName").val($(this).val());
});
});
Last few hours i am trying to solve this but i can not.I am sending ajax request using jquery and based on response i set data on jsp.actully i am checking login detail so if login fail it set error message on label problem is that error message is set for few second and removed i mean to say error message is set for few second i want that if login fails the message is set on label still user enter valid details
thanks in advance
Here is my code
LoginDemo.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<link href="css/firstpage.css" rel="stylesheet" type="text/css" /><!-- <style> -->
<script src="js/jquery.min.js"></script>
<title>Insert title here</title>
<script>
$(document).ready(function(){
$("#submit").click(function(){
$.ajax({
type: "POST",
url: "AddInspServlet",
cache:false,
data: { userid: $('#username').val(), password: $('#password').val(),btn:$('#submit').val() },
success:function(data,textstaus){
alert("success:"+data);
if(data == "no"){
alert( document.getElementById("error").innerHTML);
document.getElementById("error").innerHTML= "UserName OR Password is incorrect";
alert( document.getElementById("error").innerHTML);
}else{
location.href = 'Home.jsp';
}
},
error:function(data){
alert("error"+data);
},
});
});
});
</script>
</head>
<body>
<form id="login" name="Loginform" method="post">
<h1><b>Log In</b></h1>
<fieldset id="inputs">
<input id="username" type="text" placeholder="Username" autofocus required>
<input id="password" type="password" placeholder="Password" required>
</fieldset>
<fieldset id="actions">
<input type="submit" id="submit" value="login">
Forgot your password?
</fieldset>
<label id="error" style="color: red;font: bolder; font-size: 18px;">
</label>
</form>
</body>
AddInspServlet
Here i m adding code which server executed and retrieve response
if(btn.equals("login"))
{
System.out.println("***** login condition checking ******");
String password =request.getParameter("password");
UserVO v =op.loginCheck(username, password);
if(password.equals(v.getPassword()))
{
System.out.println("inside true condition");
HttpSession session = request.getSession();
session.setAttribute("userid",v.getUser_id());
session.setAttribute("username",v.getUsername());
session.setAttribute("user", v.getFirst_name()+" "+v.getLast_name());
session.setAttribute("roleid", v.getRole_id());
// response.sendRedirect("Home.jsp");
System.out.println("submitting data success fully");
out.print("yes");
}
else
{
System.out.println("false condition");
out.print("no");
}
}
Get rid of the form tags.
By adding a type="submit" input element without using the action attribute in the form tag, the page will be reloaded.
Or you could keep the form tags and change the type of the submit button to type="button". The form will then not be executed and the page will not reload.
It would be better if you be more specific about the problem. I assume your problem is Label is getting displayed for few seconds and then get disappeared. Is that is true? then try to return "false" inside you data == "no" logic.
Thanks.
code:
<script type="text/javascript">
function showFileName() {
var filename = document.getElementById("uploadFile");
}
</script>
OR
<script type="text/javascript">
var filename = document.getElementById("uploadFile");
</script>
OR
var filename="uploadedfilename";
<form name="AttachmentsForm" method="post" action="<%=Constants.WEB_APP_NAME%><%=Constants.SERVLET_NAME%>?para=ajaxRefTabUpload&action=add&uploadfilename="+filename+"" ENCTYPE="multipart/form-data">
<table class="innerBorderTable" width="100%">
<tr>
<td>Attach New File:</td>
<td>
<INPUT TYPE="FILE" NAME="uploadFile" width="120">
<input type="submit" class="button" value="Add Attachment">
</td>
</tr>
</table>
</form>
I tried 3 different approaches to pass it with +filename+ i am getting null with uploadfilename in action parameter
Please advise
use of scriptlets(<% %>) in JSP highly discouraged, use JSTL(<c:tags) or Expression Language(${})
to use JSTL in your jsp download jstl.x.x.jar file and add it to your buildpath.
then, add this
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
in top of jsp.
to resolve form action url you have:
<%=Constants.WEB_APP_NAME%><%=Constants.SERVLET_NAME%>
no need of any constants for that, instead use <c:url tag to resolve url like:
<c:url value="/yourServletUrl" var="postUrl"/>
<form action="${postUrl}" method="post" ...
i am getting null with uploadfilename in action parameter
because, you accessing javascript variable in html(&uploadfilename="+filename+"), instead do like:
jsp:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<title>your title</title>
</head>
<body>
<c:url value="/yourServletUrl" var="postUrl"/>
<form id="AttachmentsForm"
method="post"
onSubmit="showFileName()"
action="${postUrl}para=ajaxRefTabUpload&action=add"
enctype="multipart/form-data">
<table class="innerBorderTable" width="100%">
<tr>
<td>Attach New File:</td>
<td>
<input type="file" name="uploadFile" width="120">
<input type="submit" class="button" value="Add Attachment">
</td>
</tr>
</table>
</form>
<script type="text/javascript">
function showFileName(e) {
if (e.preventDefault)
e.preventDefault();
var filename = document.getElementById("uploadFile");
alert('fileName: '+filename);
//here, attach filename to from action and continue your form submition by AJAX
// You must return false to prevent the default form behavior
return false;
}
}
</script>
</body>
</html>
Try something like:
function showFileName() {
document.forms[0].action ="<%=Constants.WEB_APP_NAME%>... //Here goes the expression you want to set the action to
}
I am new to ajax and jquery and trying to place an ajax call in my code. But below are the error messages I get when placing alerts:
jqxhr.status = 404
thrown error = Not Found
jqxhr.statusText = Not Found
request = undefined
error = undefined
What I want to do:
Open a modal dialog with just a Fancy text box (Tinymce) on click of an "Edit gif". After the contents are edited in the textbox, and the "Save" button in the modal dialog is clicked, initiate an ajax call to save the contents in the Database.
What is happening:
The modal dialog opens correctly, I am able to see that the "data" part for the ajax call is populated correctly (placed alerts to confirm). I believe the url is also correct. If I type the url in a browser, the control does go to my servlet as per web.xml (Sysout in Servlet gets printed). But somehow, the ajax call never goes through to the server after click of "Save" button. Will be really great if one of you can help me out here, will greatly appreciate it. My JSP (copied what I feel is relevant alone):
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<link rel="stylesheet" type="text/css" href="css/sis.css" media="screen" />
<link rel="stylesheet" type="text/css" href="<%=request.getContextPath()%>/css/jquery-ui-1.10.3.custom">
<script type="text/javascript" src="<%=request.getContextPath()%>/js/jquery.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/jquery-ui.min.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/tinymce/tinymce.min.js"></script>
<script>
$(function() {
$("#dialog-form2").dialog({
autoOpen: false, width: 500, modal: true,
buttons: {
"Save": function() {
tinymce.get("stChallenge").setContent(tinyMCE.get("edChallenge").getContent());
alert($("#ChalId").val());
alert(tinyMCE.get("edChallenge").getContent());
var xhr =
$.ajax({
url: "/AjaxServlet?method=updateChal&keyword=dummy",
type: "GET",
data: {
CommentId: $("#ChalId").val(),
challenge: tinyMCE.get("edChallenge").getContent()
},
success: function (result) {
alert("Success :" + result);
$(this).dialog("close");
},
error:function (jqxhr, ajaxOptions, thrownError, request, error) {
alert('jqxhr.status = ' + jqxhr.status + '\n' + 'thrown error = ' + thrownError + '\n' + 'jqxhr.statusText = ' + jqxhr.statusText + '\n' +
'request = ' + request + '\n' + 'error = ' + error);
$(this).dialog("close");
}
});
},
Cancel: function() {
$(this).dialog("close");
}
},
close: function() {
}
});
$("#Edit2")
.click(function() {
$("#dialog-form2").dialog("open");
});
});
</script>
<script type="text/javascript">
tinymce.init({
selector: "#edChallenge", theme: "modern",
plugins: [
],
image_advtab: false
});
</script>
<script type="text/javascript">
tinymce.init({
selector: "#stChallenge", theme: "modern", readonly: true, toolbar: "false", menubar: "false",
plugins: [
],
image_advtab: false
});
</script>
</head>
<body>
<c:set var="model" value="${sessionScope.model}" />
<html:form action="managePerf.do?method=showPerf" method="post" styleId="ManagePerfForm">
<html:errors/>
Date: <html:text property="rankDate" styleId="datepicker" name="ManagePerfForm" />
<html:submit value="Go" styleClass="input button"/>
<fieldset>
<table border="0">
<tr>
<td>
<div id="dialog-form2" title="Edit Challenges">
<form>
<textarea cols="75" rows="50" id="edChallenge">${comments}</textarea>
</form>
</div>
<label>Challenges</label>
<a href="javascript:void(0);" id="Edit2">
<img src='${pageContext.request.contextPath}/img/Edit.gif' height="32" width="32"/>
</a>
<div id="dTextBox" class="ui-widget">
<textarea cols="75" rows="15" id="stChallenge" readonly="true">${comments}</textarea>
</div>
<input type="hidden" id="ChalId" value=${CommentId} />
</td>
</tr>
</table>
</fieldset>
</html:form>
</body>
There is a simple web page which sends request, handles & manipulated by a servlet class and send back the response text.while i want ajax type handleing the request at client side that is why i am giving the response target to a invsible iframe. *but i want to print success on the page after iframe gets the response *
<html> <body>
<form action="test" method="post" target="IFrame"> /*response target is iframe*/
<input type="text" name="logic" />
<input type="submit" value="Submit" />
</form>
<iframe name="IFrame" style="width:0; height:0"> </iframe>
</body> </html>
i think this can be done using javascript or jquery, please guid me if you have any idea.
In the page which loads in the iframe, you will need to invoke a parent function.
<!-- This is the Parent. Call it JSTest1.html -->
<html>
<head>
</head>
<body>
<script type="text/javascript">
function parentAlert() {
alert('hey there from the parent');
}
</script>
I'm the parent
<iframe src="/JSTest2.html"></iframe>
</body>
<!-- this is the iframe html loaded. Call it JSTest2.html-->
<html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready( function() {
window.parent.parentAlert();
});
</script>
In the Iframe.
</body>
To send a message from Iframe to Parent window page:
<script type="text/javascript">
$(document).ready( function() {
//Message part is two parts Event name and Data you want to send
// Example message = "my_action,my_data"
message = "my_action,my_data"
parent.postMessage(message, "*");
});
</script>
At the parent window you can do the following to listen to this message and capture it:
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventer(messageEvent,function(e) {
// Youe message which you send is captured here in e.data will split it on ',' to get the event and the data
message = e.data.split(',')[0]
value = e.data.split(',')[1]
if ( message === "my_action" ) {
myParentFunction(value)
}
},false);