Pass JavaScript variable to JSP session - javascript

I wrote a code to get client ip address from JavaScript. But i can't get proper output from that. i am getting error in this semicolon <% ; %>. I mentioned my code below. thank you.
<script>
function getMyIpAddress() {
$.getJSON("https://jsonip.com?callback=?", function(data) {
<%String ipAddress =%>data.ip; <% ; %>
//alert("Your IP address is :- " + data.ip);
//document.getElementById("demo").innerHTML = ipAddress;
<% session.setAttribute("clientipAddress", ipAddress); %>
});
}
</script>

The jsp is java servlet page.So in the <% %> or <% =%> should be java fragment code.
As you see,In you code <%String ipAddress =%> there just a variable declaration the ipAddress is null, the correct grammar is <%ipAddress=%>,and the <% ; %> is wrong grammar in java too.

Related

how to make jquery autocomplete ui using ajax in jsp

My problem is that jQuery UI AutoComplete is not working using AJAX in my JSP. I find many guides, but I cannot find the solution to my problem.
What I can do in this condition?
<%--
Document : Auto
Created on : Feb 13, 2018, 4:24:31 PM
Author : Lenovo
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<title>JSP Page</title>
</head>
<body>
<div class="ui-widget">
<input type="text" id="auto"/>
</div>
<script type="text/javascript">
$(function()
{
$('#auto').autocomplete(
{
source:function(request,response)
{
//Fetch data
$.ajax({
url:"Fetch.jsp",
method:"post",
dataType:'json',
data:{search:request.term},
success:function(data)
{
response(data.name);
}
});
}
});
});
</script>
</body>
</html>
This is my Fetch.jsp file:
<%#page import="org.json.JSONArray"%>
<%#page import="org.json.JSONObject"%>
<%# page contentType="text/html; charset=iso-8859-1" language="java"%>
<%#page language="java" %>
<%#page import="java.sql.*" %>
<%
try
{
String query = (String)request.getParameter("search");
JSONObject json=new JSONObject();
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/sample","root","root");
Statement st=con.createStatement();
ResultSet rs;
rs=st.executeQuery("select name from user2 where name like '"+query+"%'");
while(rs.next())
{
json.put("name",rs.getString("name"));
out.print(json.toString());
}
}
catch(Exception e1)
{
out.println(e1);
}
%>
Fetch.jsp should print a json array, not an object.
You are actually not printing a valid json, but json objects in sequence. You should print an array of the strings you got from the database.
Change:
JSONObject json=new JSONObject();
to
JSONArray json=new JSONArray();
and also change
while(rs.next())
{
json.put("name",rs.getString("name"));
out.print(json.toString());
}
to
while(rs.next())
{
json.put(rs.getString("name"));
}
out.print(json.toString());
And finally in your js:
success:function(data)
{
response(data);
}
From the docs:
A response callback, which expects a single argument: the data to suggest to the user. This data should be filtered based on the provided term... It's important, when providing a custom source callback, to handle errors during the request. You must always call the response callback even if you encounter an error. This ensures that the widget always has the correct state.
References
Jquery UI Autocomplete API source: array, string or callback

Javascript pop up message in JSP

Without creating a new page jsp file, is there a way I can make a popup "Data inserted successfully" message appear after I have inserted registration data into a table successfully.
Pop up in the sense that no new browser window is created but the message appears in a new box within the current web page and when clicked "Ok", redirects me to the next web page in the TRY SECTION.
<%#page import="com.mysql.jdbc.Statement"%>
<%#page import="com.mysql.jdbc.Connection"%>
<%#page import="java.sql.DriverManager"%>
<%Class.forName("com.mysql.jdbc.Driver");%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Registration Page</title>
</head>
<body>
<%!
String firstname, lastname, address, phoneNo;
String sex, password;
%>
<%
firstname = lastname = address = phoneNo= "";
sex = ""; password = "";
firstname = request.getParameter("firstname");
lastname = request.getParameter("lastname");
address= request.getParameter("address").trim();
phoneNo = request.getParameter("phoneNo");
sex = request.getParameter("Sex");
password = request.getParameter("password");
if(firstname.equals("")|| lastname.equals("")|| phoneNo.equals("")||
sex.equals("")|| password.equals(""))
{
out.write("Empty fields, make sure you input data into all field before pushing the " +
"REGISTER button");
}
else
{
String sql1="INSERT INTO customer_details VALUES('"+firstname+"', '"+lastname+"','"+address+"', '" +phoneNo+"',' "+sex+ "','"+password+"')";
String sql2 = "INSERT INTO verification VALUES('"+firstname+"', '"+password+"')";
try{
Connection conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/" + "onlineburgerapp","root", "root");
Statement st = (Statement) conn.createStatement();
st.executeUpdate(sql1);
st.executeUpdate(sql2);
conn.setAutoCommit(true);
conn.close();
response.sendRedirect("availableBurgers.jsp");
}
catch(Exception e){
e.printStackTrace();}
}
%>
</body>
You can insert JavaScript code into JSP code.
For example:
<%
try{
%>
<script type="text/javascript">
alert("Inserted Successfully");
</script>
<%
}catch(Exception e){
}
%>
If i understand properly your problem: if your SQL requests are successful, you want to display a 'success' message/popup to the user.
How do you request this JSP you show here?
If it is a classic webbrowser request (let's assume), since at the end, it redirects to the availableBurgers.jsp, this page won't send any content to your browser.
I would just set the success popup in the availableBurgers.jsp since this is your success page.
An improvement to the selected good answer:
if you want to customize your message with some variables you have:
<%
try {
String myVariable = "Successfully";
%>
<script type="text/javascript">
var myMessage;
<%
out.println("myMessage = \"I have inserted "+myVariable+"\"");
%>
alert(myMessage);
</script>
<%
} catch(Exception e) {
}
%>

how to get error message if record is already present in table in jsp page

I have an index.jsp page from where I am inserting name and id into oracle table. I am able to insert successfully, but when user enters same employee id again index.jsp page redirects to tomcat error page says
HTTP Status 500 javax.servlet.ServletException: java.sql.SQLIntegrityConstraintViolationException: ORA-00001: unique constraint
I want to display an error note within index.jsp when user enters id which is already present in database.
<%# 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><center>
<H1>Inserting record into a Database</H1>
<%# page language="java" %>
<%# page import="java.sql.*" %>
<%# page import="java.sql.DriverManager.*" %>
<%
int flag=0;
PreparedStatement ps=null;
Connection con= null;
ResultSet rs= null;
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("hostname","user","admin");
Statement st=con.createStatement();
String id = request.getParameter("id");
String name= request.getParameter("name");
ResultSet resultset =
rs=st.executeQuery("INSERT INTO employee (employeeid,employeename)VALUES ('"+id+"','"+name+"");
out.println("Data is successfully inserted!");
%>
</center>
</body>
</html>
Use the try-catch block to handle the exception.
What you can do to prevent it from coming is to check if the record is already present in table or not.
If the same id is present then do not execute the insert operation.
try{
int flag=0;
PreparedStatement ps=null;
Connection con= null;
ResultSet rs= null;
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("hostname","user","admin");
Statement st=con.createStatement();
String id = request.getParameter("id");
String name= request.getParameter("name");
// Check if the "id" is already present in table or not
rs = st.executeQuery("SELECT * FROM employee WHERE employeeid" = id );
if (!rs.next() ) {
// id is not present then insert the new record
rs = st.executeQuery("INSERT INTO employee (employeeid,employeename)VALUES ('"+id+"','"+name+"");
System.out.println("Data is successfully inserted!");
} else{
// id is already present then show the error message
System.out.println("Data is already present in table!");
}
} catch(Exception e){
// Handle any other exception occuring
System.out.println("Exception : " + e.printStackTrace());
}
Enclose the code in try and catch block ,when the control goes to catch block handle the exception and display the message you want to display.
To be more specific, handle the exception SQLIntegrityConstraintViolationException. This exception indicates that an integrity constraint (foreign key, primary key or unique key) has been violated.
try{
int flag=0;
PreparedStatement ps=null;
Connection con= null;
ResultSet rs= null;
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("hostname","user","admin");
Statement st=con.createStatement();
String id = request.getParameter("id");
String name= request.getParameter("name");
ResultSet resultset =
rs=st.executeQuery("INSERT INTO employee (employeeid,employeename)VALUES ('"+id+"','"+name+"");
out.println("Data is successfully inserted!");
}catch(SQLIntegrityConstraintViolationException e ){
//Duplicate entry '' for key 'PRIMARY'
System.out.println(e.getMessage());//you can modify the output as per your requirement.
} catch (Exception e) {
e.printStackTrace();
}

the page is refreshed every time when is loaded

I have an aspx page the get a value from url .
the page's code is like this :
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="confirmpayment.aspx.cs" Inherits="AccidentCongress.UserPortal.confirmpayment" %>
<div id="bankform"></div>
<script language="javascript" type="text/javascript">
function postRefId(refIdValue) {
var form = document.createElement("form");
form.setAttribute("method", "POST");
form.setAttribute("action", "<% System.Configuration.ConfigurationManager.AppSettings["PgwSite"].ToString(); %>");
form.setAttribute("target", "_self");
var hiddenField = document.createElement("input");
hiddenField.setAttribute("name", "RefId");
hiddenField.setAttribute("value", refIdValue);
form.appendChild(hiddenField); document.getElementById("bankform").appendChild(form);
form.submit();
document.getElementById("bankform").removeChild(form);
}
</script>
<%
if (Request.QueryString["po"] == "true")
{
Response.Write("<script language='javascript' type='text/javascript'> postRefId('" + Request.QueryString["rid"] + "');</script>");
}
%>
But when i call this page the page is refreshed ,and this part of code is executed every time :
<%
if (Request.QueryString["po"] == "true")
{
Response.Write("<script language='javascript' type='text/javascript'> postRefId('" + Request.QueryString["rid"] + "');</script>");
}
%>
Why?
Best regards
you have
form.submit();
in your javascript function call

Rails: Accessing instance variable from not inline JS

I have this code in a .html.erb file:
<script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script>
<script>
FB.Event.subscribe('edge.create',
function(response) {
send_fb_like();
}
);
FB.Event.subscribe('edge.remove',
function(response) {
send_fb_unlike();
}
);
function send_fb_like()
{
var business_name = '<%= #consumer.name %>';
alert("You liked"+consumer_name);
}
function send_fb_unlike()
{
var business_name = '<%= #consumer.name %>';
alert("You unliked"+consumer_name);
}
</script>
This is working correctly, and I can access the #consumer.name correctly. However, if I change this to:
Where facebook_consumer.js looks like this:
$(function(){
FB.Event.subscribe('edge.create',
function(response) {
send_fb_like();
}
);
FB.Event.subscribe('edge.remove',
function(response) {
send_fb_unlike();
}
);
function send_fb_like()
{
var business_name = '<%= #consumer.name %>';
alert("You liked"+consumer_name);
}
function send_fb_unlike()
{
var business_name = '<%= #consumer.name %>';
alert("You unliked"+consumer_name);
}
});
It will dump this:
You liked <%= #consumer.name %>. I have tried saving the file as js.erb, but then it seems it doesn't know what #consumer is.
Any thoughts on what is the best approach?
Your best bet is probably to create an app-wide JS object to store values you need. At the top of the page, you can add elements to this object, and they will be available to your linked scripts.
<script type="text/javascript">
app = app || {}
app.keyName1 = "<%= #variable1 %>";
app.keyName2 = "<%= #variable2 %>";
</script>
You can't inline Ruby code into .js files. If you want to use Ruby code, you need to create a .js.erb file and then render a partial inside of that.
# controller
render :partial => "/path/to/js/partial.js.erb"
# inside your JS partial
# you can use <%= #consumer.name %> freely in this file
# and then add the line below to render your normal html.erb file
$("#reviews").append("<%= escape_javascript(render(:partial => '/path/to/partial.html.erb' )) %>");

Categories