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
Related
I am doing a file upload program in which i am using ajax call to check whether any file exists with the same name.
Here is the code
jsp page
<%# taglib prefix = "form" uri = "http://www.springframework.org/tags/form"%>
<%# 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>File Upload Example</title>
<script src="/AjaxWithSpringMVC2Annotations/js/jquery.js"></script>
<script type="text/javascript">
function checkExistence() {
var name = $('#file').val();
File f=new File(name);
var filename=f.getOriginalFileName();
document.write(filename);
$.ajax({
type: "POST",
url: "/FileController/fileexists",
data: "filename=" + filename,
success: function(response){
if(response==0)
{
ch="zero";
document.fileform.choice.value=ch;
document.fileform.submit();
}
else if(response==1)
{
alertchoice=alert("File already exists !! Do you want me to overwrite it ?");
if(alertchoice==true || alertchoice.equals(true))
{
ch="one";
document.fileform.choice.value=ch;
document.fileform.submit();
}
else {
ch="two";
alert("Upload suspended as requested by the user ");
} }
},
error: function(e){
alert('Error: ' + e);
}
});
}
</script>
</head>
<body style="background-color:powderblue;color:Tomato">
<br>
<br>
<center><form name="fileform" action="savefile" method = "POST" modelAttribute = "fileUpload"
enctype = "multipart/form-data">
Please select a file to upload :
<input type = "file" name = "file" id="file"><br><br><br>
<input type="hidden" name="choice">
<input type = "button" value ="upload" onClick="checkExistence()">
<input type="reset" value="Reset">
</form></center>
<br>
<br>
<br>
<center><b> ${message} </b></center>
</body>
</html>
//controller class
#RequestMapping(value="/fileexists",method = RequestMethod.POST)
#ResponseBody public String checkingForDuplicates(HttpServletRequest req, HttpServletResponse res){
String filename=req.getParameter("filename");
int i=isDuplicate(filename);
return i+"";
}
Here when i am clicking the button upload , control should go to the function checkExistence() . But it is not moving. Is something wrong with my code ? And i am using
File f=new File(name);
var filename=f.getOriginalFileName();
in javascript function to get the name of the file being uploaded. Does it work ?
I got the answer by making the following corrections.
Including jquery plugin
changing ajax call url from
url: "/FileController/fileexists"
to
url: "fileexists"
In jsp page to get name of the file being uploaded
var name = $('#file').val();
File f=new File(name);
var filename=f.getOriginalFileName();
modified :
var filename=document.getElementById('file').value;
var lastIndex = filename.lastIndexOf("\\");
if (lastIndex >= 0) {
originalfilename = filename.substring(lastIndex +1);
}
In controller to get the file name(for checking duplicates)
previous : String filename=req.getParameter("filename");
modified : String filename=req.getParameter("originalfilename");
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) {
}
%>
I have confirm delete message in my application and it works on IE8-9 but not on 'IE11' and 'Chrome'. I checked all settings and scripts are enabled on both browsers.
When I click on 'delete' link nothing happens page is just refreshed and no message is displayed and record is not deleted.
This is my _delete_from_page.rhtml file in 'views' directory.
<%= render :partial => "layouts/top_menu"%>
<%= render :active_scaffold => "testing_page_chain"%>
<html>
<head>
<script language="javascript">
function doRedirect()
{
var confirm_msg=confirm("Are you sure you want to delete the request with ID <%=#d.controller_id%>?" ,"");
var id=<%=#d.id%>
if (confirm_msg==true)
{
window.location="<%= url_for(:controller => "#{params[:controller]}")%>/confirm_delete?id="+id;
}
else
{
window.location="<%= url_for(:controller => "#{params[:controller]}")%>/cancel_delete";
}
}
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
</script>
</head>
</html>
<script language="javascript" type="text/javascript">
window.onload=addLoadEvent(doRedirect)
</script>
and I call this from controller 'testing_page_chain_controller.rb' like
render :partial => "delete_from_page"
Why don't you use data-confirm?
<%=link_to 'Delete', url, date: {confirm: 'Are you sure?'} %>
This is in Rails default installation by default. Then you can do your server stuff after they confirm they want to delete the object.
I do have a splash page for my website which should ask users for confirmation before entering the site.
I implemented a "Remember me" checkbox there, so if users check that it will set a cookie so in the next visit page will be redirected automatically.
The issue i've just ran into it is i want to set a conditional in my header page, so it should check if user is already have the Cookie it should show the page content and if not it should redirect to the splash page.
Is there any way either with PHP or JS
Here is the Splash page code
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<!-- JQuery -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function(e) {
$('#remember').click(function() {
if (this.checked) {
addCookie(30);
} else {
deleteAllCookies();
}
});
});
function deleteAllCookies() {
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i];
var eqPos = cookie.indexOf("=");
var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
}
}
function addCookie(exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = expires;
}
function checkCookie() {
if (document.cookie == false) {
} else if (document.cookie.indexOf("expires") >= 0) {
window.location.href = "https://www.google.com";
}
}
function goTo() {
window.location.href = "https://www.google.com";
}
</script>
</head>
<body onLoad="checkCookie();">
<h1>Splash Page</h1>
<form>
<input type="checkbox" id="remember"> Remember me
<br>
<input type="button" value="Enter" onClick="goTo();">
</form>
</body>
</html>
#totallytotallyamazing
I used JS, Jquery, and (PHP just for testing), for this solution.
Here is the DEMO. (I slightly altered the previous Splash page Demo to accommodate this Demo.)
Here is the code:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<!-- JQuery -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
function checkCookie() {
if (document.cookie == false) {
$('#x').text("No Cookie.");
window.location.href = "http://www.totallytotallyamazing.com/jsFiddle/cookie/indexNoAlert.html";
} else if (document.cookie.indexOf("expires") >= 0) {
$('#x').text("You have Cookie.");
}
}
</script>
</head>
<body onLoad="checkCookie();">
<h1>My Website</h1>
<p><div id='x'></div></p>
<?php
session_start();
if(isset($_COOKIE['expires'])) {
echo "Here is your expiration date " . $_COOKIE['expires'] . "!<br>";
}
?>
</body>
</html>
After the page does it's final redirect, reload the page one more time to see the "expires" cookie display is expiration date.
I hope this works for you, please let me know.
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' )) %>");