Am using Jquery FormData for the first time, but seems am missing something. In the JS - postAjax method, when new FormData() is called, it just skips the remaining lines and goes to the end of the function without any errors. What am I doing wrong here?
template.js //script files in this order
<script src="js/jquery-2.1.0.js"></script>
<script src="js/jquery.form.js"></script>
<script src="js/bootstrap.js"></script>
<script src="js/bootstrapValidator.js"></script>
<script src="js/hemoncCBCFunctions.js"></script>
<script src="js/validations.js"></script>
JSP
<form name ="newSectionSubmitForm" id="newSectionSubmitForm" class="form-horizontal" role="form" method="post" ENCTYPE="multipart/form-data">
<table>
<tr>
<td>
<input type="file" id='imageFile0' name='imageFile0' class="form-control" />
</td>
</tr>
</table>
<form>
JS
function submitNewSection(targetUrl, form) {
postAjaxData(null, 'content', targetUrl, form, null, null);
}
function postAjaxData(initiatingElement, targetElement, targetUrl, form,
additionalParamMap, successCallback) {
var $targetElement = $('#' + targetElement);
var serializedFormData;
serializedFormData = $('#' + form).serialize();
for ( var j in additionalParamMap) {
serializedFormData += "&" + j + "=" + additionalParamMap[j];
}
alert('serialized form data ' + serializedFormData);
var formData = new FormData(serializedFormData);//**exits the function no errors**
formData.append("file", $('#imageFile0').files[0]);
alert('serialized form data ' + formData);
$.ajax({
type : "POST",
cache : false,
data : formData,
url : targetUrl,
success : function(data) {
processRedirect(data);
$targetElement.html(data);
$targetElement.show();
if (successCallback != null) {
successCallback(data);
}
},
error : function(xhr, httpRequest, textStatus, errorThrown) {
var errorId = xhr.getResponseHeader("errorId");
var errorMsg = xhr.getResponseHeader("errorMessage");
if (errorId != null && errorId != undefined) {
$("#page_error").html(
"An unexpected error has occurred. Error Id: "
+ errorId);
} else {
$("#page_error").html("An unexpected error has occurred.");
}
},
});
Controller File (however the code does not reach here)
#RequestMapping(value = "/submitNewSection.html")
public String submitNewSection( MultipartHttpServletRequest req, HttpServletRequest request, Model model) {
Iterator<String> itr = req.getFileNames();
MultipartFile mpf = req.getFile(itr.next());
System.out.println("file name " + mpf.getOriginalFilename() +" uploaded!");
}
Thanks so much.
Related
I am doing my application in MVC. I did cascading dropdownlist in list . While selecting the value from dropdown i passed the value by $.getJson() to the controller. I am passing one id to the controller. My problem is i need to pass 2 id's to the controller. Is it possible to send 2 ids to the controller?
My View page is
<div>
#Html.DropDownList("Business", ViewBag.CategoryID as SelectList ,"Select the Business Category", new { id = "Business" })
</div>
<div>
<label>Select the Service Type</label>
#*<select id="Buname" name="buname" style="width:150px"></select>*#
#Html.DropDownList("Service", ViewBag.Service as SelectList,"Select", new { id = "Service", name ="buname"})
</div>
<div>
<label> Select the Location</label>
<select id="Location" name="location" style="width:150px"></select>
</div>
<div>
<label> Select the Location</label>
<select id="Employee" name="employee" style="width:150px"></select>
</div>
<script type="text/javascript">
$(function () {
$('#Business').change(function () {
$.getJSON('/Appt/Categories/' + $('#Business').val(), function (data) {
var items = '<option> Any Hospital</option>'
$.each(data, function (i, Service) {
debugger;
items += "<option value='" + Service.Value + "'>" + Service.Text +
"</option>";
});
$("#Service").html(items);
});
});
$('#Service').change(function () {
$.getJSON('/Appt/Location/' + $('#Service').val(), function (data) {
var items = '<option> Any Location </option>';
$.each(data, function (i, location) {
items += "<option value='" + location.Value + "'>" + location.Text +
"</option>";
});
$("#Location").html(items);
});
});
$('#Location').change(function () {
$.getJSON('/Appt/Employee/' + $('#Location').val(), function (data) {
var items = '<option> Any Employee </option>';
$.each(data, function (i, employee) {
items += "<option value='" + employee.Value + "'>" + employee.Text +
"</option>";
});
$("#Employee").html(items);
$("Service").html(items);
});
});
});
</script>
My Controller code is
public ActionResult WaitingList()
{
SYTEntities ca = new SYTEntities();
ViewBag.CategoryId = new SelectList(ca.BusinessCategories.ToList(), "CategoryId", "CategoryName");
ViewBag.Service = new SelectList(ca.tblBusinessCategories.ToList(), "BusinessID", "BusinessName");
return View();
}
public JsonResult Categories(int id)
{
SYTEntities db = new SYTEntities();
var business = from s in db.tblBusinessCategories
where s.CategoryId == id
select s;
return Json(new SelectList(business.ToArray(),"BusinessID", "BusinessName"), JsonRequestBehavior.AllowGet);
}
public JsonResult Location(int id)
{
SYTEntities db = new SYTEntities();
var location = from s in db.tblBusinessLocations
where s.BusinessID == id
join loc in db.tblLocations
on s.LocID equals loc.LocationId
select loc;
return Json(new SelectList(location.ToArray(), "LocationId", "LocationName"), JsonRequestBehavior.AllowGet);
}
public JsonResult Employee(int id)
{
SYTEntities db = new SYTEntities();
var emp = from s in db.Employees
where s.LocationId == id && s.BusinessID == 91
select s;
return Json(new SelectList(emp.ToArray(), "EmpId", "EmpName"), JsonRequestBehavior.AllowGet);
}
In public JsonResult Employee(int id) i need to pass ('#Service') value.
Is it possible to do? Can anyone please help me?
You can pass as many values as you want using the data parameter of jQuery.getJSON
var url = '#Url.Action("Categories", "Appt")'; // don't hard code your urls!
$.getJSON(url, { id: $('#Business').val(), otherProperty: anotherValue }, function (data) {
Yes you just need to add one more parameter to the Controller Action as below.
public JsonResult Categories(int id, int id2)
{
SYTEntities db = new SYTEntities();
var business = from s in db.tblBusinessCategories
where s.CategoryId == id
select s;
return Json(new SelectList(business.ToArray(),"BusinessID", "BusinessName"), JsonRequestBehavior.AllowGet);
}
and the below change in you View
$.getJSON('/Appt/Categories/' + $('#Business').val(), { id2: ('#otherId2').val() }, function (data) {
var items = '<option> Any Hospital</option>'
$.each(data, function (i, Service) {
debugger;
items += "<option value='" + Service.Value + "'>" + Service.Text +
"</option>";
});
$("#Service").html(items);
});
I'm trying to upload files using dropzone.js
View:
#using (Html.BeginForm("SaveMethod", "ControllerName", FormMethod.Post, new { enctype = "multipart/form-data", #class = "dropzone", id = "js-upload-form" }))
........................
<div class="form-inline">
<div class="form-group">
<input type="file" name="MainFile" id="js-upload-files"/>
</div>
<div class="upload-drop-zone" id="drop-zone">
Just drag and drop files here
</div>
<div class="dropzone-previews"></div>
</div>
JS:
var formData = null;
formData = new FormData($form[0]);
dropZone.ondrop = function (e) {
e.preventDefault();
this.className = 'upload-drop-zone';
startUpload(e.dataTransfer.files)
}
dropZone.ondragover = function () {
this.className = 'upload-drop-zone drop';
return false;
}
dropZone.ondragleave = function () {
this.className = 'upload-drop-zone';
return false;
}
var startUpload = function (files) {
for (var i = 0; i < files.length; i++) {
formData.append(files[i].name, files[i]);
}
}
Controller:
[HttpPost]
public JsonResult SaveMethod(TaskManage objTaskManage, HttpPostedFileBase files)
{
}
Now, after submit, i want to have files that was dropped on drop area along with the files attached in upload control. Here, what happens is files giving me null and when i use Request.Files["MainFile"] i get only the files dropped on dropzone area, it doesn't show me the file i have upload to control.
I'm not able to find out the issue. Any help is really appreciated.
File upload in ASP.NET MVC using Dropzone JS and HTML5
You can download the latest version from the official site here http://www.dropzonejs.com/ and also we can install using the nuget package manage console by the following command Package Manager Console
PM> Install-Package dropzone
Now create a bundle for your script file in BundleConfig.cs
bundles.Add(new ScriptBundle("~/bundles/dropzonescripts").Include(
"~/Scripts/dropzone/dropzone.js"));
Similarly add the dropzone stylesheet in the BundleConfig.cs
bundles.Add(new StyleBundle("~/Content/dropzonescss").Include(
"~/Scripts/dropzone/css/basic.css",
"~/Scripts/dropzone/css/dropzone.css"));
Now add the bundle reference in your _Layout page
View Page:
<div class="jumbotron">
<form action="~/Home/SaveUploadedFile" method="post" enctype="multipart/form-data" class="dropzone" id="dropzoneForm" style="width: 50px; background: none; border: none;">
<div class="fallback">
<input name="file" type="file" multiple />
<input type="submit" value="Upload" />
</div>
</form>
</div>
Controller:
public ActionResult SaveUploadedFile()
{
bool isSavedSuccessfully = true;
string fName = "";
try{
foreach (string fileName in Request.Files)
{
HttpPostedFileBase file = Request.Files[fileName];
//Save file content goes here
fName = file.FileName;
if (file != null && file.ContentLength > 0)
{
var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\WallImages", Server.MapPath(#"\")));
string pathString = System.IO.Path.Combine(originalDirectory.ToString(), "imagepath");
var fileName1 = Path.GetFileName(file.FileName);
bool isExists = System.IO.Directory.Exists(pathString);
if (!isExists)
System.IO.Directory.CreateDirectory(pathString);
var path = string.Format("{0}\\{1}", pathString, file.FileName);
file.SaveAs(path);
}
}
}
catch(Exception ex)
{
isSavedSuccessfully = false;
}
if (isSavedSuccessfully)
{
return Json(new { Message = fName });
}
else
{
return Json(new { Message = "Error in saving file" });
}
}
Now add the following script to your view page at the and in script tag.
//File Upload response from the server
Dropzone.options.dropzoneForm = {
init: function () {
this.on("complete", function (data) {
//var res = eval('(' + data.xhr.responseText + ')');
var res = JSON.parse(data.xhr.responseText);
});
}
};
Here you can see the response from server.
I am finalising a college project and I am stuck.
I have created an API in netbeans and it is working fine.
Returing e.g.
<?xml version="1.0" encoding="UTF-8"?>
<accountholder>
<accountnumber>45672</accountnumber>
<address>234 THE BANK, DUBLIN 1</address>
<balance>763.32</balance>
<email>JOHANN#SMITH.COM</email>
<firstname>JOHANN</firstname>
<id>1</id>
<lastname>SMITH</lastname>
<pinnumber>1234</pinnumber>
</accountholder>
Now I am trying to create a javascript to return data when searching by Id.
<script language="javascript" type="text/javascript">
var request = null;
function createRequest() {
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("MsXML2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = null;
}
}
}
if (request == null)
alert("Error creating request object!");
}
function getMessage()
{
createRequest();
var accountholderid = document.getElementById("Id").value;
id=eval(accountholderid);
var url = "http://localhost:8080/BankProjectApi/webresources/bankprojectapi.accountholder/"+id;
request.onreadystatechange = handleResponse;
request.open("GET", url, true);
request.send(null);
}
function handleResponse() {
if (request.readyState==4 && request.status==200)
{
var xmlDocument=request.responseXML;
var firstname = xmlDocument.getElementsByTagName("firstname");
var lastname = xmlDocument.getElementsByTagName("lastname");
var accountnumber = xmlDocument.getElementsByTagName("accountnumber");
for(var i=0; i<firstname.length; i++) {
var firstname = firstname[i].childNodes[0].nodeValue;
var lastname = lastname[i].childNodes[0].nodeValue;
var accountnumber= accountnumber[i].childNodes[0].nodeValue;
document.getElementById('lastname').value=firstname;
document.getElementById('firstname').value=lastname;
document.getElementById('accountnumber').value=accountnumber;
}
}
}
</script>
In the body I have an input textfield with a button with an on click:
<td>Enter Account holder ID : </td>
<td><input type="text" id="playerid" size="10"/>
<input type="button" value="Get Details" onclick="getMessage()"/>
</tr>
<tr>
<td>Account holder Last Name : </td>
<td> <input type="text" id="lastname" size="10"/> </td>
</tr>
<tr>
<td>Account holder First Name : </td>
<td> <input type="text" id="firstname" size="10"/> </td>
</tr>
<tr>
<td>Account number : </td>
<td> <input type="text" id="accountnumber" size="10"/> </td>
</tr>
What am I missing as it is not returning anything :(
I believe your id value for the 'accountholderid' was looking for 'Id' instead of 'playerid'.
May I ask why you are calling 'eval' on the value? Do you need parseInt?
(function () {
var request = null;
function createRequest() {
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject('MsXML2.XMLHTTP');
} catch (othermicrosoft) {
try {
request = new ActiveXObject('Microsoft.XMLHTTP');
} catch (failed) {
request = null;
}
}
}
if (request === null) {
alert('Error creating request object!');
}
}
function getMessage() {
createRequest();
var accountholderid = document.getElementById('playerid').value,
id = eval(accountholderid),
url = 'http://localhost:8080/BankProjectApi/webresources/bankprojectapi.accountholder/' + id;
request.onreadystatechange = handleResponse;
request.open("GET", url, true);
request.send(null);
}
function handleResponse() {
if (request.readyState === 4 && request.status === 200) {
var xmlDocument = request.responseXML,
firstname = xmlDocument.getElementsByTagName('firstname'),
lastname = xmlDocument.getElementsByTagName('lastname'),
accountnumber = xmlDocument.getElementsByTagName('accountnumber');
for(var i = 0, max = firstname.length; i < max; i += 1) {
var firstname = firstname[i].childNodes[0].nodeValue,
lastname = lastname[i].childNodes[0].nodeValue,
accountnumber = accountnumber[i].childNodes[0].nodeValue;
document.getElementById('lastname').value = firstname;
document.getElementById('firstname').value = lastname;
document.getElementById('accountnumber').value = accountnumber;
}
}
}
}());
Also, I did a quick refactoring of your code to aid in my assessing the issue, adhere to more community conventions as well as avoid common JS pitfalls. (ex. closure, missing var declarations, ===, curlys everywhere, single variable pattern, and some others).
i want to upload a file by node.js so i try by this article.
http://debuggable.com/posts/parsing-file-uploads-at-500-mb-s-with-node-js:4c03862e-351c-4faa-bb67-4365cbdd56cb
I run this code
var formidable = require('formidable')
, http = require('http')
, sys = require('sys');
var server=http.createServer(function(req, res) {
console.log('out if condition'+sys.inspect(req));
if (req.url == '/upload' && req.method.toLowerCase() == 'post') {
// parse a file upload
console.log('in if condition');
var form = new formidable.IncomingForm();
form.parse(req, function(fields, files) {
res.writeHead(200, {'content-type': 'text/plain'});
res.write('received upload:\n\n');
res.end(sys.inspect({fields: fields, files: files}));
});
return;
}
// show a file upload form
res.writeHead(200, {'content-type': 'text/html'});
res.end
( '<form action="/upload" enctype="multipart/form-data" method="post">'
+ '<input type="text" name="title"><br>'
+ '<input type="file" name="upload" multiple="multiple"><br>'
+ '<input type="submit" value="Upload">'
+ '</form>'
);
});
server.listen(8000);
when i upload the file it doesn't proceed further easily and doesn't go in if condition of upload why ?
fs.writeFile(files.upload.name, files.upload,'utf8', function (err) {
if (err) throw err;
console.log('It\'s saved!');
});
Please check.
http://rahulmehta1.wordpress.com/2011/04/26/uploading-a-file-in-node-js-by-formidable/
I used the jQuery autocompletion for my Struts2 application.
Pratically, my action made a list of strings that jQuery use. This is the script:
$().ready(function() {
$("#tag").autocomplete("/myAction/Action", {
multiple : true,
autoFill : true,
minChars:1
});
});
During typing appear the box with the suggestions. The problem is that the box render another value,
exactly render the code of my JSP ( links to CSS for the autocomplete plug-in).
How can I solve this?
This is my JSP:
<html>
<head>
<script src="<%=request.getContextPath()%>/scripts/jquery-latest.js"></script>
<link rel="stylesheet" href="<%=request.getContextPath()%>/scripts/main.css" type="text/css" />
<link rel="stylesheet" href="<%=request.getContextPath()%>/scripts/jquery.autocomplete.css" type="text/css" />
<script type="text/javascript" src="<%=request.getContextPath()%>scripts/jquery.bgiframe.min.js"></script>
<script type="text/javascript" src="/<%=request.getContextPath()%>/query.dimensions.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/scripts/jquery.autocomplete.js"></script>
<script type="text/javascript">
$().ready(function() {
$("#tag").autocomplete("/myAction/Action", {
multiple : true,
autoFill : true,
minChars:1
});
});
</script>
</head>
<body>
<s:form action="Action" theme="simple">
<s:iterator value="elencoMateriali" var="asd">
<s:property value="#asd" escape="false"/>
</s:iterator>
<s:textfield id="tag" name="tagField" label="tag" />
</s:form>
</body>
I think it's too late for an answer, but the probles is still remaining in Struts2. I have made some modifications to solve such problem:
Copy the jquery.struts2.js file into you js path.
Edit the jquery.struts2.js fil and look for 'success: function(data)' in the handle of the Autocompleter Widget, and replace the function for the next one:
success: function(data) {
var x = 0;
if (data[o.list] !== null) {
var isMap = false;
if (!$.isArray(data[o.list])) {
isMap = true;
}
var result = [];
$.each(data[o.list], function(j, val) {
if (isMap) {
result.push({
label: val.replace(
new RegExp(
"(?![^&;]+;)(?!<[^<>]*)(" +
$.ui.autocomplete.escapeRegex(request.term) +
")(?![^<>]*>)(?![^&;]+;)", "gi"
), "<strong>$1</strong>" ),
value: val,
id: j
});
}
else {
if (o.listkey !== undefined && o.listvalue !== undefined) {
result.push({
label: val[o.listvalue].replace(
new RegExp(
"(?![^&;]+;)(?!<[^<>]*)(" +
$.ui.autocomplete.escapeRegex(request.term) +
")(?![^<>]*>)(?![^&;]+;)", "gi"
), "<strong>$1</strong>" ),
value: val[o.listvalue],
id: val[o.listkey]
});
}
else {
result.push({
label: data[o.list][x].replace(
new RegExp(
"(?![^&;]+;)(?!<[^<>]*)(" +
$.ui.autocomplete.escapeRegex(request.term) +
")(?![^<>]*>)(?![^&;]+;)", "gi"
), "<strong>$1</strong>" ),
value: data[o.list][x],
id: data[o.list][x]
});
}
}
x++;
});
response(result);
}
}
Now, if you subscribe a onSelectTopics method on your jsp code, you will have a new item.id element available, so you can set the id value into a hidden o whatever you want.
Now, your autocompleter show a list with the strong word, fills the input with the selection, and mantains the id in a variable you can catch.
Remember to add the modified js in the include header section.
<%# taglib prefix="s" uri="/struts-tags" %>
<%# taglib prefix="sx" uri="/struts-dojo-tags" %>
<s:form action="ActionJson" theme="simple">
<s:url id="elencoFuffa" action="ActionJSON"/>
<sx:autocompleter id="autocompleter" name="materiale" loadOnTextChange="true" preload="false" href="%{elencoFuffa}" size="24" loadMinimumCount="1" showDownArrow="false" cssClass="dropDown" onchange="submit();"/>
<s:submit value="Prosegui"/>
<s:property value="luoghiSmaltimento"/>
</s:form>
Now, the Action:
public class Action extends ActionSupport {
private String materiale;
private String luoghi;
private List<String> elencoMateriali;
private Map<String, String> json;
public String execute() throws Exception {
System.out.println("------------------" + materiale);
return SUCCESS;
}
public String getMateriali() throws Exception {
MaterialiDAO dao = new MaterialiDAO();
List<Materiali> toResult = new ArrayList<Materiali>();
toResult = dao.findAll();
elencoMateriali = new ArrayList<String>();
Iterator i = toResult.iterator();
while (i.hasNext()) {
Materiali m = (Materiali) i.next();
elencoMateriali.add(m.getValueNomemateriale());
}
return SUCCESS;
}
public String getJson() throws Exception {
json = new HashMap<String, String>();
if (materiale != null && materiale.length() > 0) {
MaterialiDAO dao = new MaterialiDAO();
List<Materiali> materiali = dao.findByLikeValue(materiale);
for (Materiali m : materiali) {
json.put(m.getValueNomemateriale(), "" + m.getIdMateriali());
}
}
return SUCCESS;
}
public String trovaLuogo() throws Exception {
LuoghismalDAO daoL = new LuoghismalDAO();
MaterialiDAO daoM = new MaterialiDAO();
Materiali m = daoM.findByMaterialiName(materiale);
if (m != null) {
luoghi = m.getLuoghismal().getValueDescrluogo();
return SUCCESS;
} else {
luoghi = "-- Scegliere un materiale --";
return SUCCESS;
}
}
/* Getters and setters */
At the end the struts.xml
<action name="ActionJSON" class="it.action.Action"
method="getJson">
<result type="json">
<param name="root">json</param>
</result>
</action>