I am receiving an error not loading message when I click on my submit button on my login.html. I don't have much experience with this and there are no error messages to point me in the direction to fix it.
I have my login.html
<body>
<div id="log">
<h2>Login</h2>
<form method="post" action="login" class="form-1" accept-charset="utf-8" onsubmit="sendAjax()">
<input type="text" name="username" id="username" placeholder="Username"/><br/>
<input type="password" name="password" id="password" placeholder="Password"/><br/>
<input type="submit" value="Sign In"/>
</form>
</div>
</body>
which is called into a div in my index.html
$('#login').click(function(e){
$('#map-canvas').addClass("hidden");
$('#dMain').removeClass("hidden");
$('#dMain').load('html/login.html');
e.preventDefault();
my login servlet
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String username = request.getParameter("username");
String password = request.getParameter("password");
if(databaseConnection.checkUser(username, password))
{
RequestDispatcher rs = request.getRequestDispatcher("Welcome");
rs.forward(request, response);
}
else
{
out.println("Username or Password incorrect");
RequestDispatcher rs = request.getRequestDispatcher("login.html");
rs.include(request, response);
}
}
and my ajax function
function sendAjax(){
var article = new Object();
article.username = $('#username').val();
article.password = $('#password').val();
$ajax({
url: "http://localhost:8080/FishingTrax/LoginServlet",
type: 'POST',
dataType: 'json',
data: JSON.stringify(article),
contentType: 'application/json',
mimeType: 'application/json',
success: function (data) {
},
error:function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er);
}
});
};
I had two problems with my code, I was lacking the return prior to the sendAjax(). The define Ajax problem was due to missing a full stop in $ajax so it should be $.ajax
function sendAjax(){
var article = new Object();
article.username = $('#username').val();
article.password = $('#password').val();
$.ajax({
url: "http://localhost:8080/FishingTrax/LoginServlet",
type: 'POST',
dataType: 'json',
data: JSON.stringify(article),
contentType: 'application/json',
mimeType: 'application/json',
success: function (data) {
},
error:function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er);
}
});
};
Related
I am performing simple crud operation during this I am getting 400 bad request error on console
i.e. POST http://localhost:8080/student/getDetails 400
my code :
<body>
<form >
Enter Student id: <input type="number" id="id" name="id"/><br/>
<button id="selectButton" onclick="getStudent()">Get Student</button>
</form>
<script type="text/javascript"
src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
function getStudent() {
$.ajax({
type: "POST",
url : "/student/getDetails",
contentType: "application/json; charset=utf-8",
dataType: "json",
success : function(data)
{
alert(data);
},
error: function (data) {
alert(data);
}
});
}
</script>
</body>
I'm creating a JSP/Servlet web application and I'd like to upload a file to a servlet via Ajax. How would I go about doing this? I'm using jQuery.
I've done so far:
<form class="upload-box">
<input type="file" id="file" name="file1" />
<span id="upload-error" class="error" />
<input type="submit" id="upload-button" value="upload" />
</form>
With this jQuery:
$(document).on("#upload-button", "click", function() {
$.ajax({
type: "POST",
url: "/Upload",
async: true,
data: $(".upload-box").serialize(),
contentType: "multipart/form-data",
processData: false,
success: function(msg) {
alert("File has been uploaded successfully");
},
error:function(msg) {
$("#upload-error").html("Couldn't upload file");
}
});
});
However, it doesn't appear to send the file contents.
To the point, as of the current XMLHttpRequest version 1 as used by jQuery, it is not possible to upload files using JavaScript through XMLHttpRequest. The common workaround is to let JavaScript create a hidden <iframe> and submit the form to it instead so that the impression is created that it happens asynchronously. That's also exactly what the majority of the jQuery file upload plugins are doing, such as the jQuery Form plugin (an example).
Assuming that your JSP with the HTML form is rewritten in such way so that it's not broken when the client has JavaScript disabled (as you have now...), like below:
<form id="upload-form" class="upload-box" action="/Upload" method="post" enctype="multipart/form-data">
<input type="file" id="file" name="file1" />
<span id="upload-error" class="error">${uploadError}</span>
<input type="submit" id="upload-button" value="upload" />
</form>
Then it's, with the help of the jQuery Form plugin, just a matter of
<script src="jquery.js"></script>
<script src="jquery.form.js"></script>
<script>
$(function() {
$('#upload-form').ajaxForm({
success: function(msg) {
alert("File has been uploaded successfully");
},
error: function(msg) {
$("#upload-error").text("Couldn't upload file");
}
});
});
</script>
As to the servlet side, no special stuff needs to be done here. Just implement it exactly the same way as you would do when not using Ajax: How can I upload files to a server using JSP/Servlet?
You'll only need an additional check in the servlet if the X-Requested-With header equals XMLHttpRequest or not, so that you know how what kind of response to return for the case that the client has JavaScript disabled (as of now, it is mostly the older mobile browsers which have JavaScript disabled).
if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
// Return an Ajax response (e.g. write JSON or XML).
} else {
// Return a regular response (e.g. forward to JSP).
}
Note that the relatively new XMLHttpRequest version 2 is capable of sending a selected file using the new File and FormData APIs. See also HTML5 drag and drop file upload to Java Servlet and Send a file as multipart through XMLHttpRequest.
Monsif's code works well if the form has only file type inputs. If there are some other inputs other than the file type, then they get lost. So, instead of copying each form data and appending them to FormData object, the original form itself can be given to the constructor.
<script type="text/javascript">
var files = null; // when files input changes this will be initialised.
$(function() {
$('#form2Submit').on('submit', uploadFile);
});
function uploadFile(event) {
event.stopPropagation();
event.preventDefault();
//var files = files;
var form = document.getElementById('form2Submit');
var data = new FormData(form);
postFilesData(data);
}
function postFilesData(data) {
$.ajax({
url : 'yourUrl',
type : 'POST',
data : data,
cache : false,
dataType : 'json',
processData : false,
contentType : false,
success : function(data, textStatus, jqXHR) {
alert(data);
},
error : function(jqXHR, textStatus, errorThrown) {
alert('ERRORS: ' + textStatus);
}
});
}
</script>
The HTML code can be something like following:
<form id ="form2Submit" action="yourUrl">
First name:<br>
<input type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lastname" value="Mouse">
<br>
<input id="fileSelect" name="fileSelect[]" type="file" multiple accept=".xml,txt">
<br>
<input type="submit" value="Submit">
</form>
$('#fileUploader').on('change', uploadFile);
function uploadFile(event)
{
event.stopPropagation();
event.preventDefault();
var files = event.target.files;
var data = new FormData();
$.each(files, function(key, value)
{
data.append(key, value);
});
postFilesData(data);
}
function postFilesData(data)
{
$.ajax({
url: 'yourUrl',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
processData: false,
contentType: false,
success: function(data, textStatus, jqXHR)
{
//success
},
error: function(jqXHR, textStatus, errorThrown)
{
console.log('ERRORS: ' + textStatus);
}
});
}
<form method="POST" enctype="multipart/form-data">
<input type="file" name="file" id="fileUploader"/>
</form>
This code works for me.
I used Commons IO's io.jar, Commons file upload.jar, and the jQuery form plugin:
<script>
$(function() {
$('#upload-form').ajaxForm({
success: function(msg) {
alert("File has been uploaded successfully");
},
error: function(msg) {
$("#upload-error").text("Couldn't upload file");
}
});
});
</script>
<form id="upload-form" class="upload-box" action="upload" method="POST" enctype="multipart/form-data">
<input type="file" id="file" name="file1" />
<span id="upload-error" class="error">${uploadError}</span>
<input type="submit" id="upload-button" value="upload" />
</form>
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
try {
// Parse the request
List items = upload.parseRequest(request);
Iterator iterator = items.iterator();
while (iterator.hasNext()) {
FileItem item = (FileItem) iterator.next();
if (!item.isFormField()) {
String fileName = item.getName();
String root = getServletContext().getRealPath("/");
File path = new File(root + "../../web/Images/uploads");
if (!path.exists()) {
boolean status = path.mkdirs();
}
File uploadedFile = new File(path + "/" + fileName);
System.out.println(uploadedFile.getAbsolutePath());
item.write(uploadedFile);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
I have a form in jsp:
<form id="emailForm" data-role="form">
<input type="text" class="form-control" id="name" name="name" placeholder="Enter full name..">
<input type="submit" id="emailSubmit" name="emailSubmit" class="btn btn-default" value="submit">
</form>
I send the form to controller using AJAX:
$("#emailSubmit").click(function(e){
e.preventDefault(); //STOP default action
var postData = $("#emailForm").serializeArray();
$.ajax(
{
type: "POST",
url : "HomeController",
data : postData,
success: function(data)
{
$("#emailResult").html("<p>Thank your for submitting</p>);
},
error: function(jqXHR, textStatus, errorThrown)
{
$("#emailResult").html("<p>ss"+errorThrown+textStatus+jqXHR+"</p>");
}
});
});
I check if it has been submitted in Controller here:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String emailSubmit = request.getParameter("emailSubmit");
if(emailSubmit != null){
// continue
}}
Can someone please tell me why when it checks if form was submitted in the controller that it is null?
For forms the standard way is to catch the submit event instead of the click event of the button:
$("#emailForm").submit(function(e){
e.preventDefault();
var postData = $(this).serializeArray(); // or: $(this).serialize();
$.ajax({
type: "POST",
url : "HomeController",
data : postData,
success: function(data)
{
$("#emailResult").html("<p>Thank your for submitting</p>);
},
error: function(jqXHR, textStatus, errorThrown)
{
$("#emailResult").html("<p>ss"+errorThrown+textStatus+jqXHR+"</p>");
}
});
});
I have tried several methods to be able to check the submit button isn't null and can't solve that issue. For now I have set a hidden input field in the form like so:
<input type="hidden" name="form" value="contactForm">
In controller I check for the form:
String form = request.getParameter("form");
if(form.equals("contactForm")){
// continue
}
Doing this enables me to know which form has been posted to the controller.
refer.jvmhost.net/refer247/registration, this is my url,i have to fetch request to this url like user details and should get the appropriate response in json format with status n error if it contains ..dont give me android code..
this is html page.
<head>
<script type="text/javascript" src="json2.js"></script>
</head>
<body>
<div data-role="page" data-theme="c">
<div data-role="header" data-position="fixed" data-inset="true" class="paddingRitLft" data-theme="c">
<div data-role="content" data-inset="true"> <img src="images/logo_hdpi.png"/>
</div>
</div>
<div data-role="content" data-theme="c">
<form name="form" method="post" onsubmit="return validate()">
<div class="logInner">
<div class="logM">Already have an account?</div>
<div class="grouped insert refb">
<div class="ref first">
<div class="input inputWrapper">
<input type="text" data-corners="false" class="inputrefer" placeholder="Userid" name="userid" id="userid" />
</div>
<div class="input inputWrapper">
<input type="password" data-corners="false" class="inputrefer" placeholder="Password" name="password" id="password" />
</div> <input type="submit" data-inline="true" value="Submit" onclick="json2()">
<p>Forgot Password
</p>
</div>
</div>
<div class="logM">New user? Create refer Account</div>
<input type="button" class="btnsgreen" value="Sign Up! its FREE" class="inputrefer" data-corners="false" data-theme="c" />
</form>
</div>
</div>
<p style="text-align: center;">© refer247 2013</p>
</div>
</body>
this is json2.js
function json2()
{
var json1={"username":document.getElementById('userid').value,
"password":document.getElementById('password').value,
};
//var parsed = jsonString.evalJSON( true );
alert(json1["username"]);
alert(json1["password"]);
};
so tell me how to send the json data to that url n obtain some response like if email
id is already exist if u registering with that id ..then give some error
like email id already exist n if registerd succesfully then give respone like registerd successfully and status msg..200 okk...
You can use ajax to post json data to specified url/controller method. In the below sample I am posting an json object. You can also pass each parameter separately.
var objectData =
{
Username: document.getElementById('userid').value,
Password: document.getElementById('password').value
};
var objectDataString = JSON.stringify(objectData);
$.ajax({
type: "POST",
url: "your url with method that accpects the data",
dataType: "json",
data: {
o: objectDataString
},
success: function (data) {
alert('Success');
},
error: function () {
alert('Error');
}
});
And your method can have only one parameter of string type.
[HttpPost]
public JsonResult YourMethod(string o)
{
var saveObject = Newtonsoft.Json.JsonConvert.DeserializeObject<DestinationClass>(o);
}
$.ajax({
url: urlToProcess,
type: httpMethod,
dataType: 'json',
data:json1,
success: function (data, status) {
var fn = window[successCallback];
fn(data, callbackArgs);
},
error: function (xhr, desc, err) {
alert("error");
},
});
function addProductById(pId,pMqty){
$.getJSON("addtocart?pid=" + pId + "&minqty="+ pMqty +"&rand=" + Math.floor((Math.random()*100)+1), function(json) {
alert(json.msg);
});
}
Here is a simple example, which will call on button click or onclick event and call addtocart servlet and passes 2 argument with it i.e. pId and pMqty.
and after successful completion it return message in alert which is set in that servlet in json.
var json1={"username":document.getElementById('userid').value,
"password":document.getElementById('password').value,
};
$.ajax({
url: '/path/to/file.php',
type: 'POST',
dataType: 'text',//no need for setting this to JSON if you don't receive a json response.
data: {param1: json1},
})
.done(function(response) {
console.log("success");
alert(response);
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
on the server you can receive you json and decode it like so:
$myjson=json_decode($_POST['param1']);
I have the following front end code, I need to get the textfield(id=uid) value and parse it to the servlet and based on that value, fill the other two textfields(It's a Search Function), But following code only retrieves the values, couldn't send the "uid". How could I do that? Please help me.
<script type="text/javascript">
$(document).ready(function(){
$('#getData').click(function(){
$.ajax({
url:'JsonServlet',
type:'post',
dataType: 'json',
success: function(data) {
$('#uname').val(data.uname);
$('#uadd').val(data.uadd);
}
});
});
});
</script>
</head>
<body>
UserID:<input name="userid" type="text" id="uid"/><br/>
Name:<input type="text" id="uname"/>
Address:<input type="text" id="uadd"/>
<input type="button" id="getData" value="Get Data"/>
My servlet Code looks like this
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String userid = request.getParameter("userid");
ResultSet rs = db.selectQuery("select * from tbl_user where userid = '"+userid+"'");
JSONObject json = new JSONObject();
while (rs.next()) {
json.put("uname", rs.getString("username"));
json.put("uadd", rs.getString("useraddress"));
}
//json.put("uname", "user1");
// json.put("uadd", "address1");
out.print(json);
} catch (Exception e) {
e.printStackTrace();
}
your ajax should like this..
$.ajax({
url:'JsonServlet?userid='+document.getElementById("uid").value,
type:'post',
dataType: 'json',
success: function(data) {
$('#uname').val(data.uname);
$('#uadd').val(data.uadd);
}
});
});
the you should able to use String userid = request.getParameter("userid");