Passing file from ajax to spring contorller - ajax

I have form in that, apart from other fields, there is file drop down and file browser button. When the user uploads a file and clicks the button, an Ajax call is made and the file is submitted to the controller. The Javascript shows the file, but in controller it's empty.
HTML:
<label for="selectEnclosure" style="margin-left:8%; ">Select an Enclosure:</label>
<select id="templateEnclosuresDropDown" class="validate[required] input_user" style="width:25%" title="Select>Enclosure"</select>
<c:forEach items="${templateEnclosures}" var="templateDDEnclosure" varStatus="loopStatus">
<c:if test="${templateEnclosure.enclosureType.name!='Default'}"> {
<option value="${templateDDEnclosure.persistentId}"> ${templateDDEnclosure.enclosure.name} </option>
</c:if>
</c:forEach>
<option value="0">Additional Enclosure</option>
Ajax call:
userhome.upload = function() {
alert(" pelae sai");
var form=$('<form></form>');
form.attr("method", "post");
form.attr("action", SECURE_CONTEXT_PATH_ROOT + "/letter/melletter/uploadEnclosure")
form.processData()
var field =$('<input></input>');
field.attr("enclosureFile", $('#enclosureFile').prop('files')[0]);
field.attr("enclosurename" ,$('#templateEnclosuresDropDown :selected').text());
field.attr("templateId",$("#codeNameId").val());
var url = SECURE_CONTEXT_PATH_ROOT + '/letter/melletter/uploadEnclosure';
$(document.body).append(form);
form.submit();
}

First thing to do would be adding this attribute to your form element:
enctype="multipart/form- data"

Related

How do I set selected value that is base on drop-down list in Jquery and assign it to my model?

I need the value from the option to be assigned to my model once the user clicks on the specific option.
<select name="isEmailVerified" class="form-select">
<option value="" selected> all </option>
<option value="true"> verified </option>
<option value="false"> unverified </option>
</select>
expected value => #Model.IsEmailVerified.XXXXX(my value)
What I usually do when I want to asyncronously send data back and forth is this:
I take advantage of Tag Helpers as they're great and saves you a ton of boilerplate code, so I create a standard <form> element without an actual Submit button, just a div that looks like one. You might want to check official MSDN Documentation for the Select Tag Helper to create an appropriate model.
#model VerificationModel
<form asp-action="CheckEmail" method="post">
<select asp-for="IsEmailVerified" asp-items="Model.VerificationTypes">
<div id="SubmitCheck" class="btn">Check email</div>
</form>
Create a javascript function that takes care of the actual submitting chore. Since the form is created with the Tag Helpers, the request body will automatically bind
$('#SubmitCheck').on('click', function() {
let form = $(this).parents('form')[0];
let formData = new FormData(form);
let request = function () {
return fetch(form.getAttribute('action'), {
method: 'POST',
body: formData
});
};
let onresponse = function() {
// do some preliminary actions on 200 response
}
let callback = function() {
// deal with response result
}
let onerror = function() {
// deal with errors
}
request()
.then(response => onresponse())
.then(result => callback())
.fail(err => onerror());
})
Add the [FromForm] attribute to Controller props (model is the same used in the page) to ensure model binding
public async Task<CustomResultClass> CheckEmail([FromForm] VerificationModel model)
{
// do something
}

Get the ID from a button which has a dynamic ID

I can not grasp my mind around this.
I am making a ajax call into a servlet. The problem is, on the page that is displayed, i could have 1-20 different buttons that needs to recall the same servlet. So I have the following form...
<form id="ajax-contact">
<input type="text" value="${item.transactionId}" id="transactionId" name="transactionId"/><br>
<input type="text" value="deliveryReceipt" id="action" name="action"/><br>
<input type="text" value="${item.id}" id="id" name="id"/><br>
<button type="submit" id="${item.id}" class="btn btn-primary" data-toggle="modal" data-target=".${item.id}">view delivery receipt</button>
</form>
In my ajax, I have this...
$(function() {
// Get the form.
var form = $('#ajax-contact');
// Get the messages div.
var formMessages = $('#form-messages');
// Set up an event listener for the contact form.
$(form).submit(function(e) {
// Stop the browser from submitting the form.
e.preventDefault();
// Serialize the form data.
//var formData = $(form).serialize();
var id = $("#id").val();
var tranid = $("#transactionId").val();
var action = $("#action").val();
var dataFromForm = "trannsactionId="+tranid+"&action="+action+"&id="+id;
alert(dataFromForm);
alert(formData);
// Submit the form using AJAX.
$.ajax({
url : "Controller",
type: "GET",
data : dataFromForm,
dataType: "json",
})
.success(function(response) {
...
I am trying to make it so the ajax call uses the params for the specific set of information within the form. How can I do this?
Thanks!
More detail:
Once this page shows, if I have 10 sections on there with a button. When I click on the first view delivery receipt button, it works fine.
If I go down my list and click on t he 8th view delivery receipt, itll make an ajax call for the first form.

how to retain dynamic dropdown values after page refresh using spring and jsp

I am having 3 dropdowns.customername and companyname and servername.like this..
Based on Customer drop down i am populating Company Names.and based on Company names dropdown i am population server names using Spring and javascript.
If i click go button my page is refreshing.That time my droddown values are not retaining..
Can you any one suggest me regarding to this.
This is my code:
on click of customer dropdown i am calling onchange method in jsp.
<td valign="bottom">
<form:select path="CustomerId" id="customerDetails">
<option selected="selected" disabled="disabled">Select Customer</option>
<form:options items="${map.customerList}"
itemLabel="customerName" itemValue="customerId" />
</form:select> <br>
</td>
with this i am getting my customer dropdown values.Onchange of the customer i am getting company names..
<script>
$(document).ready(function() {
$("#customerDetails").change(function() {
var value1 = $('#customerDetails :selected').text();
$.ajax({
type : 'POST',
url : 'companynames',
data : {
selectedcustomername : value1
},
success : function(result) {
getcompNames(result);
}
});
});
});
</script>
Controller's code:
#RequestMapping(value = "/companynames", method = RequestMethod.POST)
public #ResponseBody String getEnvironmentNames(HttpServletRequest request,
HttpServletResponse response, #RequestParam String selectedcustomername) throws SQLException {
request.setAttribute("selectedcustomername", selectedcustomername);
System.out.println("selectedcustomername"+selectedcustomername);
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("environments", new Environments());
List<Environments> environmentnamesList= loginDelegate.getEnvironments(selectedcustomername);
Collections.sort(environmentnamesList, new CustomComparator());
Gson gson = new Gson();
System.out.println("gson"+gson);
String jsonString = gson.toJson(environmentnamesList);
System.out.println("jsonString"+jsonString);
return jsonString;
}
Processing response of controller:
<script language="JavaScript">
function getcompNames(result){
$('#environmentName').empty().append('<option selected="selected" disabled="disabled">Select An Environment</option>');
var data = JSON.parse(result);
$.each(data, function(key, value)
{
$("#environmentName").append("<option>" + value.environments_name +" - "+ value.environments_purpose + "</option>");
});
}
This is my company ui code.
<td width="20%" nowrap="nowrap" class="boldFontSize3">
<b>Company:</b>
<select class="body" name="environmentName" id="environmentName" class="body">
<option selected="selected">Select a comapany name</option>
</select>
</td>
Like this way only i am getting servername.
Go button code:
<input name="Submit" value="Go" type="submit" class="boldFontSize3" />
after clicking go button my dropdown values are null
..my problem is when user click on go button my page is refreshing.i am getting customer dropdown values from modelandview object.For that i am getting customer dropdown values.But after page refresh i am not getting companynames and server.Because restcall will happen only onchange of customer Dropdown only.

Validation of dynamic created form (AngularJS)

I try to made nested form with validation. All works fine, but when I remove one of nested form, validation continue to use removed form. I made jsfiddle example http://jsfiddle.net/sokolov_stas/VAyXu/
When example runs, form are valid. If click "+" button, nested form will be added and valid will be false. Then click "-" button, and valid will be false all the same.
The question is: How to remove dynamic created form from validation processing.
Well, for one thing, a <form> inside of a <form> is not valid HTML.
Second, you're not supposed to be doing DOM manipulation from inside the controller. The controller is for "business" logic. See the section on controllers here
For what you're doing, you'd probably be better off using one form, with an ng-repeat inside of it, and adding additional elements to an array:
<form name="myForm" ng-controller="FormCtrl" ng-submit="doSomething()">
<div ng-repeat="item in items">
<input ng-model="item" type="text" required/>
</div>
<a ng-click="addItem()">+</a>
<a ng-click="removeItem()">-</a>
<button type="submit">Submit</button>
<div>Form valid: {{myForm.$valid}}</div>
</form>
and the controller:
function FormCtrl($scope) {
$scope.items = [];
$scope.addItem = function() {
$scope.items.push(null);
};
$scope.removeItem = function() {
$scope.items.pop();
};
$scope.doSomething = function () {
//your submission stuff goes here.
};
}

jQuery returning null - selected option not being posted correctly?

This jQuery script is returning null. I've tried using other syntax for selected options but here's what I've got below:
The script works and runs correctly, allowing me to download the Excel file. However the ID is not being set correctly (via the option selected) and thus is parsing as "0".
<script>
//When Page Loads....
$(document).ready(function(){
$('#dropdown').change(function(){
// Call the function to handle the AJAX.
// Pass the value of the text box to the function.
sendValue($(this).val());
});
});
// Function to handle ajax.
function sendValue(str){
// post(file, data, callback, type); (only "file" is required)
$.post(
"scripts/export_to_excel/index.php", //Ajax file
{ sendValue: str }, // create an object will all values
//function that is called when server returns a value.
function(data){
$('#linkDiv').html(data.returnValue);
},
//How you want the data formatted when it is returned from the server.
"json"
);
}
</script>
Select HTML
<p>Select event for export to Excel:</p>
<p>
<select name="eventIDExport" id="dropdown">
<option value=0>
<?=$options?>
</select>
</p>
<?php var_dump($_POST['eventIDExport']); ?>
<div id="linkDiv"></div>
Rendered mark-up
<p>Select event for export to Excel:</p>
<p>
<select name="eventIDExport" id="dropdown">
<option value=0>
<option value="1">BIG event</option>
<option value="54">2013 Network Conference</option>
</select>
</p>
NULL
<div id="linkDiv"></div>
Some of the code in index.php to process Ajax request - I think this is triggering the null value?
if (isset($_POST['eventIDExport']))
{
$eventIDExport = $_POST['eventIDExport'];
}else{
$eventIDExport = "";
}
Why you POST sendValue and check if eventIDExport is set?
$.post("scripts/export_to_excel/index.php", {
sendValue: str
^^^^^^^^^
and
if (isset($_POST['eventIDExport']))
^^^^^^^^^^^^^
Your code should be:
if(isset($_POST['sendValue']))
{
$eventIDExport = $_POST['sendValue'];
} else {
$eventIDExport = "";
}
or
$.post("scripts/export_to_excel/index.php", {
eventIDExport: str

Resources