I have problem with send form without refresh page in JSP using AJAX. How can I create AJAX to send this form, from index.jsp to send.jsp without refresh page ? Thanks for all your answers.
This is form code and it s work, without AJAX. (index.jsp)
<form id="dom-realitka-notifikacia" action="send.jsp" method="post" >
<div class="stred">
<b class="cierna">E-mail:</b>
<input type="text" class="form-control form-rovno" id="email" name="email" placeholder="Sem napíšte e-mail">
<input type="hidden" value="domrealitka" id="tabulka" name="tabulka">
<input type="hidden" value="<%= rs.getInt("id") %>" id="id_realitka" name="id_realitka">
<button type="submit" class="btn btn-success">Odoslať</button>
</div>
</form>
And this is (send.jsp), work without AJAX and insert into MYSQL.
page contentType="text/html" pageEncoding="UTF-8"
page import="javax.mail.*"
page import="javax.mail.internet.*"
page import="javax.sql.*"
page import="javax.naming.Context"
page import="javax.naming.InitialContext"
page import="java.sql.*"
request.setCharacterEncoding("UTF-8");
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
String email = request.getParameter("email");
int id_realitka = Integer.valueOf(request.getParameter("id_realitka"));
String tabulka = request.getParameter("tabulka");
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("nacitala sa driver");
Context ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/janko");
con = ds.getConnection();
System.out.println("nacitala sa databaza");
String sql = "INSERT INTO janko.notifikacia (email, id_realitka, tabulka) VALUES ( ?, ?, ?)";
ps = con.prepareStatement(sql);
ps.setString(1, email);
ps.setInt(2, id_realitka);
ps.setString(3, tabulka);
ps.executeUpdate();
con.close();
}
catch(ClassNotFoundException e1) //ClassNotFoundException dame Class.forName a klikneme ctrl+space a e1 dopiseme hocico
{
System.out.println(e1.getMessage()); //vypis spravy e1 do konzoly
}
catch(SQLException e2) //SQLException mame z DriverManager.getConnection po kliknuti ctrl+space a e2 dopiseme hocico
{
System.out.println(e2.getMessage()); //vypis spravy e2 do konzoly
}
finally{
con = null;
rs = null;
ps = null;
}
The form can be dynamically submitted easily using jQuery. Just include jQuery in your file and paste the following code in your HTML file.
<script>
$.ajax({url: "send.jsp",
data: $('#dom-realitka-notifikacia').serialize(),
success: function(result){
//do something like showing success message
}});
</script>
This code will serialize your form data and send it to the concerned servlet. The servlet code remains the same.
Related
I have the following coding in JSP which work when a JSP page is loaded:
<%
String sportugues = request.getParameter("port");
String senglish = request.getParameter("engl");
String sfuncgram = request.getParameter("funcgram");
//Integer snsyn = Integer.valueOf(request.getParameter("nsyninp"));
Usuario usu = new Usuario();
usu.setPortugues(sportugues);
usu.setEnglish(senglish);
usu.setFuncgram(sfuncgram);
//usu.setNsyn(snsyn);
UsuarioDao usudDao = new UsuarioDao();
usudDao.cadastroStudyAlfaDireita(usu);
%>
But I want it to work only when I click a HTML button like:
<button onclick="">JSP Command</button>
The button and the JSP coding must be in the same JSP page.
You can wrap your code that you need to load when click in a condition that check isButtonClick, then assign to onClick a function to update it
<c:set var="isButtonClicked" value="false" />
<c:if test="${isButtonClicked}">
<%
String sportugues = request.getParameter("port");
String senglish = request.getParameter("engl");
String sfuncgram = request.getParameter("funcgram");
//Integer snsyn = Integer.valueOf(request.getParameter("nsyninp"));
Usuario usu = new Usuario();
usu.setPortugues(sportugues);
usu.setEnglish(senglish);
usu.setFuncgram(sfuncgram);
//usu.setNsyn(snsyn);
UsuarioDao usudDao = new UsuarioDao();
usudDao.cadastroStudyAlfaDireita(usu);
%>
</c:if>
<button onClick="function(){<c:set var="isButtonClicked" value="${!isButtonClicked}"} />
I have a table with 3 columns.Last column has 4 radio buttons in each row.I am not able to fetch all the values of radio buttons checked after submitting the form.I always get only one value which is the value of radio button checked in the first row.
Here is the code of jsp page:
<form action = "SaveData" method = "POST" target = "_blank">
<h1>LIST</h1>
<%
try {
/* Create string of connection url within specified format with machine
name, port number and database name. Here machine name id localhost and
database name is student. */
String connectionURL = "jdbc:mysql://localhost:3306/sample";
// declare a connection by using Connection interface
Connection connection = null;
/* declare object of Statement interface that is used for executing sql
statements. */
Statement statement = null;
// declare a resultset that uses as a table for output data from tha table.
ResultSet rs = null;
// Load JBBC driver "com.mysql.jdbc.Driver"
Class.forName("com.mysql.jdbc.Driver").newInstance();
/* Create a connection by using getConnection() method that takes parameters
of string type connection url, user name and password to connect to database.*/
connection = DriverManager.getConnection(connectionURL, "root", "password");
/* createStatement() is used for create statement object that is used for
sending sql statements to the specified database. */
statement = connection.createStatement();
// sql query to retrieve values from the secified table.
String QueryString = "SELECT * from data";
rs = statement.executeQuery(QueryString);
%>
<table class="comparison-table">
<tr>
<th>LIST</th>
<th>Y/N</th>
<th>OPTIONS</th>
</tr>
<div>
<tr>
<%
while (rs.next()) {
String slist=rs.getString(1);
%>
<td name="list"><%= slist%></td>
<td>
<select id="choose" name="choose">
<option>Yes</option>
<option>No</option>
</select>
</td>
<td>
<form>
<input type="radio" name="option" value="a" checked> A
<input type="radio" name="option" value="b" >B
<input type="radio" name="option" value="c" > C
<input type="radio" name="option" value="d"> D
</form>
</td>
</tr>
</div>
<% } %>
<%
// close all the connections.
rs.close();
statement.close();
connection.close();
}
catch (Exception ex) {
%>
<%
out.println("Unable to connect to database."+ex);
}
%>
</table>
<button value="Submit" id="button">Submit</button>
</form>
Here is the Servlet code:
import javax.servlet.annotation.WebServlet;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
//Extend HttpServlet class
#WebServlet("/SaveData")
public class SaveData extends HttpServlet {
// Method to handle GET method request.
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Reading All Form Parameters";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n" +
"<table width = \"100%\" border = \"1\" align = \"center\">\n" +
"<tr bgcolor = \"#949494\">\n" +
"<th>Param Name</th>"+
"<th>Param Value(s)</th>\n"+
"</tr>\n"
);
Enumeration paramNames = request.getParameterNames();
while(paramNames.hasMoreElements()) {
String paramName = (String)paramNames.nextElement();
out.print("<tr><td>" + paramName + "</td>\n<td>");
String[] paramValues = request.getParameterValues(paramName);
// Read single valued data
if (paramValues.length == 1) {
String paramValue = paramValues[0];
if (paramValue.length() == 0)
out.println("<i>No Value</i>");
else
out.println(paramValue);
} else {
// Read multiple valued data
out.println("<ul>");
for(int i = 0; i < paramValues.length; i++) {
out.println("<li>" + paramValues[i]);
}
out.println("</ul>");
}
}
out.println("</tr>\n</table>\n</body></html>");
}
}
Output after submitting the form would be values of two parameters "choose" and "option". I get proper output for "choose" parameter ie. all the selected Yes/No options in a cloumn,whereas for "option" parameter i would get only the value of first row selected radio button ie if i select 'c' in the first row radio buttons only 'c' will be displayed with rest of the rows ignored.
Please help me out in fetching data of all the columns of the radio buttons selected in a String array.
I also want to fetch the value of "slist" which is from database using servlet. This is under td tag with name="list".
First you sould not nest form tag, remove the form tag before radio button.
From MDN web docs :
elements of type radio are generally used in radio
groups—collections of radio buttons describing a set of related
options. Only one radio button in a given group can be selected at the
same time.
You should add a variable to differentiate lines like this for example :
<tr>
<%! int lineNumber = 0 %>
<%
while (rs.next()) {
String slist=rs.getString(1);
%>
<td name="list"><%= slist%></td>
<td>
<select id="choose" name="choose">
<option>Yes</option>
<option>No</option>
</select>
</td>
<td>
<input type="radio" name="option<%= lineNumber %>" value="a" checked> A
<input type="radio" name="option<%= lineNumber %>" value="b" >B
<input type="radio" name="option<%= lineNumber %>" value="c" > C
<input type="radio" name="option<%= lineNumber %>" value="d"> D
</td>
</tr>
<% lineNumber++ %>
This is my code:
AdminDelete.jsp:
<%# page import ="java.sql.*" %>
<%
String uid = session.getAttribute("uid").toString();
String content = request.getParameter("content");
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/upload_hub",
"root", "root");
Statement st = con.createStatement();
int t= st.executeUpdate("DELETE * FROM post WHERE(uid like'"+uid+"' AND content like'"+content+"')");
if(t>0){
response.sendRedirect("../Admin.jsp");
}
%>
this is in the Admin's index:
<form method="send" action="functions/AdminDelete.jsp" >
<h3>delete all posts:</h3>
<% String content = request.getParameter("content");%>
<input type="button" value="delete" id="content">
</form>
I am trying to make a button that when i'm clicking on it, it delete's all of the posts in my website but when i click it, it dosen't do anything
I can not write entire answer in comment. So writing answer. As I mentioned in comment. You need to add space after LIKE. Also using PreparedStatement.
<%# page import ="java.sql.*" %>
<% String uid = session.getAttribute("uid").toString();
String content = request.getParameter("content");
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/upload_hub", "root", "root");
PreparedStatement ps = con.prepareStatement("DELETE FROM post WHERE uid like ? AND content LIKE ?");
ps.setString(1, "%" + uid + "%");
ps.setString(2, "%" + content + "%");
int t= ps.executeUpdate();
try {
con.close();
} catch(Exception e) {
e.printStackTrace();
}
if(t>0){
response.sendRedirect("../Admin.jsp");
}
%>
One thing to note here is that you need to verify the UID is set in session and content is set in request parameters.
Also you have used method="send". Instead use method="POST".
<form method="POST" action="functions/AdminDelete.jsp" >
<h3>delete all posts:</h3>
<input type="text" name="content" />
<input type="submit" value="Delete" />
</form>
Suppose one record in DB has UID containing letter a and corresponding to this record content has value containing b. Now submit data with b as input in form and make sure UID in session has value set to a. It should work. If you come up with any error message let me know.
So I have been sitting here racking my brain for a few hours and just cannot seem to find what I have wrong here. I am trying to get my form to send the information that the user inputs to my email. When I click send nothing happens... Anything would help! Thanks!
Here is the code I have atm:
Email me!
<div class="formCenter">
<form action="MAILTO:myemail#yahoo.com" method="post" enctype="text/plain">
First Name:<br>
<input type="text" name="firstName"><br>
Last Name:<br>
<input type="text" name="lastName"><br>
Email:<br>
<input type="text" name="email"><br>
Comments:<br>
<textarea name="commentBox" rows="6" cols="40"></textarea><br>
<input type="submit" value="Send">
<input type="reset" value="Reset">
</form>
</div>
Okay so you have to send the Action to a page like Email.PHP (or ASP.net ect) which will process your POST variables.
Example:
<?php
$firstame = $_POST['firstName'];
?>
You then have to use Mail(), which will work on most servers but sometimes it won't so you can use a tool like PHPMailer which is an object orientated tool.
As you are providing the link as MAILTO, it opens up your local mail client to send an email with the POST variables listed, which is very unprofessional at best. You are better off having a link that goes to MAILTO for the time being, perhaps with a hidden value like or something like that, so when they open the client it automatically generates an email that they can just click. With that being said, you would keep your form layout as it is, but just swap out variables so they don't appear.
The reason you didn't see anything when you clicked Send is because even though your TYPE is a submit, you sometimes need the Value and/or Name to be Submit. Some browsers and servers will treat it differently, even frameworks like Bootsrap. If you change your name and value to Submit then change one back to Send to see what works for you, you can keep it in the Send format, given that it works.
I hope this helps.
you can try this one:
<?php
if($_POST["message"]) {
mail("your#email.address", "Form to email message", $_POST["message"], "From: an#email.address");
}
?>
see this page http://htmldog.com/techniques/formtoemail/
The form itself is not able to send the email. What the code does is prompts you to select email client software such as Outlook.
Did you check whether your email client software work properly? A reboot of machine is also a mean of troubleshooting.
JavaScript
function submitEmail() {
var fname = $.trim($("#txtfname").val());
var lname = $.trim($("#txtlname").val());
var email = $.trim($("#txtemail").val());
var comments = $.trim($("#txtComments").val());
if (isValidEmail(email) && (fname.length > 1) && (lname.length > 1)) {
$.ajax({
type: "POST",
url: "index.aspx/SubmitEmail",
data: "{'Email':'" + $.trim($("#txtemail").val()) + "'," + "'FName':'" + $.trim($("#txtfname").val()) + "'," + "'LName':'" + $.trim($("#txtlname").val()) + "'," + "'Comments':'" + $.trim($("#txtComments").val()) + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (response.d != "null") {
var JsonObj = $.parseJSON(response.d);
if (JsonObj._Status == "OK") {
alert('Success Email :)')
}
else {
alert(JsonObj._Message);
}
}
},
failure: function (msg) {
alert(msg);
}
});
}
else {
return false;
}
}
function isValidEmail(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
};
<WebMethod()> _
Public Shared Function SubmitEmail(ByVal Email As String, ByVal FName As String, ByVal LName As String, ByVal Comments As String) As String
Dim _serializer = New JavaScriptSerializer()
Dim jSonRes As String = String.Empty
Dim MyString As New StringBuilder()
MyString.Append("First Name: " & FName).Append(Environment.NewLine)
MyString.Append("Last Name: " & LName).Append(Environment.NewLine)
MyString.Append("Email Address: " & Email).Append(Environment.NewLine)
MyString.Append("Comments: " & Comments).Append(Environment.NewLine)
Try
Dim Message As New Net.Mail.MailMessage("Do-Not-Reply#test.com", "myemail#yahoo.com")
Message.CC.Add("test#test.com,test#test.com")
Message.Subject = "New Request from " & FName & " " & LName
Message.IsBodyHtml = False
Message.Body = MyString.ToString()
Dim SmtpMail As New System.Net.Mail.SmtpClient
SmtpMail.Host = "localhost"
SmtpMail.Send(Message)
jSonRes = _serializer.Serialize(New With {._Status = "OK", ._Message = ""})
Catch ex As Exception
jSonRes = _serializer.Serialize(New With {._Status = "Error", ._Message = ex.Message})
End Try
Return jSonRes
End Function
<form action="index.aspx/submitEmail" method="post" enctype="text/plain">
First Name:<br>
<input type="text" name="firstName" id="fname"><br>
Last Name:<br>
<input type="text" name="lastName" id="lname"><br>
Email:<br>
<input type="text" name="email" id="txtemail"><br>
Comments:<br>
<textarea name="commentBox" rows="6" cols="40" id="txtComments"></textarea><br>
<input type="submit" value="Send">
<input type="reset" value="Reset">
</form>
This is the correct way to send a email. You can also use a php or C# code for sending a email. I have used vb.net code(webmethod) for sending email.
i want to get dropdown values in my program in order to merge the string to my file path so that the path will change dynamically according to user input.iam new to apache commoms,before i was using o'reilly api.
here is my code :
#Override
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, java.io.IOException
{
//FileItem f1;
String d1= request.getParameter("sel1");
String d2=request.getParameter("sel2");
String d3="/home/adapco/Desktop/output";
String conc=d3+"/"+d1+"/"+d2+"/";
filePath=(new StringBuilder()).append(conc).toString();
// filePath="/home/adapco/Desktop/output/";
isMultipart = ServletFileUpload.isMultipartContent(request);
}
i tried to debug and i am getting the wright file path but while proceeding further,the fileItems shows size=0 and and it is not entering the loop because of size0.
filePath="/home/adapco/Desktop/output/";
if i pass the upload path to the filePath it works fine.
List fileItems = upload.parseRequest(request);
Iterator i = fileItems.iterator();
while ( i.hasNext () )
{
FileItem fi = (FileItem)i.next();
if ( !fi.isFormField () )
{
String fieldName = fi.getFieldName();
String fileName = fi.getName();
String contentType = fi.getContentType();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
if( fileName.lastIndexOf("\\") >= 0 ){
file = new File( filePath +
fileName.substring( fileName.lastIndexOf("\\"))) ;
}else{
file = new File( filePath +
fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}
fi.write( file ) ;
out.println("Uploaded Filename: " + fileName + "<br>"+filePath);
}
my html :
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action="upload" method="post"
enctype="multipart/form-data">
<input type="file" name="file">
<br />
<select name="sel1">
<option label ="1">aerospace</option>
<option label ="2">automotive</option>
</select>
<select name="sel2">
<option label="1">internal</option>
<option label="2">demo</option>
</select>
<input type="submit" value="Upload File" />
</form>
</body>
</html>
The request.getParameter() calls should be removed. They are causing that the request body is parsed before Apache Commons FileUpload can parse it. The request.getParameter() should not be used on multipart/form-data requests.
You need to collect normal form fields in the else of your if (!fi.isFormField()).
if (!fi.isFormField()) {
// Collect uploaded files.
}
else {
// Collect normal form fields.
}
See also FileUpload User Guide and this answer.