AJAX using Jquery not working across JSP pages - javascript

I am developing a dynamic web application using the following technologies on Eclipse Luna : JSP for server-side scripting, Apache Tomcat v7.0, Oracle 11g as my database and Jquery.
Below is my first .jsp page which is an elementary registration page :
<%# 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>
<link type="text/css" rel="stylesheet" href="stylesheet.css"/>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="ValidateRegister.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome</title>
</head>
<body>
<%#include file="Home.jsp" %> <br/>
<div id="form">
<form id="login" action="RegisterProcess.jsp" method="post" name="login">
<table>
<tr><td>User Name</td><td><input type="text" name="uname"/><br/></td><td><p id="unamecheck"></p></td></tr>
<tr><td>Email ID</td><td><input type="text" name="uemail"/><br/></td><td></td></tr>
<tr><td>Password</td><td><input type="password" name="upass" /><br/></td><td></td></tr>
<tr><td></td><td><input type="submit" id="submit" value="Register"/></td><td></td></tr>
</table>
</form>
</div>
</body>
</html>
This page gathers user credentials and on form submission the following javascript is triggered:
$(document).ready(function() {
$('#submit').click(function() {
var result=validateForm();
if(result===false)
return result;
else
checkUsername();
});}
);
function validateForm()
{
//does usual validation like empty string etc..
}
function checkUsername()
{
$.ajax(
{
url:"RegisterProcess.jsp",
data:$("#login").serialize(),
type:"post",
dataType:"json",
success:function(data)
{
$("#unamecheck").text(data);
},
error: function( xhr, status, errorThrown ) {
alert( "Sorry, there was a problem!" + status + errorThrown);
console.log( "Error: " + errorThrown );
console.log( "Status: " + status );
console.dir( xhr );
},
complete:function(xhr,status)
{
alert( "The request is complete!" );
}
});
}
The jsp page being referenced is :
<%# 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">
<title>Processing</title>
</head>
<body>
<%#page import="bean.RegisterDao"%>
<jsp:useBean id="obj" class="bean.User"/>
<jsp:setProperty name="obj" property="*"/>
<%
final int status=RegisterDao.register(obj);
if(status>0)
out.print("You are successfully registered");
else
out.print("Username already exists!");
%>
</body>
</html>
When I press submit the form, I get the alert message :"Sorry, there was a problem!error" followed by "The request is complete!" and then I'm redirected to the page RegisterProcess.jsp, which outputs the correct thing :"Username already exists" or "Registration successful".
I have used Firebug to debug but could not decipher much. Any help would be much appreciated as I could not find any similar question been asked previously.

You appear to be confused about what the $.ajax call is actually doing. AJAX is a technology that allows browsers to make asynchronous HTTP calls to resources without requiring the entire browser page to be loaded. What you're doing in your $.ajax call is asking for the browser to submit the data from your form to the URL, RegisterProcess.jsp, and then to process the result in some way.
By specifying the data type of json in your $.ajax call, you're asking jQuery to treat the response from the server as a JSON object, but the RegisterProcess.jsp page renders as HTML. Therefore, the $.ajax call interprets the response as an error and displays the message accordingly.
The reason you're subsequently redirected to RegisterProcess.jsp in your browser is that you don't prevent the default submission of the registration form. One way of doing that is to issue a preventDefault() on the incoming event, or return false from your event handler.
Restructure your code so that you submit an $.ajax request to a resource that returns JSON, or remove the json data type specifier from the $.ajax call.

Take a look at how your form is set up. Upon submission, your form makes a POST to RegisterProcess.jsp here:
<form id="login" action="RegisterProcess.jsp" method="post" name="login">
Additionally, you're making a second POST using AJAX whenever the submit button is being pressed. More than likely, you've got a race condition.
The form's POST is completing first and issuing a redirect, which interrupts your AJAX's POST in JavaScript. I'll bet that if you look at what error is being thrown, it will be some form of interrupt exception.
Do you want to redirect your user to RegisterProcess.jsp? If not, remove the action and method from your <form> and let your AJAX call do the verifying.
Is the user supposed to be redirected to ReigsterProcess.jsp? If so, change your form to this and remove your AJAX call:
<form id="login" name="login" action="RegisterProcess.jsp" method="post" onsubmit="return validateForm();">
When clicking submit, now the form will first look for a true/false return from validateForm() before submitting the POST and redirecting to RegisterProcess.jsp.

Related

How to retrieve item from another localStorage Domain?

I'm working on a JAVA web application which plays the role of a search engine. Its backend is developed with AngularJS. And I have a small PHP code which tries to send a data from an input text to the JAVA web app via an iframe. the data is stocked in a localStorage.
Here is below the PHP Code :
index.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Search</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<script type="text/javascript">
function redirect(){
var toSearch = document.getElementById('wordToSearch').innerHTML;
console.log("toSearch : ", toSearch);
localStorage.setItem('wordToSearch', 'bdd');
window.location.href = "http://localhost:8050/searchEngine/#/search";
}
</script>
<form action="http://localhost:8050/searchEngine/#/search">
<input type="text" name="word" id="wordToSearch">
<input type="submit" value="Search" onclick="redirect()">
</form>
</body>
</html>
Precisely, I'm trying to retrieve the "wordToSearch" item value stored within the localStorage
Here is below the code where i add my iFrame to my application :
<iframe src='http://localhost:8040/test/index.php'></iframe>
This is the result i get in the developer tools :
Developer Tools Result
Can anyone help me please ?
So TL;DR, you're saying you want JavaScript code running on a page whose origin is http://localhost:8050 to access the localStorage for origin http://localhost:8040 (or vice-versa)?
You can't do that. Web storage is specific to the origin, which includes the port.
You can do it using cookie, set value to http://localhost:8050 and get value from http://localhost:8040. Visit https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie

How to keep a track of a website for a particular browser in a particular session

1.How to find that your website is being hit in the next tab of the same browser?
2. How to prevent the website from being opened in the second tab?
If the browser first calls your site, you create a session on server side which results in sending the session cookie to the browser. In your HTML you can embed a hidden form value. This hidden value must be included in every subsequent call. Best is to use always POST so that the hidden value isn't included in the URL.
If the user opens a second tab and want to open a URL of your site the hidden parameter is not included but the session cookie from the first tab is.
So at server side you know there is already a session but the hidden value is missing. So you can send a totally different response.
Update
Here a small example.
In web content folder there is a subfolder protected. All included JSP files should only be opened in one tab. Here there is only MyJsp.jsp.
In the root folder there are two JSPs: error.jsp which is displayed when someone is trying to open a protected JSP in a second tab. And index.jsp which redirects to protected/MyJsp.jsp.
And there is a servlet filter mapped to the protected folder. This filter will be called before executing the JSPs in this folder.
protected/MyJsp.jsp:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
<p>Hello,
<c:choose>
<c:when test="${not empty param.name}">
<c:out value="${param.name}" />.
</c:when>
<c:otherwise>
stranger.
</c:otherwise>
</c:choose>
</p>
<form method="post">
<label>Please enter your name</label>
<input id="name" name="name" type="text"/>
<input id="marker" name="marker" type="hidden"
value="<c:out value="${sessionScope.marker}"/>"/>
<button type="submit">OK</button>
</form>
</body>
</html>
This JSP is asking for a name. Form submit calls the same JSP via POST. The hidden field is filled with a value from the session.
index.jsp:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!--include the library-->
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:redirect url="protected/MyJsp.jsp"/>
The servlet filter:
#WebFilter("/protected/*")
public class OneTabFilter implements Filter {
private static final String MARKER_NAME = "marker";
private static final String MARKER_VALUE = "4711*0815";
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
final HttpServletRequest req = (HttpServletRequest) request;
final HttpServletResponse rsp = (HttpServletResponse) response;
HttpSession session = req.getSession(false);
if(session == null) {
session = req.getSession(true);
// Put the marker value into session so it is usable in JSP files.
session.setAttribute(MARKER_NAME, MARKER_VALUE);
// pass the request along the filter chain
chain.doFilter(request, response);
} else {
if(MARKER_VALUE.equals(req.getParameter(MARKER_NAME))) {
// pass the request along the filter chain
chain.doFilter(request, response);
} else {
// Redirect to the error page.
// The error page itself is not affected by this filter.
rsp.sendRedirect(req.getServletContext().getContextPath() + "/error.jsp");
}
}
}
// ...
}
Try it yourself!

Page Reload while clicking on the href link

I have a web application in which index.jsp is a welcome page. Index.jsp contains the UI code . And i have multiple html files which has the same href link . My problem is whenever I click on the link the UI is reloaded. So when the url is same, the UI should be maintained and the page should not be reloaded.
I am new to web application development . Please help me on this.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<div id="myform_sample1">
<a href="http://localhost:8080/app/index.jsp?file=filepath" target="http://localhost:8080/app/index.jsp?file=filepath">sample1<br>
</a>
</div>
<div id="myform_sample2">
<a href="http://localhost:8080/app/index.jsp?file=filepath" target="http://localhost:8080/app/index.jsp?file=filepath">sample2<br>
</a>
</div>
</body>
</html>
you can try this:
$.ajax({
url: "test.html",
cache: false,
success: function(html){
$("#results").append(html);
}
});
on a click event you can transfer values and get back through ajax without reloading ur UI
I think you might be looking for jQuery:load, get, ajax

How do I pass a variable through a hyperlink?

I would like to start off saying that I'm very new to programming. I am developing a site (www.example.com) that has multiple hyperlinks.
When a user visits my site I want all the links to be defaulted to the back office of another site (www.tvcmatrix.com/mhammonds) I use. How do I set the links to redirect to the query string value based on inputted text from a form that is on my site (www.example.com)?
In other words, if the url reads www.example.com/?user=abelliard, how do I make all the links on the site change to "www.tvcmatrix.com/abelliard"? If no query string is present, then I would like for the links to be www.tvcmatrix.com/mhammonds.
Here is a file on my site for the form called "form.asp"
<!DOCTYPE html>
<html>
<body>
<form action="viral.asp" method="get" name="input" target="_self">
Your TVC Matrix Associate ID: <input type="text" name="user" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
Here is the "viral.asp" file in the "form.asp" file.
<%# language="javascript"%>
<!DOCTYPE html>
<html>
<body>
<%
var id = Request.QueryString("user");
Response.Write("Your URL is: www.mca.com/?user=" + id)
%>
</body>
</html>
Here is the last file and front end of the site called "front.asp"
I have 'viral' and 'form' down packed. The main thing I needed help with was the front end of the site that deals with the links.
I have no clue if I am even a tad bit close or way off track, but what I have isn't working at all so I know it's wrong.
<!DOCTYPE html>
<html>
<head>
<title>Main Site</title>
</head>
<body>
Click Here!
<iframe width="450" height="40" src="form.asp">
</iframe>
</body>
<script lang="javascript" type="text/javascript">
function tvcid() {
var username = document.getElementById('username');
if (username.value != "") {
tvcid = "username";
}
else {
tvcid = "mhammonds";
}
}
</script>
</html>
How do I pass a variable through a hyperlink?
For staters, you're not using a hyperlink, you're submitting a form.
Request.QueryString("user"); is looking for something on the querystring. You're using POST, which has form fields.
Use Request("user");, which will grab the value regardless of whether it's on the querystring or a POST field. If you want to force recognition of form fields only, use Request.Form("user");
Classic ASP code is executed server side when the page loads. You are submitting a form inside an iframe, and the result page is also displayed inside the iframe. This result can't change anything on the parent page because it has already been loaded. The easiest way around this would be to have all your code on the same page. I'll show you how to do this with VBS as the scripting language, it's what I'm used to, but it should be easy enough to use server side JS instead
<%# language="VBScript"%>
<%
Dim id
If Request("user") <> "" then
id = Request("user")
else
id = "mhammonds"
End if
%>
<!DOCTYPE html>
<html>
<head>
<title>Main Site</title>
</head>
<body>
Click Here!<br />
<% If Request("Submit") <> "Submit" then %>
<form method="get">
Your TVC Matrix Associate ID: <input type="text" name="user" />
<input type="submit" name="submit" value="Submit" />
</form>
<% else
Response.Write("Your URL is: www.mca.com/?user=" & id)
End If %>
</body>
</html>
If you really don't want to have to reload front.asp then you need to look at ajax, and add the relevant tag to your question

javascript with jsp

Ok its a continuation of my crap attempts of using client side scripts along with server side elements.
<%# 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">
<title>Insert title here</title>
</head>
<body>
<form name="test" action="test.jsp" method="post" enctype="multipart/form-data">
<select name="harish" onchange=callme();>
<option value="1">1</option>
<option value="2">2</option>
</select>
<script>
var jsvar="Hello";
function callme()
{
alert(jsvar);
jsvar=document.getElementById("harish").value;
alert(jsvar);
}
</script>
<%
String s=(String)("<script>document.writeln(jsvar)</script>").toString();
out.println(s.equals("Hello"));
if(!(s.equals("Hello")))
{
String jspvar="<script>document.writeln(jsvar)</script>";
out.println("jspvar"+jspvar);
session.setAttribute("test",jspvar);
}
%>
</form>
</body>
</html>
Now what I am trying is to set the selected value as a session variable.But my bad the value from javascript is not sitting properly on the jsp/java variable and therby my condition if(!(s.equals("Hello"))) fails.Can anyone help me here...
Update:
Can the below be the solution for this question
Have a HTML page with two frames. Let the first page contain all the javascript values you wish to populate. The second page(hidden) of the frame actually does the trick. That is actually a JSP. On click of a button (on any action on the first page) in the first page, point your location to the hidden frame (2nd page), perform checks / conversions and populate the variable of the first page using cross frame JAVASCRIPT.
my condition if(!(s.equals("Hello"))) fails
That is because this:
String s=(String)("<script>document.writeln(jsvar)</script>").toString();
out.println(s.equals("Hello"));
...is pretty much the same as writing:
out.println("this".equals("that"));
It will always be false.
Now what I am trying is to set the selected value as a session variable.
To set a variable in the session, you need to POST the form to the server (ignoring AJAX techniques, etc.). As I mentioned here, using multipart/form-data requires a MIME parser - the form below uses the default enctype.
This form will, when you select an option from the drop-down, post the form to the server. Every time the JSP is run, it uses a scriptlet <% ... %> tests to see if a "harish" parameter has been posted. If it has, it places it in the session. An expression <%= ... %> is used to display the current session value.
<%# 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>
<!-- header removed for clarity -->
<body>
<form id="test" name="test" action="test.jsp" method="post"><select
name="harish" onchange="document.getElementById('test').submit();">
<option value="select">select an option</option>
<option value="1">1</option>
<option value="2">2</option>
</select></form>
<%
//see if a parameter was sent from page; "harish"==name attr on select
String value = request.getParameter("harish");
if (value != null) {
//store it in session
session.setAttribute("test", value);
}
%>
<%="harish=" + session.getAttribute("test")%>
</body>
</html>
This assumes that the above page is test.jsp - that the page posts back to itself. If not, you'll need to move the scriptlet and the expression to test.jsp.
Java is evaluated on the server side, so in variable s you will always find
<script>document.writeln(jsvar)</script>
Javascript is evaluated on the opposide side, that is on the client's browser, so this is why your method does not work (I've fallen many time into this also ^^)
You can POST the form on the same jsp where this code resides and take the result from the POSTed data, to do that you'll use a scriptlet. If I remember correctly you could use
request.getParameter("PARAMETER_NAME")
So just add the name of the jsp where this code is to the action of the form and the above code to retrieve the selected value.

Categories

Resources