XMLHttpRequest request / Servlet response is null - ajax

There is a problem with servlet. I send form data by XMLHttpRequest to a server, but servlet handles request object incorrectly and send in response object "null.null". I tried following things but nothing helps:
encode "document.getElementsByName('contractor').value" by encodeURIComponent;
pass the object of FormData as argument to .send();
changing enctype attribute in form to "multipart/formdata";
using get method.
Please take a look. If there are any suggestions how to make it works without using jQuery I would appreciate a lot.
HTML:
<div id="request-form">
<form enctype="application/x-www-form-urlencoded" method="post">
Contractor<input type="text" name="contractor"><br>
Contract No<input type="text" name="contract-no">
<input type="button" onclick=clickOnButton() value="Submit"><br>
</form>
</div>
JS:
var httpRequest;
function clickOnButton() {
if (window.XMLHttpRequest) {
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
var dataForRequest = 'contract=' + document.getElementsByName('contractor').value + '&contract-no=' + document.getElementsByName('contract-no').value;
httpRequest.onreadystatechange = responseHandler;
httpRequest.open('POST', "/AjaxServ", true);
httpRequest.send(dataForRequest);
}
function responseHandler() {
if (httpRequest.readyState == 4) {
if (httpRequest.status == 200) {
var line = httpRequest.responseText;
alert(line);
}
}
}
Java:
public class ServletClass extends HttpServlet {
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String contractor = req.getParameter("contractor");
String contractNo = req.getParameter("contract-no");
resp.setContentType("text/plain");
PrintWriter out = resp.getWriter();
out.write(contractor + "." + contractNo);
}
}

Shouldn't it be 'contractor=' + document.getElementsByName('contractor').value instead of
'contract=' + document.getElementsByName('contractor').value ?

Related

Fine Uploader- Server side code saves uploaded file but client displays 'Upload failed' message

I have an MVC2 application where I am trying to use the Fine-Uploader plugin. When I run through my code behind, it saves the file that I uploaded. However, what get's displayed back in the browser is Upload Failed. I'm not sure what I'm missing here. My code is below:
Code behind:
public void UploadFiles()
{
try
{
if (Request.Files.Count > 0)
{
foreach (string file in Request.Files)
{
HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
if (hpf.ContentLength == 0)
{
continue;
}
string filename = Path.GetFileName(hpf.FileName);
string path = Path.Combine(Server.MapPath(ConfigurationManager.AppSettings["AttachmentPath"]), filename);
hpf.SaveAs(path);
}
}
}
catch (Exception e)
{
//Do something
}
}
Master page:
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
<script src="<%=Url.Content("~/Scripts/jquery.fineuploader-3.5.0.js") %>" type="text/javascript"></script>
<script src="<%=Url.Content("~/Scripts/jquery.fineuploader-3.5.0.min.js") %>" type="text/javascript"></script>
Markup page:
<div id="manual-fine-uploader"></div>
<div id="triggerUpload" class="btn btn-primary" style="margin-top: 10px;">
<i class="icon-upload icon-white"></i> Upload now
</div>
<script type="text/javascript">
$(document).ready(function () {
var manualuploader = new qq.FineUploader({
element: $('#manual-fine-uploader')[0],
request: {
endpoint: 'Home/UploadFiles'
},
autoUpload: false,
text: {
uploadButton: '<i class="icon-plus icon-white"></i> Select Files'
}
});
$('#triggerUpload').click(function () {
manualuploader.uploadStoredFiles();
});enter code here
});
</script>
Fine Uploader expects a valid JSON response indicating whether the upload succeeded or not.
A successful upload response must have:
{ "success": true }
for Fine Uploader to know that it worked. You can add whatever else you want to your response, but without indicating 'success' Fine Uploader will think that the upload failed.
What I would do is add a return to your UploadFiles function. Somewhat like:
public UploadResult UploadFiles()
{
try
{
// ... save file and other things
}
catch (Exception ex)
{
// failsauce :(
return new UploadResult(false);
}
// success :)
return new UploadResult(true);
}
Where UploadResult is much like:
public class UploadResult
{
// This is important!
public const string ResponseContentType = "text/plain";
public FineUploaderResult(bool success)
{
_success = success;
}
public override void ExecuteResult(ControllerContext context)
{
// Here we create the JSON Response object,
// set the correct content-type, and finally
// it gets built with the correct success flag.
var response = context.HttpContext.Response;
response.ContentType = ResponseContentType;
response.Write(BuildResponse());
}
public string BuildResponse()
{
var response = new JObject();
response["success"] = _success;
// ... maybe set some other data in the response JSON
return response.ToString();
}
}
There is an example using ASP.NET MVC C# up on the server examples repository that may provide some assistance.
Also, on the development branch there is a server-side README which indicates exactly what constitutes a valid JSON response for Fine Uploader.

Upload files with Jquery File Upload in ASP.NET MVC 3

Does anyone has a clean suggestion of instantiate this jquery's useful library.
I need to submit files and manage the Json response from the server.
I always get none json response within the Js code. I have reviewed some articles mentioning it but the code doesn't fit to the purpose.
The situation is: I achieve the submition and saving in the database but the Json response never arrives.
Thanks in advance.
This is my view code:
<script type="text/javascript">
$("#formUplImg").fileupload({
dataType: "json",
url:'#Url.Action("CreateJson","ProductImage")',
done: function (e, data) {
alert(data.StatusMessage);
}
});
</script>
#using (Html.BeginForm("CreateJson", "ProductImage", FormMethod.Post, new { id = "formUplImg", enctype = "multipart/form-data", #class = "jqtransform" }))
{
#Html.ValidationSummary(true)
<div class="rowElem">
<input type="file" id="Content" name="Content" />
</div>
<div class="rowElem">
#Html.ValidationMessageFor(item => item.Content)
</div>
<div class="rowElem">#Html.JQueryUI().Button("Guardar imagen", ButtonElement.Button, ButtonType.Submit, new { id = "guardar_imagen" })</div>
}
This is my controller action code:
[HttpPost]
public ContentResult CreateJson(UploadedFileInfo fileInfo)
{
try
{
if (fileInfo.Content == null)
throw new Exception("Hubo problemas con el envĂ­o. Seleccione un archivo a subir");
var file = new TempDocument
{
CreatedBy = User.Identity.Name,
CreationTime = DateTime.Now,
FileName = fileInfo.Content.FileName,
MimeType = fileInfo.Content.ContentType,
Size = fileInfo.Content.ContentLength,
Content = new byte[fileInfo.Content.ContentLength]//Image content to save
};
fileInfo.Content.InputStream.Read(file.Content, 0, fileInfo.Content.ContentLength);//Reading image content into ProductImage object
DocumentsManager.StorePendingDocuments.Add(file);
DocumentsManager.SaveTempDocuments();//Store each document uploaded to: TempDocument Table
TempData["SuccessMsg"] = "The image was saved successfully";
var json = new JavaScriptSerializer().Serialize(new { Success = true, StatusMessage = "El objeto fue insertado correctamente" });
return Content(json, "application/json");
}
catch (Exception exception)
{
TempData["ErrorMsg"] = exception.Message;
var json = new JavaScriptSerializer().Serialize(new { Success = false, StatusMessage = exception.Message });
return Content(json, "application/json");
}
}
Use return type of Action as ActionResult and use:
`return Json(new { Result = "Success" });`
So that on success you will get Json object containing result value.

File upload is not working in spring using jquery-ajax

This is my form :
<form name="CIMtrek_Compliance_Daily_Shipments" enctype="multipart/form-data">
<input type="file" id="CIMtrek_comments" name="CIMtrek_comments" value="" />
<button id="upload" onclick="uploadCommentFile()">Upload</button>
</form>
and this is my ajax call using jquery :
function uploadCommentFile(){
$("#upload").live("click", function() {
var file_data = $("#CIMtrek_comments").prop("files")[0]; // Getting the properties of file from file field
var form_data = new FormData(); // Creating object of FormData class
form_data.append("file", file_data) // Appending parameter named file with properties of file_field to form_data
//form_data.append("user_id", 123) // Adding extra parameters to form_data
$.ajax({
type: 'POST',
url: "/CIMtrek_Compliance_Daily_Shipments_FileUpload",
dataType: 'script',
cache: false,
contentType: false,
processData: false,
data: {
uploadFile: file_data
},
success: function (msg) {
global.getElementById("CIMtrek_uploadedFileName").innerHTML=msg;
}
})
})
}
and this is my spring controller :
#RequestMapping(value = "/CIMtrek_Compliance_Daily_Shipments_FileUpload", method = RequestMethod.POST)
public String createComments(#RequestParam("uploadFile") CommonsMultipartFile uploadItem,
HttpServletRequest request) {
String uploadedFileName="";
try {
MultipartFile file = uploadItem;
String fileName = null;
InputStream inputStream = null;
OutputStream outputStream = null;
if (file.getSize() > 0) {
inputStream = file.getInputStream();
System.out.println("size::" + file.getSize());
fileName = request.getRealPath("") + "/WEB-INF/resources/Attachment"+ file.getOriginalFilename();
System.out.println("path : "+request.getRealPath("") + "/WEB-INF/resources/Attachment");
outputStream = new FileOutputStream(fileName);
System.out.println("fileName:" + file.getOriginalFilename());
int readBytes = 0;
byte[] buffer = new byte[10000];
while ((readBytes = inputStream.read(buffer, 0, 10000)) != -1) {
outputStream.write(buffer, 0, readBytes);
}
outputStream.close();
inputStream.close();
}
uploadedFileName =file.getOriginalFilename();
} catch (Exception e) {
e.printStackTrace();
}
return uploadedFileName;
}
but i get the following exception when i click on upload button :
HTTP Status 400 -
The request sent by the client was syntactically incorrect.
what could be the problem, Please help me to identify.
Best Regards.
Follow this one it helped and solved my problem :

JSP Session Not Recognised In Ajax

I've tried to put an object in a session inside a servlet and read it inside a javascript code. Actually that works, but after converting the normal javascript code to AJAX, it couldn't recognize it any more.
This is the servlet's code
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
JSONObject object = new JSONObject();
object.put("A","A");
request.getSession().setAttribute("json", object.toJSONString());
}
And I want to recieve it in the following AJAX code.
<script type="text/javascript">
function runAjax(){
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function(){
if(ajax.readyState == 4 && ajax.status == 200){
var json = <%=session.getAttribute("json")%>
alert(json);
}
}
ajax.open("GET", "servlet", true);
ajax.send();
}
</script>
json content is null.
Any help please?
Thanks very much.
JavaScript executes in the browser. JSP scriptlet executes on the server.
So when you make a request to the page containing the above JavaScript code, the HTML is generated by the server. The server executes the following scriptlet code: <%=session.getAttribute("json")%>. Since, at this moment, the session attribute doesn't exist, the generated HTML is:
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
var json = null
alert(json);
}
}
Then this HTML/JS code is downloaded by the browser, and the JS code is executed in the browser. The browser sends an AJAX request to the server, and when the response comes back, the browser executes the following function:
function() {
if (ajax.readyState == 4 && ajax.status == 200) {
var json = null
alert(json);
}
}
So obviously, what is displayed in the allert box is null.
You can try like this to have the session object value in javascript.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
JSONObject object = new JSONObject();
object.put("A","A");
request.getSession().setAttribute("json", object.toJSONString());
PrintWriter out=response.getWriter();
out.write(object.toJSONString());
}
<script type="text/javascript">
function runAjax(){
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function(){
if(ajax.readyState == 4 && ajax.status == 200){
var json = ajax.responseText;
alert(json);
}
}
ajax.open("GET", "servlet", true);
ajax.send();
}
</script>

populate dropdown on change of another using servlet

i am new in java struts i am developing web application in struts 1.3 i have two dropdowns one is for location and another is for Floor,i have a requirement that on change on one dropdown values of other dropdown fills from database for i googled a lot and i got code but when i change on my first dropdown second dropdown does not populate though i saw in debugging mode in Netbeans that that values return from database .i do my database activity in servlet doGet method
<script>
function createRequestObject()
{
var req;
if(window.XMLHttpRequest)
{
//For Firefox, Safari, Opera
req = new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
//For IE 5+
req = new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
//Error for an old browser
alert('Your browser is not IE 5 or higher, or Firefox or Safari or Opera');
}
return req;
}
//Make the XMLHttpRequest Object
var http = createRequestObject();
function sendRequest(method, url)
{
if(method == 'get' || method == 'GET')
{
http.open(method,url);
http.onreadystatechange = handleResponse;
http.send(null);
}
}
function handleResponse()
{
if(http.readyState == 4 && http.status == 200)
{
var response = http.responseText;
if(response)
{
document.getElementById("dwnfloor").innerHTML = response;
}
}
}
function getFloorDropdown(SelectedValue)
{
alert(SelectedValue);
sendRequest('GET','http://localhost:8084/AssetManagement/DropDown?locid=' +SelectedValue );
}
</script>
<tr>
<td >
<span style="color:#FF0000">*</span>Location</td>
<td> <html:select name="RoomForm" property="name"
onchange="getFloorDropdown(this.value)">
<htmlption value="0">Select Location</htmlption>
<htmlptionsCollection name="RoomForm"
property="list" value="id" label="name" />
</html:select>
<td>
</tr>
<tr>
<td >
<span style="color:#FF0000">*</span>Floor
</td>
<td id="dwnfloor">
<select name="dwnfloor">
<option value="0">Select Floor</option>
</select>
</td>
</tr>
Servlet Code
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
String country=request.getParameter("locid");
String buffer="<select name=\"dwnfloor\"><option value=\"0\">Select</option>";
Connection connection = null;
PreparedStatement p_statement = null;
Statement statement = null;
ResultSet result = null;
try {
DAOOperation dao= new DAOOperation();
String sqlst = "select id,name from floor_mst where id=?";
try {
connection = DBConnection.getConnection();
p_statement = connection.prepareStatement(sqlst);
p_statement.setString(1, country);
result = p_statement.executeQuery();
while(result.next()) {
buffer=buffer+"<option value=\""+result.getString("ID")+" \">"+result.getString("name")+"</option>";
}
buffer=buffer+"</select>";
response.getWriter().println(buffer);
System.out.println(buffer);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
connection.close();
} catch (Exception e) {
}
}// end finally
} catch(Exception e) {
System.out.println(e);
}
}
and servlet mapping in web.xml
web.xml
<servlet-mapping>
<servlet-name>DropDown</servlet-name>
<url-pattern>/DropDown</url-pattern>
</servlet-mapping>
In the servlet, write response.getWriter().write(buffer) instead of response.getWriter().println() and also, try to alert the response you got from the servlet
in the ajax code you have written. It seems like your javascript has not recieved the response.
If the problem is not solved then Im online.

Resources