Send and Retrieve Data using JSON and AJAX - java

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");

Related

file and form upload at the same time using ajax in java web [duplicate]

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();
}
}

How to check if form was submitted in Java

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.

Ajax error not loading message

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);
}
});
};

table search data can be shown... search function ok... display error

<in search.php>
<?php require_once("../includes/session.php"); ?>
<?php require_once("../includes/connection.php") ?>
<?php require_once("../includes/functions.php") ?>
<?php
$searchq = $_POST['searchq'];
$tablehead="<tr><th>Product Name</th><th>Category</th><th>Price</th><th>Discount</th><th>Edit</th></tr>";
$tabledata = "";
if(empty($searchq)) {
echo "";
} else {
//If there is text in the search field, this code is executed every time the input changes.
echo "<div id='results'-->"; //this div is used to contain the results. Mostly used for styling.
//This query searches the name field for whatever the input is.
$sql = "SELECT * FROM `tblstudent` WHERE `student_id` LIKE '%$searchq%' or `name` LIKE '%$searchq%' or `email` LIKE '%$searchq%'";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)) {
$id = $row['id'];
$student_id=htmlentities($row['student_id']);
$hashed_password=htmlentities($row['hashed_password']);
$name=htmlentities($row['name']);
$email=htmlentities($row['email']);
"this is the part that i add on but not work, error-free"
$tabledata.="<tr id='$id' class='edit_tr'><td class='edit_td' >
<span id='one_$id' class='text'>$student_id</span>
<input type='text' value='$student_id' class='editbox' id='one_input_$id' />
</td>
<td class='edit_td' >
<span id='two_$id' class='text'>$hashed_password</span>
<input type='text' value='$hashed_password' class='editbox' id='two_input_$id'/>
</td>
<td class='edit_td' >
<span id='three_$id' class='text'>$name $</span>
<input type='text' value='$name' class='editbox' id='three_input_$id'/>
</td>
<td class='edit_td' >
<span id='four_$id' class='text'>$email $</span>
<input type='text' value='$email' class='editbox' id='four_input_$id'/>
</td>
<td><a href='#' class='delete' id='$id'> X </a></td>
</tr>";
}
$finaldata = "<table width='100%'>". $tablehead . $tabledata . "</table>"; // Content for Data
}
echo "</div>";
?>
this is the js query plug in.
<EditDeletePage.js>
$(document).ready(function()
{
$(".delete").live('click',function()
{
var id = $(this).attr('id');
var b=$(this).parent().parent();
var dataString = 'id='+ id;
if(confirm("Sure you want to delete this update? There is NO undo!"))
{
$.ajax({
type: "POST",
url: "delete_ajax.php",
data: dataString,
cache: false,
success: function(e)
{
b.hide();
e.stopImmediatePropagation();
}
});
return false;
}
});
$(".edit_tr").live('click',function()
{
var ID=$(this).attr('id');
$("#one_"+ID).hide();
$("#two_"+ID).hide();
$("#three_"+ID).hide();
$("#four_"+ID).hide();
$("#one_input_"+ID).show();
$("#two_input_"+ID).show();
$("#three_input_"+ID).show();
$("#four_input_"+ID).show();
}).live('change',function(e)
{
var ID=$(this).attr('id');
var one_val=$("#one_input_"+ID).val();
var two_val=$("#two_input_"+ID).val();
var three_val=$("#three_input_"+ID).val();
var four_val=$("#four_input_"+ID).val();
var dataString = 'id='+ ID +'&name='+one_val+'&category='+two_val+'&price='+three_val+'&discount='+four_val;
if(one_val.length>0&& two_val.length>0 && three_val.length>0 && four_val.length>0)
{
$.ajax({
type: "POST",
url: "live_edit_ajax.php",
data: dataString,
cache: false,
success: function(e)
{
$("#one_"+ID).html(one_val);
$("#two_"+ID).html(two_val);
$("#three_"+ID).html(three_val);
$("#four_"+ID).html(four_val);
e.stopImmediatePropagation();
}
});
}
else
{
alert('Enter something.');
}
});
// Edit input box click action
$(".editbox").live("mouseup",function(e)
{
e.stopImmediatePropagation();
});
// Outside click action
$(document).mouseup(function()
{
$(".editbox").hide();
$(".text").show();
});
//Pagination
function loading_show(){
$('#loading').html("<img src='images/loading.gif'/>").fadeIn('fast');
}
function loading_hide(){
$('#loading').fadeOut('fast');
}
function loadData(page){
loading_show();
$.ajax
({
type: "POST",
url: "load_data.php",
data: "page="+page,
success: function(msg)
{
$("#container").ajaxComplete(function(event, request, settings)
{
loading_hide();
$("#container").html(msg);
});
}
});
}
loadData(1); // For first time page load default results
$('#container .pagination li.active').live('click',function(){
var page = $(this).attr('p');
loadData(page);
});
$('#go_btn').live('click',function(){
var page = parseInt($('.goto').val());
var no_of_pages = parseInt($('.total').attr('a'));
if(page != 0 && page <= no_of_pages){
loadData(page);
}else{
alert('Enter a PAGE between 1 and '+no_of_pages);
$('.goto').val("").focus();
return false;
}
});
});
I edit from the http://palavas.biz/forum/viewtopic.php?f=51&t=4143&sid=9241f1f287fc672cc32f91a06b93f4c3#.UjqVx9Jmim4 but not work... i try to change the function that already have a table display to a search function only display out. but unfortunately I can't display out the data which list inside the table when type words in the search keyword textbox.

Getting Response Text From Ajax Call

I am trying to get the response from an Ajax call into a html label. I am using a tomcat server. Ia m able to see the description returned form the server however how do i get the responses into the lable text. Under is what i have tried:
Jquery
function GetDescription(Id){
$.ajax({
type:'GET',
url:'getDescription.htm',
data:{dId:Id},
dataType: 'json',
success: function (data) {
$('.TypeDesc').text = data.responseText;
}
});
}
$(document).ready(function() {
$(".photos").each(function(i){
if ($(this).val() != '') {
var image = new Image();
image.src = $(this).val();
image.onload = function(){
var typeId = document.getElementsByClassName("TypeId")[i].value;
GetDescription(typeId);
var ctx = document.getElementsByClassName("canvas")[i].getContext('2d');
ctx.drawImage(image,0,0, 320, 240);
}
}
});
});
html
</head>
<body>
<div id ="content">
<c:forEach items="${object}" var="i">
<div id="table">
<div>
<p><canvas class="canvas" height="240" width="320"></canvas>
</div>
Name:- ${i.fName} ${i.lName}
<input type="hidden" id="photo" value="${i.photo}" class="photos"/>
<input type="hidden" id="Number" value="${i.Number}" />
<input type="text" class="TypeId" value="${i.citizenTypeId}"/>
<label class="TypeDesc"></label>
</div>
</c:forEach>
</div>
</body>
</html>
The problem is that you're telling jQuery you're expecting JSON:
dataType: 'json',
...and so it's (trying to) parse the response as JSON and pass you an object, but then you're trying to use it like a raw XHR object.
If you want the text, remove the dataType or change it to dataType: 'text', and then use data which will be a string.
Your other problem is that text is a function, not a property, so you need to call it.
So:
dataType: 'text',
success: function (data) {
$('.TypeDesc').text(data);
}
Please add this to the parameters of the ajax call
success: function(data) {
$('.TypeDesc').each(function(){
$(this).text(data);
});
}
You need to give the lable a unique ID like id="TypeDesc{i}" or something different.
So you can refer to it something like this:
$('#TypeDesc{i}').text = data.responseText;

Categories