how can get response from <form target="IFrame"> - java

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);

Related

Submit AJAX and Springboot values

I want to send the URI value to the database using AJAX and the request is written in #Controller. But when I hit submit there's nothing in the database.
For example I have the address:
http://localhost:8080/post/view/2
As above I want to save value 2 to my database every time I click submit. I have tried but nothing
#Controller
#RequestMapping(value="post/view/{id}", method= RequestMethod.POST, produces = "apllication/json")
public #ResponseBody Comment newComment (#RequestParam(name="id") Long id) {
Comment comment = new Comment();
Post postView = postService.findById(id);
comment.setPoster(postView);
commentService.create(comment);
return comment;
}
And my code HTML
view.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head >
<script type="text/javascript" language="javascript"
src="https://www.technicalkeeda.com/js/javascripts/plugin/jquery.js"></script>
<script type="text/javascript"
src="https://www.technicalkeeda.com/js/javascripts/plugin/json2.js">
</script>
<title th:text="${postView.title}">View Post</title>
<script >
function madeAjaxCall(){
$.ajax({
type: "post",
url: "http://localhost:3313/post/view/{id}"
}
</script>
</head>
<body>
<div>
<form method="post" >
<main id="posts">
<article>
<h2 class="title" th:text="${postView.title}">Post Title</h2>
<div class="date">
<i>Posted on</i>
<span th:if="${postView.author}" th:remove="tag">
<i>by</i>
<span th:text="${ postView.author.lastName}">Svetlin Nakov</span>
</span>
</div>
</article>
<input type="button" value="Ajax Submit" onclick="madeAjaxCall();"/>
</main>
</form>
</div>
</body>
</html>
I think I was wrong or missing something at AJAX or #Controller. Thank you
try using #PathVariable instead of #RequestParam
I noticed several things that are wrong in your code:
https://www.technicalkeeda.com/js/javascripts/plugin/jquery.js this link is invalid. Try using jQuery from the official site: https://code.jquery.com/jquery-3.5.1.js
This might not be your server url url: "http://localhost:3313/post/view/{id}". Please confirm the port is 3313 and provide a valid value for {id}. Also, you don't need to use the port and url at all. See my code below:
produces = "apllication/json" you have typo here. Just change it to produces = MediaType.APPLICATION_JSON_VALUE
You are using #RequestParam but your request has the id parameter in path. Lookup the difference between the #RequestParam and #PathParam.
(#RequestParam(name="id") Long id) { You should be using #PathVariable
Here's a working code:
Backend controller:
#PostMapping(value = "/post/view/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody
void newComment(#PathVariable Long id) {
System.out.println("Requested with id = " + id);
}
Frontend:
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<body>
<script>
function madeAjaxCall() {
$.ajax({
type: "post",
url: "/post/view/5"
})
}
</script>
<input type="button" value="Ajax Submit" onclick="madeAjaxCall();"/>
</body>
</html>

Set Ajax response on jsp not working

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.

how to use jquery ajax in jsp ?

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

Unable to initiate ajax call from jquery

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>

Disable jQuery event if Textbox is in focus

I want to disable the jQuery event if a Text box is in focus. I am using following code. If a user is entering any text in text field then if by change the cursor moves to the image then it will reset the text in text field to the value shoot by event. I don't want to the event to execute if text field is in focus.
<!DOCTYPE html>
<html>
<head>
<style>span {display:none;}</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<input type="text" id="team" />
<script>
$("input").focusin(function() {
document.getElementById("team").value = "I am in Focus Dont shoot events PLZ";
}
);
$(document).ready(function() {
$("img").mouseover(function(event) {
if(event.target.name != '')
{
document.getElementById("team").value = event.target.name;
}
//alert(event.target.name);
});
});
</script>
<img src="http://1.bp.blogspot.com/-bVD6mGlH_ik/TnHV75bw9KI/AAAAAAAAB84/1hJU7WJuU8k/s400/fewr.jpg" name="I" />
</body>
</html>
I have already tried following function
$("input").focusin(function() {
document.getElementById("team").value = "I am in Focus Dont shoot events PLZ";
});
Now I am using below code but still not working. Please help me.
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<img src="http://1.bp.blogspot.com/-bVD6mGlH_ik/TnHV75bw9KI/AAAAAAAAB84/1hJU7WJuU8k/s400/fewr.jpg" name="Ihhhhhhhhhhhhhhh" id="myimage" />
<input id="theone">
<input type="image" src="http://www.clker.com/cliparts/e/2/a/d/1206574733930851359Ryan_Taylor_Green_Tick.svg.thumb.png" id="bind">
<input type="image" src="http://www.clker.com/cliparts/4/3/1/f/1195436930767206781not_ok_mark_h_kon_l_vdal_01.svg.thumb.png" id="unbind">
<script>
$("#unbind").click(function(event) {
$("img").off();
alert("off");
});
$("#bind").click(function(event) {
$("img").on();
alert("on");
});
$("img").mouseover(function(event) {
if(event.target.name != '')
{
document.getElementById("theone").value = "done";
}
//alert(event.target.name);
});
</script>
</body>
</html>
Just put one condition in mousehover event...
Enter Text in text box if textbox is not focus using this code !$("#team").is(":focus")
here is the demo : http://jsfiddle.net/s8zxY/1/

Categories