populate dropdown on change of another using servlet - ajax

i am new in java struts i am developing web application in struts 1.3 i have two dropdowns one is for location and another is for Floor,i have a requirement that on change on one dropdown values of other dropdown fills from database for i googled a lot and i got code but when i change on my first dropdown second dropdown does not populate though i saw in debugging mode in Netbeans that that values return from database .i do my database activity in servlet doGet method
<script>
function createRequestObject()
{
var req;
if(window.XMLHttpRequest)
{
//For Firefox, Safari, Opera
req = new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
//For IE 5+
req = new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
//Error for an old browser
alert('Your browser is not IE 5 or higher, or Firefox or Safari or Opera');
}
return req;
}
//Make the XMLHttpRequest Object
var http = createRequestObject();
function sendRequest(method, url)
{
if(method == 'get' || method == 'GET')
{
http.open(method,url);
http.onreadystatechange = handleResponse;
http.send(null);
}
}
function handleResponse()
{
if(http.readyState == 4 && http.status == 200)
{
var response = http.responseText;
if(response)
{
document.getElementById("dwnfloor").innerHTML = response;
}
}
}
function getFloorDropdown(SelectedValue)
{
alert(SelectedValue);
sendRequest('GET','http://localhost:8084/AssetManagement/DropDown?locid=' +SelectedValue );
}
</script>
<tr>
<td >
<span style="color:#FF0000">*</span>Location</td>
<td> <html:select name="RoomForm" property="name"
onchange="getFloorDropdown(this.value)">
<htmlption value="0">Select Location</htmlption>
<htmlptionsCollection name="RoomForm"
property="list" value="id" label="name" />
</html:select>
<td>
</tr>
<tr>
<td >
<span style="color:#FF0000">*</span>Floor
</td>
<td id="dwnfloor">
<select name="dwnfloor">
<option value="0">Select Floor</option>
</select>
</td>
</tr>
Servlet Code
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
String country=request.getParameter("locid");
String buffer="<select name=\"dwnfloor\"><option value=\"0\">Select</option>";
Connection connection = null;
PreparedStatement p_statement = null;
Statement statement = null;
ResultSet result = null;
try {
DAOOperation dao= new DAOOperation();
String sqlst = "select id,name from floor_mst where id=?";
try {
connection = DBConnection.getConnection();
p_statement = connection.prepareStatement(sqlst);
p_statement.setString(1, country);
result = p_statement.executeQuery();
while(result.next()) {
buffer=buffer+"<option value=\""+result.getString("ID")+" \">"+result.getString("name")+"</option>";
}
buffer=buffer+"</select>";
response.getWriter().println(buffer);
System.out.println(buffer);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
connection.close();
} catch (Exception e) {
}
}// end finally
} catch(Exception e) {
System.out.println(e);
}
}
and servlet mapping in web.xml
web.xml
<servlet-mapping>
<servlet-name>DropDown</servlet-name>
<url-pattern>/DropDown</url-pattern>
</servlet-mapping>

In the servlet, write response.getWriter().write(buffer) instead of response.getWriter().println() and also, try to alert the response you got from the servlet
in the ajax code you have written. It seems like your javascript has not recieved the response.
If the problem is not solved then Im online.

Related

Recommended way to handle http errors inside my asp.net mvc 5 web application

i need a way to globally handle http errors inside my asp.net mvc web application. i did the following if the call to the action method is Ajax :-
$(document).ready(function () {
$(document).ajaxError(function (e, xhr, textStatus, errorThrown) {
if (xhr.status == 401)
window.location = "/Account/Login";
else if (xhr.status == 403 || xhr.status == 404)
alert(xhr.statusText, 'Error');
$(".loadingimage").hide();
});
where my action method looks as follow:-
[CheckUserPermissions(Action = "Edit", Model = "Skill")]
public async Task<ActionResult> DeleteKBLink(int? skillid,int? linktokbid)
{
if (skillid == null || linktokbid==null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var linktokb= await unitofwork.SkillRepository.FindLinkToKB(linktokbid.Value);
if (linktokb == null)
{
return new HttpStatusCodeResult(404, "The link has already been deleted.");
}
but i am not sure how i can handle the http errors in-case the request is not ajax ? currently i will be redirected to http not found page .. thnaks
This solution works well for me...
[1]: Remove all 'customErrors' & 'httpErrors' from Web.config
[2]: Check 'App_Start/FilterConfig.cs' looks like this:
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}
[3]: in 'Global.asax' add this method:
public void Application_Error(Object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
Server.ClearError();
var routeData = new RouteData();
routeData.Values.Add("controller", "ErrorPage");
routeData.Values.Add("action", "Error");
routeData.Values.Add("exception", exception);
if (exception.GetType() == typeof(HttpException))
{
routeData.Values.Add("statusCode", ((HttpException)exception).GetHttpCode());
}
else
{
routeData.Values.Add("statusCode", 500);
}
Response.TrySkipIisCustomErrors = true;
IController controller = new ErrorPageController();
controller.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
Response.End();
}
[4]: Add 'Controllers/ErrorPageController.cs'
public class ErrorPageController : Controller
{
public ActionResult Error(int statusCode, Exception exception)
{
Response.StatusCode = statusCode;
ViewBag.StatusCode = statusCode + " Error";
return View();
}
}
[5]: in 'Views/Shared/Error.cshtml'
#model System.Web.Mvc.HandleErrorInfo
#{
ViewBag.Title = (!String.IsNullOrEmpty(ViewBag.StatusCode)) ? ViewBag.StatusCode : "500 Error";
}
<h1 class="error">#(!String.IsNullOrEmpty(ViewBag.StatusCode) ? ViewBag.StatusCode : "500 Error"):</h1>
//#Model.ActionName
//#Model.ContollerName
//#Model.Exception.Message
//#Model.Exception.StackTrace

XMLHttpRequest request / Servlet response is null

There is a problem with servlet. I send form data by XMLHttpRequest to a server, but servlet handles request object incorrectly and send in response object "null.null". I tried following things but nothing helps:
encode "document.getElementsByName('contractor').value" by encodeURIComponent;
pass the object of FormData as argument to .send();
changing enctype attribute in form to "multipart/formdata";
using get method.
Please take a look. If there are any suggestions how to make it works without using jQuery I would appreciate a lot.
HTML:
<div id="request-form">
<form enctype="application/x-www-form-urlencoded" method="post">
Contractor<input type="text" name="contractor"><br>
Contract No<input type="text" name="contract-no">
<input type="button" onclick=clickOnButton() value="Submit"><br>
</form>
</div>
JS:
var httpRequest;
function clickOnButton() {
if (window.XMLHttpRequest) {
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
var dataForRequest = 'contract=' + document.getElementsByName('contractor').value + '&contract-no=' + document.getElementsByName('contract-no').value;
httpRequest.onreadystatechange = responseHandler;
httpRequest.open('POST', "/AjaxServ", true);
httpRequest.send(dataForRequest);
}
function responseHandler() {
if (httpRequest.readyState == 4) {
if (httpRequest.status == 200) {
var line = httpRequest.responseText;
alert(line);
}
}
}
Java:
public class ServletClass extends HttpServlet {
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String contractor = req.getParameter("contractor");
String contractNo = req.getParameter("contract-no");
resp.setContentType("text/plain");
PrintWriter out = resp.getWriter();
out.write(contractor + "." + contractNo);
}
}
Shouldn't it be 'contractor=' + document.getElementsByName('contractor').value instead of
'contract=' + document.getElementsByName('contractor').value ?

How can I Authenticate with ServiceStack using jQuery Ajax

I'm trying to do something like the following:
jQuery Part:
function ajaxLogin() {
$.ajax({
url: "auth/credentials",
type: "POST",
data: { UserName: $("#form_username").val(), Password: $("#form_pwd").val() },
success: function (data) {
$("#login_div").hide();
},
error: function (jqXHR,textStatus,errorThrown) {
$("$login_msg").text(errorThrown);
}
});
}
However, for some reason it's always coming back to the success function and data contains the html contents of the current html document.
My ServiceStack AuthProvider contains the following TryAuthenticate:
public override bool TryAuthenticate(IServiceBase authService, string userName, string password)
{
var session = authService.GetSession();
string error = null;
try
{
var dataSource = authService.TryResolve<RiskViewDataSource>();
var diModelInstance = dataSource.diModelRootObject;
string authResult = UserFactory.authenticate(session.Id, userName, password, false);
if ("OK".Equals(authResult))
{
session.IsAuthenticated = true;
session.UserName = session.DisplayName = userName;
session.UserAuthId = password;
UsersManager.generateUsersPolicies();
UsersManager.loadUserPolicies();
return true;
}
else
{
session.IsAuthenticated = false;
session.UserName = session.DisplayName = null;
session.UserAuthId = null;
authService.RemoveSession();
return false;
}
}
catch (Exception e)
{
Log.Error(e.ToString());
session.IsAuthenticated = false;
session.UserName = session.DisplayName = null;
session.UserAuthId = null;
error = "Could not connect to RiskView database";
}
if (error != null)
{
throw HttpError.Unauthorized(error);
}
else
{
return false;
}
}
Ok, after a day of messing about I've come up with this solution which works for me. I had to create a new service request for logging in. I called it RenewSession.
Service Stack Part:
[Route("/RenewSession", "POST")]
public class RenewSessionRequest : IReturn<RenewSessionResponse>
{
}
public class RenewSessionResponse : IHasResponseStatus
{
public RiskViewJsonObject Result { get; set; }
public ResponseStatus ResponseStatus { get; set; }
}
public class RenewSessionService : Service, IPost<RenewSessionRequest>
{
public object Post(RenewSessionRequest request)
{
string username = this.Request.GetParam("UserName");
string password = this.Request.GetParam("Password");
string message = "";
IAuthProvider authService = AuthService.GetAuthProvider("credentials");
Boolean success = false;
try
{
var response = authService.Authenticate(this, this.GetSession(), new Auth { UserName = username, Continue = null, Password = password });
success = true;
}
catch (Exception e)
{
message = e.ToResponseStatus().Message;
}
return new RenewSessionResponse { Result = new Mapping.RiskViewJsonObject("{ \"success\" : " + (success ? "true" : "false") + ", \"message\" : \"" + RiskViewJsonObject.cleanForJSON(message)+ "\" }") };
}
}
Html and Ajax Part:
1) Add a div to the page for the login details (Hide it to start with)
<div id="login-div" style="position:absolute;display:hidden;left:100;top:100;background-image:url('images/login_bk.png');">
<p id="login_error_msg"></p>
<form id="login_form" onsubmit="loginSubmit(); return false;">
<table>
<tr>
<td>Username:<input id="in_un" type="text" name="UserName" autocomplete="off" autocorrect="off" autocapitalize="off"/></td>
</tr>
<tr>
<td>Password:<input id="in_pw" type="password" name="Password" autocomplete="off" autocorrect="off" autocapitalize="off"/></td>
</tr>
<tr>
<td style="text-align: center;">
<input id="login_submit" type="submit" class="hand_cursor" value="Login">
</td>
</tr>
</table>
</form>
</div>
2) I add 401 checks to every ajax query on my page (401 tells us that the session has expired)
$.getJSON('/Menus?format=json', function(data) {
// Do some stuff
}).fail(function (jqxhr,textStatus,error) {
if (jqxhr.status == 401) {
loginAgain();
}
});
3) Show the div to re-login
function loginAgain(reloadMenu) {
$("#login-div").show("slow");
}
4) The onclick for login button or onsubmit event for the login form
function loginSubmit() {
if ($("#in_un").val().trim() == "" || $("#in_pw").val().trim() == "") {
$("#login_error_msg").text("Username or Password is still empty.");
return false; // Prevent form from submitting
} else {
$("#login_submit_btn").attr("disabled","disabled");
$("#login_error_msg").text("");
$.ajax({
url: "/RenewSession?format=json",
type: "POST",
data: { UserName: $("#in_un").val(), Password: $("#in_pw").val() },
success: function (data, textStatus, jqXHR) {
$("#login_submit_btn").removeAttr("disabled");
if (data.Result.success) {
$("#login-div").hide();
} else {
if (data.Result.message) {
$("#login_error_msg").text(data.Result.message);
} else {
$("#login_error_msg").text(textStatus);
}
$("#in_pw").focus();
}
},
error: function (jqXHR, textStatus, errorThrown) {
$("#login_submit_btn").removeAttr("disabled");
$("#login_error_msg").text("ERROR: "+errorThrown);
$("#in_pw").focus();
}
});
}
return false; // Stop the form submiting, we're just gonna hide the div
}

Fine Uploader- Server side code saves uploaded file but client displays 'Upload failed' message

I have an MVC2 application where I am trying to use the Fine-Uploader plugin. When I run through my code behind, it saves the file that I uploaded. However, what get's displayed back in the browser is Upload Failed. I'm not sure what I'm missing here. My code is below:
Code behind:
public void UploadFiles()
{
try
{
if (Request.Files.Count > 0)
{
foreach (string file in Request.Files)
{
HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
if (hpf.ContentLength == 0)
{
continue;
}
string filename = Path.GetFileName(hpf.FileName);
string path = Path.Combine(Server.MapPath(ConfigurationManager.AppSettings["AttachmentPath"]), filename);
hpf.SaveAs(path);
}
}
}
catch (Exception e)
{
//Do something
}
}
Master page:
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
<script src="<%=Url.Content("~/Scripts/jquery.fineuploader-3.5.0.js") %>" type="text/javascript"></script>
<script src="<%=Url.Content("~/Scripts/jquery.fineuploader-3.5.0.min.js") %>" type="text/javascript"></script>
Markup page:
<div id="manual-fine-uploader"></div>
<div id="triggerUpload" class="btn btn-primary" style="margin-top: 10px;">
<i class="icon-upload icon-white"></i> Upload now
</div>
<script type="text/javascript">
$(document).ready(function () {
var manualuploader = new qq.FineUploader({
element: $('#manual-fine-uploader')[0],
request: {
endpoint: 'Home/UploadFiles'
},
autoUpload: false,
text: {
uploadButton: '<i class="icon-plus icon-white"></i> Select Files'
}
});
$('#triggerUpload').click(function () {
manualuploader.uploadStoredFiles();
});enter code here
});
</script>
Fine Uploader expects a valid JSON response indicating whether the upload succeeded or not.
A successful upload response must have:
{ "success": true }
for Fine Uploader to know that it worked. You can add whatever else you want to your response, but without indicating 'success' Fine Uploader will think that the upload failed.
What I would do is add a return to your UploadFiles function. Somewhat like:
public UploadResult UploadFiles()
{
try
{
// ... save file and other things
}
catch (Exception ex)
{
// failsauce :(
return new UploadResult(false);
}
// success :)
return new UploadResult(true);
}
Where UploadResult is much like:
public class UploadResult
{
// This is important!
public const string ResponseContentType = "text/plain";
public FineUploaderResult(bool success)
{
_success = success;
}
public override void ExecuteResult(ControllerContext context)
{
// Here we create the JSON Response object,
// set the correct content-type, and finally
// it gets built with the correct success flag.
var response = context.HttpContext.Response;
response.ContentType = ResponseContentType;
response.Write(BuildResponse());
}
public string BuildResponse()
{
var response = new JObject();
response["success"] = _success;
// ... maybe set some other data in the response JSON
return response.ToString();
}
}
There is an example using ASP.NET MVC C# up on the server examples repository that may provide some assistance.
Also, on the development branch there is a server-side README which indicates exactly what constitutes a valid JSON response for Fine Uploader.

Ajax based username availablity checking and then generating some username to use in jsp

i have somewhat done a ajax based jsp coding for checking username availability. It worked perfectly. Though it might have some errors. So if there any please point it out. Now my main question is that after the checking i also want generate some usernames for users to use like we can see it at gmail registration form. I am giving my code here...
First the index.html...
<html>
<body>
<form action=sample.jsp method=post>
id<input type=text name=id><br>
<input type=submit value=next>
</form>
</body>
</html>
Now sample.jsp...
<jsp:useBean id="ob" class="sample.Database" scope="session" />
<jsp:setProperty name="ob" property="*" />
<html>
<head>
var xmlHttp
var xmlHttp
var checkvalue
function showState(p1){
if (typeof XMLHttpRequest != "undefined"){
xmlHttp= new XMLHttpRequest();
}
else if (window.ActiveXObject){
xmlHttp= new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlHttp==null){
alert ("Browser does not support XMLHTTP Request")
return
}
var url="getlist.jsp?name="+p1;
xmlHttp.onreadystatechange = stateChange;
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
function stateChange(){
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
checkvalue=document.getElementById("name").innerHTML=xmlHttp.responseText;
document.f1.checking.value = xmlHttp.responseText;
}
}
function conditions(){
if(!checkvalue.match("Available"))
{
alert("no match");
return false
}
}
</script>
</head>
<body >
<center>
<br>
<form action="sample1.jsp" name="f1" method="post" onsubmit="return conditions()">
name <input type=text name=name onchange="showState(this.value);"><div id='name'></div><br>
checking<input type=text name=checking><br>
<input type=submit value=next>
</form>
</body>
</html>
now getlist.jsp...
<jsp:useBean id="ob" class="sample.Database" scope="session" />
<%
String n=request.getParameter("name");
if(ob.checkName(n)==0)
{
%>
<font color=green>Available</font>
<%
}
else
{
%>
<font color=red>Not available</font>
<%
}
%>
now sample1.jsp....
<jsp:useBean id="ob" class="sample.Database" scope="session" />
<jsp:setProperty name="ob" property="*" />
<%
if(ob.insertData()==1)
out.println("Success");
else
out.println("Unsuccess");
%>
code for class file in package->sample filename->Database.java...
package sample;
import java.util.*;
import java.sql.*;
public class Database
{
private String id="",name="";
private int t=0;
private Connection con;
public void setName(String name)
{
this.name=name;
}
public String getName()
{
return name;
}
public void setId(String id)
{
this.id=id;
}
public String getId()
{
return id;
}
public Connection c1()
{
try{
Class.forName("oracle.jdbc.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1000:xe","system","12345");
}
catch(Exception e){}
return con;
}
public int checkName(String n)
{
try{
con=c1();
PreparedStatement pst = con.prepareStatement("select name from testani where name='"+n+"'");
t = pst.executeUpdate();
con.close();
}
catch(Exception e){}
return t;
}
public int insertData()
{
try{
con=c1();
PreparedStatement pst = con.prepareStatement("insert into testani values('"+name+"','"+id+"')");
t = pst.executeUpdate();
con.close();
}
catch(Exception e){}
return t;
}
}
I have created a database named testani with attributes name and id by using mysql...
Now how can i modify this code to generate some names.... Thanks in advance..
I guess you need to make your own algorithm for name suggestion.
Like once the user enters his name,surname, birth year,etc. then you can design an algorithm that can take these values and do some processing by combining(concatenating) words or birth year or anything that you want to generate suggested usernames.
Then you can simply return that list to the user.

Resources