This question already has answers here:
Send a file as multipart through XMLHttpRequest
(2 answers)
Closed 7 years ago.
hello stackoverflow team, i am using a button with onclick function on it which make call to an ajax and that ajax populate a form in a div under that button. In the form there are various text fields and one input type=file now i want to upload this file using ajax and side by side upload the data into data base. I can upload the data to the database using ajax, but i am unable to upload the file using ajax. Here is my js code
var selectedCategory = $("#category option:selected").val();
var prod_name = $("#prod_name").val();
var prod_code = $("#prod_code").val();
var price = $("#price").val();
var age = $("#age").val();
var description = $("#description").val();
var img_path = $("#image_path").val();
var formValues = "&selectedCategory="+selectedCategory+
"&prod_name="+prod_name+
"&prod_code="+prod_code+
"&price="+price+
"&age="+age+
"&description="+description+
"&image_path="+img_path;
alert(formValues);
uploadData(formValues);
$.ajax({
url: "UploadFile",
type: 'POST',
data: img_path,
success: function (data)
{
$("#panel_body").html(data);
//showProducts();
}
});
}
Here is my form that is created using ajax call to my servlet:
<table cellpadding="5" cellspacing="5" style="margin: 0 auto;" id="add_record_table">
<form action="UploadImage" method="post" enctype="multipart/form-data"></form>
<tbody><tr>
<td><label>Select Category</label></td>
<td>
<select name="category" id="category"><option id="0" value="-1">--Select category--</option><option id="1" value="Alphabets and Numbers">Alphabets and Numbers</option></select>
</td>
</tr>
<tr>
<td>
<label>Product Name</label>
</td>
<td>
<input type="text" name="prod_name" id="prod_name" placeholder="Product Name">
</td>
</tr>
<tr>
<td>
<label>Product Code</label>
</td>
<td>
<input type="text" name="prod-code" id="prod_code" placeholder="Produce Code">
</td>
</tr>
<tr>
<td>
<label>Price</label>
</td>
<td>
<input type="text" name="price" id="price" placeholder="Price">
</td>
</tr>
<tr>
<td>
<label>Recomended Age</label>
</td>
<td>
<input type="text" name="age" id="age" placeholder="Recomended Age">
</td>
</tr>
<tr>
<td>
<label>Description</label>
</td>
<td>
<textarea id="description" rows="5" cols="50" placeholder="Description" style="resize: vertical; max-height: 250px;"></textarea>
</td>
</tr>
<tr>
<td>
<label>Upload Image</label>
</td>
<td>
<input type="file" name="image_path" id="image_path" accept="image/jpeg">
</td>
</tr>
<tr>
<td>
</td>
<td>
<input type="submit" name="submit" onclick="validateForm();" class="btn btn-primary btn-large" value="ADD" id="add_data">
</td>
</tr>
</tbody></table>
Please assist me to get through this problem.
you can upload your files via ajax here is the example
var fileInput = document.getElementById('image_path');
var file = fileInput.files[0];
var formData = new FormData();
formData.append('comprobante', file);
.... and all more data like:
formData.append('age', age);
...data...
$.ajax({
data: formData,
url: 'UploadFile',
type: 'post',
processData: false,
contentType: false,
success:function (data)
{
$("#panel_body").html(data);
//showProducts();
}
});
Then you should handle the file uploaded in the backend.
Related
<form name="update" id="update" action="update" method="post">
<table border="0">
<tr>
<th></th>
<th>Del</th>
<th>Name</th>
<th>Address</th>
<th>Remarks</th>
</tr>
<c:forEach items="${recList}" var="rec" varStatus="loop">
<tr>
<td><input type="checkbox" name="del" value="${loop.index}"/></td>
<td><input type="text" name="name" value="${rec.getName()}"/></td>
<td><input type="text" name="address" value="${rec.getAddress()}"/></td>
<td><input type="text" name="remarks" value="${rec.getRemarks()}"/></td>
<td><input type="hidden" name="index" value="${loop.index}"/>
<input type="submit" value="Update"/></td>
</tr>
</c:forEach>
</table>
</form>
This is my code for this view
My problem is when I click the UPDATE button, the form seems to send series of values like
name= "aiko,hashimoto,yuki,ode"
instead of sending only
name="hashimoto"
to the Controller if second UPDATE button is clicked. Can anyone help me with my issue?
<form> tag can't be inside <table>. By logic, I think it's best to put the inside the loop but it is not possible. Is there another way to solve this?
Submit your form with javascript function using ajax call like below sample code.
send single value from form submit not possible
function submitform(){
var messageId = $("#messageId").val();
$.ajax({
url:'<c:url value="/dummy/dummyMessageId"/>',
datatype:'JSON',
data: 'messageId=' + messageId ,
success : function(response) {
if (null != response && response.success) {
} else {
var errorDiv = $('#Error');
errorDiv.html(response.error.message);
}
}
});
}
<input type="button" value="Update" onclick="submitform()"/></td>
add above code in your HTML input button
i have a thymeleaf form that can validate data from the database through spring controller, the data validation works fine, but when i want to validate with different data after validation it give me an Error 400, there's no error in the stack trace, so i don't know how how to fix this, maybe because of my bad logic, because i'm newbie at this..
here's the form
<form th:name="memberRkiForm" id="memberRkiForm" th:action="#{/}" th:object="${formResult}"
method="POST">
<div>
<table id="form">
<tr>
<td colspan="7" height="40"><img class="formlogo"
th:src="#{/resources/img/docicon.png}">
<h3 class="formHeader"><b><u>REGISTER MANUAL</u></b></h3></td>
</tr>
<tr>
<td>
<label>Provider Name </label>
</td>
<td><label>:</label></td>
<td>
<input type="text" th:value="${providerId}" name="providerId" style="width:275px;"
readonly="readonly" hidden="hidden"> </input>
<input type="text" th:value="${providerName}" name="providerName" style="width:275px;"
readonly="readonly"> </input>
</td>
<td class="sep"></td>
</tr>
<tr>
<td>
<label>Member Card Number* </label>
</td>
<td><label>:</label></td>
<td>
<input type="text" name="cardNumber" th:field="*{cardNumber}"
onkeypress="return isNumberKey(event)"
style="width:190px; display: inline;"> </input>
<input id="checkCardNum" class="default-button" type="submit" style="display: inline;"
value="Validasi">
</td>
<td width="500">
<div class="error" style="display:inline;color:red;">
<p id="cardNumError" style="margin-left:15px;" th:text="${cardNumError}"></p>
</div>
</td>
<td class="sep"></td>
</tr>
<tr>
<td>
<label>Member Name </label>
</td>
<td><label>:</label></td>
<td>
<input type="text" th:value="${memberName}" name="memberName" style="width:275px;"
readonly="readonly"> </input>
</td>
<td class="sep"></td>
</tr>
<tr>
<td>
<label>Date Of Birth </label>
</td>
<td><label>:</label></td>
<td>
<input type="text" th:value="${birthday}" name="birthday" style="width:275px;"
readonly="readonly"> </input>
</td>
<td class="sep"></td>
</tr>
<tr>
<td><label>Client Name </label></td>
<td><label>:</label></td>
<td>
<input type="text" th:value="${clientName}" name="clientName" style="width:275px;"
readonly="readonly"> </input>
</td>
<td class="sep"></td>
</tr>
<tr>
<td>
<label>Admission Date </label>
</td>
<td><label>:</label></td>
<td>
<input id="datepicker" type="text"
style="margin-top:4px;width:230px;display:inline-block;"/>
<span class="calendarbox"><img th:src="#{/resources/img/calendar.png}" height="25"
width="35"></span>
</td>
<td class="sep"></td>
</tr>
<tr>
<td><label>Claim Service* </label></td>
<td><label>:</label></td>
<td>
<input type="text" th:value="${selectServiceIsEnabled}" name="selectServiceIsEnabled"
style="width:275px;" readonly="readonly" hidden="hidden"> </input>
<select id="selectservice" th:field="*{caseCategoryList}" class="selectcss"
style="width:275px;margin-left: 5px;" disabled="disabled">
<option th:each="case : ${caseCategoryList}" th:value="${case.caseCategoryId}"
th:text="${case.caseCategoryName + ' - ' + case.caseCategoryCode}"></option>
</select>
</td>
<td width="500">
<span class="error" style="display: inline;color:red;"><p id="select_error"></p></span>
</td>
<td class="sep"></td>
</tr>
<tr colspan="7" class="jumper"></tr>
<tr>
<td>
<input id="addMember" class="remodal-confirm" type="submit" name="action"
value="Register"/>
<input class="remodal-cancel" type="reset" value="Clear"/>
</td>
</tr>
</table>
</div>
</form>
when validate button is clicked, the form action goes to a spring controller that check the card number to the database (checkCardNum), then if the data validation return true, the form will be automatically filled by the data that related to the card number, after the form's filled with the data, i want to check validation with another card number (different from the first validated card number), but it give me an error 400.
here's my controller
#PreAuthorize("hasAuthority('"+ACLConstant.MENU_REGISTRATIONMEMBERRKI+"')")
#RequestMapping(value="/member-rki-form",method={RequestMethod.GET , RequestMethod.POST} )
public String memberrkiform(Model model, HttpServletRequest request, #ModelAttribute("formResult") MemberRkiForm formResult){
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
UserAuth userAuth = (UserAuth)auth.getPrincipal();
String[] cols = {"username", "deletedStatus"};
Object[] values = {userAuth.getUserName(), 0};
Users user = userService.findUserByColsAndValues(cols, values);
int userid = user.getUserId();
Users currentUser = userService.findUserByPK(userid);
Provider provider = currentUser.getProvider();
model.addAttribute("providerId", provider.getProviderId());
model.addAttribute("providerName", currentUser.getFirstName());
model.addAttribute("cardNumber", formResult.getcardNumber());
model.addAttribute("cardNumError", formResult.getErrorMsg());
model.addAttribute("memberName", formResult.getMemberName());
model.addAttribute("birthday", formResult.getBirthday());
model.addAttribute("clientName", formResult.getClientName());
model.addAttribute("caseCategoryList", formResult.getCaseCategoryList());
model.addAttribute("selectServiceIsEnabled", formResult.getSelectServiceIsEnabled());
return "memberrki/member-rki-form";
}
#RequestMapping(value="/checkCardNum",method={RequestMethod.GET , RequestMethod.POST})
public String checkCardNum(#ModelAttribute("formResult") MemberRkiForm formResult, Model model, HttpServletRequest request, RedirectAttributes redirectFormData){
String errorMsg = "";
String cardNumber = formResult.getcardNumber();
if(cardNumber==null || cardNumber==""){
errorMsg="Card Number Data Is Required";
}
else{
String[] cols = {"currentCardNumber", "deletedStatus" , "subscriptionStatus"};
Object[] values = {formResult.getcardNumber(), 0 , 1};
Member member = memberService.findMemberByColsAndValues(cols, values);
if(member==null){
errorMsg="Member Not Found";
}
else{
Member validatedMember = memberService.findMemberByPK(member.getMemberId());
Client validatedMemberClient = validatedMember.getClient();
formResult.setMemberName(validatedMember.getFirstName());
formResult.setBirthday(validatedMember.getBirthday().toString());
formResult.setClientName(validatedMemberClient.getClientName());
MemberProductSearchParams memberProductParams = new MemberProductSearchParams();
memberProductParams.setMember(validatedMember);
memberProductParams.setDeletedStatus(0);
memberProductParams.setSubscriptionStatus(1);
Page<MemberProduct> memberProductPage = memberService.findMemberProductListing(memberProductParams, null);
List<MemberProduct> memberProductLists = memberProductPage.getContent();
if(memberProductPage==null || memberProductLists==null){
/*System.out.println("NO PRODUCT FOUND");*/
errorMsg="NO PRODUCT AVAILABLE";
}
else{
List<Product> productList = new ArrayList<Product>();
List<CaseCategory> caseCategoryList = new ArrayList<CaseCategory>();
for(int i=0; i<memberProductLists.size(); i++){
String[] productCols = {"productId", "deletedStatus"};
Object[] productValues = {memberProductLists.get(i).getProduct().getProductId(), 0};
Product products = productService.findProductByColsAndValues(productCols, productValues);
productList.add(products);
String[] caseCategoryCols = {"caseCategoryId", "deletedStatus"};
Object[] caseCategoryValues = {productList.get(i).getCaseCategory().getCaseCategoryId(), 0};
CaseCategory caseCategories = caseCategoryService.findCaseCategoryByColsAndValues(caseCategoryCols, caseCategoryValues);
caseCategoryList.add(caseCategories);
}
formResult.setCaseCategoryList(caseCategoryList);
}
formResult.setSelectServiceIsEnabled("true");
}
}
formResult.setErrorMsg(errorMsg);
formResult.setcardNumber(cardNumber);
redirectFormData.addFlashAttribute("formResult", formResult);
formResult = new MemberRkiForm();
return "redirect:/memberrki/member-rki-form";
}
}
maybe someone here can help me to solve the problem,
Thx in advance.. (sorry for my bad english)
Please help me with this JSP dropdown that I want to implement using JSON.
I am getting 500 error:
GET http://localhost:8080/ProjectManager/getEmployeesInProject.view?projectId=1 500 (Internal Server Error)
This is the script that I am using:
Hi Guys, Please help me with this dropdown that I want to implement using JSON.
I am getting 500 error:
GET http://localhost:8080/ProjectManager/getEmployeesInProject.view?projectId=1 500 (Internal Server Error)
This is the script that I am using:
<script>
$(document).ready(function(){
$('select#projectList').change(function(e){
// Your event handler
//alert(1);
$.getJSON ("getEmployeesInProject.view", {projectId: $(this).val()},
function(j) {
alert('j.length '+j.length);
var options = '';
for (var i = 0; i < j.length; i++){
options += '<option value="' + j[i].id + '">' + j[i].name + '</option>';
}
$("select#employeeList").html(options);
});
});
});
</script>
My JSP form is :
<br />
<br />
<table width='670'>
<tr>
<td width='600'>Projects *</td>
<td>
<select id="projectList">
<c:forEach var="listProjects" items="${listProjects}"
varStatus="i">
<option value="${projectId[i.index]}">${listProjects}</option>
</c:forEach>
</select></td>
</tr>
<tr>
<td width='600'>Descriptions*</td>
<td><input type="text" id="taskDescription"></td>
</tr>
<tr>
<td width='600'>Start Date of Task[dd-mm-yyyy]*</td>
<td><input type="text" id="taskDescription"></td>
</tr>
<tr>
<td width='600'>Due Date of Task[dd-mm-yyyy]*</td>
<td><input type="text" id="taskDescription"></td>
</tr>
<tr>
<td width='600'>Who should do this? *</td>
<td><select id="employeeList">
<c:forEach var="listEmployee" items="${listEmployee}">
<option>${listEmployee}</option>
</c:forEach>
</select></td>
</tr>
<tr>
<td> <input type = "submit" value = "Add a task" /></td>
</tr>
</table>
</form:form>
This is my controller part:
#RequestMapping(value="getEmployeesInProject.view")
#Transactional
public #ResponseBody List<Employee> fetchEmployeesInProject(#ModelAttribute("project") Project project, #RequestParam(value="projectId", required=true) int projectId, ModelMap modelMap){
return assignTasksService.fetchEmployeesInProject(projectId);
}
I have a simple login page and I am using Ajax to check the user credentials.
if true it should redirect to another page, else it should throw an error message.
<script type="text/javascript">
function btnSignIn(){
var uName = document.getElementById("uName").value;
var pass = document.getElementById("pass").value;
$.ajax({
url: "/orgNgo/SignIn",
type: "POST",
data: {
"uName" : uName,
"pass" : pass
} ,
success:function() {
//... your other code
//location.reload(); //reload the page on the success
document.getElementById("lblError").innerHTML="Error";
}
});
}
</script>
<table>
<tr>
<td>
UserName:
</td>
<td>
<input type="text" id="username" name="uName"/>
</td>
<td>
<label style="visibility: hidden;">required</label>
</td>
</tr>
<tr>
<td>
Password:
</td>
<td>
<input type="text" id="password" name="pass"/>
</td>
<td>
<label style="visibility: hidden;">required</label>
</td>
</tr>
<tr>
<td colspan="3">
<input type="button" onclick="btnSignIn()" value="Submit"/>
</td>
</tr>
<tr>
<td colspan="3">
Not a member yet? SignUp
</td>
</tr>
</table>
Servlet code
if(repeatUsername){//if user name and password matches it comes to this loop
stmt.close();
c.close();
session.setAttribute("lib", uName);
request.getRequestDispatcher("/user/UserHome.jsp").forward(request,response);
//not working
}
else{
String loginError = "UserName or Password is wrong";
request.setAttribute("loginError", loginError);
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(String.valueOf(loginError));
//not working
}
Here if the user credentials are true the page is not getting redirected. when I debugged the code I found that it is reflecting in the console. And if the user credentials doesn't match it loginError String isn't getting passed to the success function of Ajax.
I'm practising Ajax for a week but usually it would be just jsp to servlet but here I'm stuck because its a two way thing.
Thanks in advance for helping out.
success: function() {
window.location = "another page";
}
will redirect to another page.
And it is up to you to check credencial
I am making an online shopping website. I want to provide an option to user that he/she can select different shipping address :-
Shipping Details
<input type="button" value="Same as billing address" style="color: #FFFFFF;" class="link-style" onclick="test();" />
<table cellpadding="20">
<tr>
<td >Name : * </td>
<td><input type="text" id="name" name="name" /></td>
</tr>
<tr>
<td>Contact Number : </td>
<td><input type="text" name="cno" id="cno" /></td>
</tr>
<tr>
<td>Address : * </td>
<td><input type="text" name="address "id="address" /></td>
</tr>
<tr>
<td>City : *</td>
<td><input type="text" name="city" id="city" /></td>
</tr>
<tr>
<td>State : * </td>
<td><input type="text" name="state" id="state" /></td>
</tr>
<tr>
<td>Country : *</td>
<td><input type="text" name="country" id="country" /></td>
</tr>
</table>
if user clicks on button then all fields are disabled. Otherwise he/she can fill diffrent shipping address. Problem is i don't want to use forms here. How to pass these parameters to a jsp or servlet in session or post? I already tried AJAX but i am unable to work with it properly
function setValue() {
alert("hi");
var name = document.getElementById("name").value;
var cno = document.getElementById("cno").value;
var address = document.getElementById("address").value;
var city = document.getElementById("city").value;
var state = document.getElementById("state").value;
var country = document.getElementById("country").value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("post", "test.jsp", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form- urlencoded");
xmlhttp.send("name=" + name);
xmlhttp.send("cno=" + cno);
xmlhttp.send("address=" + address);
xmlhttp.send("city=" + city);
xmlhttp.send("state=" + state);
xmlhttp.send("country=" + country);
}
Test.jsp is not getting the parameters.
You must only call xmlhttp.send once, which requires you to concatenate the request parameters.
xmlhttp.send("name="+name+"&cno="+cno+"&address="+address+"&city="+city+"&state=" + state + "&country="+country);
try like this:
var inputParam='{"name":"'+name+'","cno":"'+cno+'","address":"'+address+'","city":"'+city+'","state":"'+state+'","country":"'+country+'"}';
$.ajax({
type: "POST",
url: your base_url,
data: {inputParam:inputParam,module :'your module name'},
dataType: "json",
async:false,
success: function(msg)
{
console.log(msg);
}
});