Upload files Using Ajax, Jquery and Struts2 - javascript

Hi can any one please tell me how to upload files using ajax, jquery and Struts2. I have gone through the lot of tutorials in the net but i didn't get any possible solution. The requirement is when ever we click on the button the javascript function need to be called.The javascript(jquery) initiate the Ajax engine and ajax need to call the struts action to get the response. Here the request and response is without refresh the page and without using the IFrames.

I use iframe to submit my data without refresh.
i) My html is as follows :
1) Add form tag. // You can just copy paste my form tag just change the action
2) Add target="my_iframe" // The iframe name.. it can be anything
<div class="bp_up_input">
<form name="banner_image_uploads" id="banner_image_uploads" method="post" action="" target="my_iframe" enctype="multipart/form-data">
<span>
<input type="file" name="banner_image" class="my_vld" lang="Image_path" />
<input type="button" id="banner_image_upload" value="Upload" class="bp_button_style" />
</span>
<input type="hidden" name="slt_store_id" value="" />
<input type="hidden" name="sld_location" value="" />
</form>
</div>
ii) My javascript code is a follows :
$('#banner_image_upload').live('click',function(){
if($.trim($('input[name="banner_image"]').val()) != '' && $.trim($('select[name="bp_location"]').val()) != '' && $.trim($('#store_names').val()) != ''){
$("iframe").remove(); //Remove previous iframe if present
$("body").append('<iframe id="my_iframe" name="my_iframe" src="" style="display:none;"></iframe>'); //Append iframe to body with id my_iframe
$('#banner_image_uploads').submit();//submit the form with id banner_image_uploads
$("#my_iframe").load(function(){
var val = $("iframe")[0].contentDocument.body.innerHTML; // I use php so I just echo the response which I want to send e.g 250:new and save it in var val.
var data = val.split(':'); // I split the variable by :
var html = '<tr><td><img width="800" height="60" border="0" src="/assets/store_banners/live/'+$.trim($('input[name="sld_location"]').val())+'/'+data[1]+'" id="'+data[0]+'"><img src="/images/delete_trash.png" width="9" height="12" class="image_delete" style="padding-left:37%;"/></td></tr>'; // In my case I wanted to upload an image so on success I had to show the image which was uploaded. You can skip this and the below code if you want.
$('.bp_table tbody').append(html); //Append the uploaded image to the container I wanted.
$('input[name="banner_image"]').val(''); //On success I clear the file name
});
}else{
alert('Please Select filters');
}

Hi the below code is working for me. I hope it will help you.
JSP Code:
<div id="uploadImg">
<s:form id="uploadImgForm" action="strutsaction" method="post" enctype="multipart/form-data">
<s:file name="imgFileUpload" label="Choose file to upload" accept="image/*"></s:file>
<s:submit value="Upload" align="center" id="uploadImgSubmitBtn"></s:submit>
</s:form>
<div>
JQuery:
$("#uploadImgSubmitBtn").click(function(e){
// Get form
var form = $('#uploadImgForm')[0];
// Create an FormData object
var data = new FormData(form);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "strutsaction.action",
data : data,
cache: false,
processData: false,
contentType: false,
success: function(data){
$('#uploadImg').html(data);
}
});
});

Related

Refresh a specific class after post ajax Javascript

So after lot of researchs, I come here to request your help, there is my problem :
I have a comment system with multiple forms on a same page (I use FOSCommentBundle on Symfony). And I want to be able to post comments with Ajax (this part work, no problems) and refresh the comment section after the post is submitted (And i'm stuck on this part).
There is an example of code :
$(document).on("submit", ".postAjax", function(e){
e.preventDefault();
$(this).LoadingOverlay("show");
data = $(this).serializeObject();
$.ajax({
url: $(this).attr('action'),
type: 'POST',
success:function(){
$(".comments").load(window.location.href + " .comments");
}
});
});
<form method="POST" class="postAjax" action="./comment/post/1">
<input type="textarea" name="comment">
<input type="hidden" name="identifier" value="1">
<input type="submit">
</form>
<div class="comments">
<!-- Comments refreshed after post here -->
</div>
<form method="POST" class="postAjax" action="./comment/post/2">
<input type="textarea" name="comment">
<input type="hidden" name="identifier" value="2">
<input type="submit">
</form>
<div class="comments">
<!-- Comments refreshed after post here -->
</div>
<!-- ... -->
I have tried lot of things, the function ".load" of JQuery but it load all the "comments" class and duplicate the comments in each class.
If someone have a solution... Thank you
First of all, in the provided code, your <form> tag lack an action attribute for your code to work properly.
Then, to answer your question, modify your controller action (the one saving your new comment) so that it return the informations of the submitted comment (json format is better). Then, transform the returned json into html code, and append the result to your comments <div>, for example :
$(document).on("submit", ".postAjax", function(e){
e.preventDefault();
$(this).LoadingOverlay("show");
data = $(this).serializeObject();
var element = $(this);
$.ajax({
url: $(this).attr('action'),
type: 'POST',
success:function(newCommentData){
/* do some process here to transform your newCommentData array into html code */
$(element).next(".comments").append(newCommentData);
}
});
});
Also, if you want it to be cleaner, you could have an hidden 'div', with the same model as a comment div, but with each content replaced by patterns ( ex : %commentTitle%, %commentBody% ). Then each time you post a new comment, you could get that hidden div, and replace patterns with your comment data. That way, if you change comment section structure later, the JS script will still work the same way, without adjustments needed.
Try this
$(document).on("submit", ".postAjax", function(e){
e.preventDefault();
$(this).LoadingOverlay("show");
data = $(this).serializeObject();
var $comment = $(this).next(".comments");
$.ajax({
url: $(this).attr('action'),
type: 'POST',
success:function(){
$comment.append("<div />");
$comment.last("div").load(window.location.href + " .comments");
}
});
});

Prevent redirecting after post

It's probably a bad idea to ask a question, which already have multiple answers and multiple times, but I should ask it anyway. I tried pretty much everything I find there Prevent redirect after form is submitted but nothing helps me.
There is a some minor detail, which I don't see. I'm not very familiar with jQuery and AJAX. Especially with the former.
So, the code:
<form id="form" action="uploadfile.php" method="post" enctype="multipart/form-data" ><!--action="uploadfile.php" onsubmit="return false;" -->
<label>Name</label>
<input id="username" name="username" type="text" onblur="checkUsername(this.value)" onkeypress="clearError('nameerror')" oninput="clearError('nameerror')" /><br>
<label id="nameerror"></label><br>
<label>Email</label>
<input id="email" name="email" type="text" onblur="validateEmail(this.value)" onkeypress="clearError('emailerror')"/><br>
<label id="emailerror"></label><br>
Select a file<br />
<label id="draganddroperror"></label><br>
<input name="fileToUpload[]" id="fileToUpload" type="file" onchange="onChange(event)" multiple /><br />
<button id="btnSubmit" onclick="sendData()" style="background-color: gray; color: #ffffff;" />Отправить</button>
</form>
There is my JS
function sendData() {
var file_data = $("#fileToUpload").prop("files");
console.log(file_data);
if ($("#file_data").val() != "") {
var form_data = new FormData();
//form_data.append('file', file_data);
//console.log(file);
form_data.append('file', file_data);
console.log(form_data);
$.ajax({
url: 'uploadfile.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(data) {
// get server responce here
//alert(data);
// clear file field
//$("#your-files").val("");
return false;
}
});
return false; //event.preventDefault();
} else {
alert("Please select file!");
}
}
So, this is the code in question. All works flawlessly, except redirect. Another questions contains submit, but I didn't have submit input. I tried to delink form from post method (1st line), but I got server error. Return false everywhere.
I spent countless hours on this question, it consumed almost all my night hours for a few days. I would appreciate any help, thanks.
The trick to prevent form submission is return false onsubmit as below:
<form id="form" onsubmit="return sendData()" method="post" enctype="multipart/form-data">
<!--action="uploadfile.php" onsubmit="return false;" -->
<label>Name</label>
<input id="username" name="username" type="text" onblur="checkUsername(this.value)" onkeypress="clearError('nameerror')" oninput="clearError('nameerror')" />
<br>
<label id="nameerror"></label>
<br>
<label>Email</label>
<input id="email" name="email" type="text" onblur="validateEmail(this.value)" onkeypress="clearError('emailerror')" />
<br>
<label id="emailerror"></label>
<br> Select a file
<br />
<label id="draganddroperror"></label>
<br>
<input name="fileToUpload[]" id="fileToUpload" type="file" onchange="onChange(event)" multiple />
<br />
<button type="submit" id="btnSubmit" style="background-color: gray; color: #ffffff;">Upload</button>
</form>
Note that I have written onsubmit=return sendData(). When the sendData() will return true the form will get submitted, otherwise it will never get submitted. For that the last statement in sendData() is return false;. In this way the form never gets submitted in current window, instead only Ajax submit works.
function sendData() {
var file_data = $("#fileToUpload").prop("files");
console.log(file_data);
if ($("#file_data").val()) {
var form_data = new FormData();
//form_data.append('file', file_data);
//console.log(file);
form_data.append('file', file_data);
console.log(form_data);
$.ajax({
url: 'uploadfile.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(data) {
// get server responce here
//alert(data);
// clear file field
//$("#your-files").val("");
}
});
} else {
alert("Please select file!");
}
return false;
}
I hope this gives you the clear understanding.
You want to cancel the default event handler for the submit event that the button triggers. To do this you need access to the event itself. It's best practice to handle the button click from JavaScript entirely instead of calling functions from HTML.
var submitButton = document.getElementById('btnSubmit');
submitButton.addEventListener('click', sendData);
// Then you will have access to the event in the sendData function
function sendData(ev) {
ev.preventDefault();
...
}
Live example
A slightly cleaner approach is to handle the form submitting, however this is done. This would also catch a form submit by hitting the enter key for example.
var form = document.getElementById('form');
form.addEventListener('submit', sendData);
Live example
In function sendData() you should pass event param like this
function sendData(evt) {
}
and then in this function we should add evt.preventDefault(); to stop submit action. Hope this help.
Add type attribute with the value of button and you are done:
<button id="btnSubmit" type="button" ...
By default The value for the type attribute is submit, which tells the browser to submit the from to the server, If you change it to button the browser will do nothing, you can only bind events when the button is clicked

Ajax, just sending value not showing page

I have two files with php and html. This is the basic info inside my A.php file
<div class="col-md-8">
<input type="email" class="form-control" placeholder="Ingresar Número de Nota" id="idnote" name="idnote">
</div>
<button type="button" class="btn btn-primary" id="notes">Enviar</button>
When the user click in the button, it calls a function inside a js.
$(document).ready(function() {
var formData = {
'id' : $('input[name=idnote]').val()
};
$.ajax({
type : 'POST',
url : '../consults/findnote.php',
data : formData,
dataType : 'json',
encode : true
})
.done(function(data) {
//Going to findnote.php and keeping formData
//This findnote.php contains a completely different design but I need the first value to make some changes for the user.
})
});
});
The problem is that after the ajax, my webpage is not going to findnote.php is just sending the value, And I need to show findnote.php
I know if i use
event.preventDefault();
Ajax will prevent the reload, but I'm not using it.
There is a way to do it?
How Do I keep values after making a window.location? (Because if I call the file after the successful call I lose the value)
Should I try with only php? (Its an option)
Why don't do pure HTML ?
<form action="../consults/findnote.php" method="POST">
<div class="col-md-8">
<input type="email" class="form-control" placeholder="Ingresar Número de Nota" id="idnote" name="id">
</div>
<button type="submit" class="btn btn-primary" id="notes">Enviar</button>
</form>
Just added the form tag and edited the name of the input for it complies with your function result.
"The problem is that after the ajax, my webpage is not going to findnote.php is just sending the value"
This is basically what ajax is made for :)
With ajax, you can, if you want, append the result to the current page (you didn't in your code. Just sent datas).
The other solution with form tag, the one above, load the result as a new page, like a classic link.
you need to create a form and pass a function on submit that will run before form submit and redirect
<form action="../consults/findnote.php" method="POST" onsubmit="myfunction()">
<input type="email" class="form-control" placeholder="Ingresar Número de Nota" id="idnote" name="idnote">
</div>
<button type="submit" class="btn btn-primary" id="notes">Enviar</button>
</form>
then in your jquery you can do
function myfunction() {
var formData = {
'id' : $('input[name=idnote]').val()
};
$.ajax({
type : 'POST',
url : '../consults/findnote.php',
data : formData,
dataType : 'json',
encode : true
})
.done(function(data) {
//Going to findnote.php and keeping formData
//This findnote.php contains a completely different design but I need the first value to make some changes for the user.
})
});
}

Form submission oncomplete

So on my page, I have a button where user can export the data to EXCEL/PDF. The way it works is they click on the button and then I send the data into a hidden form which submits the request. Once the request is done, it returns the content of the document type that the user selected which prompts the "Save As" dialog.
<form id="export-form" action="laravel-excel.php" method="POST" target="hidden-form">
<input type="hidden" name="type" value="{{header.export.type}}" />
<input type="hidden" name="name" value="{{header.export.name}}" />
<input type="hidden" name="data" value="{{header.export.data}}" />
</form>
<iframe style="display:none" name="hidden-form"></iframe>
So everything works as it should! However, I want to add a loader to let people know that the file is processing and when its done, I want to hide it. Well based on my research I was unable to find a solution that works for forms. The solutions I found are ones where the processing happens via AJAX like so:
$('#export-form').ajaxForm({
success: function (response, status, request)
{
var disp = request.getResponseHeader('Content-Disposition');
if (disp && disp.search('attachment') != -1)
{
var type = request.getResponseHeader('Content-Type');
var blob = new Blob([response], { type: type });
var URL = window.URL || window.webkitURL;
var downloadUrl = URL.createObjectURL(blob);
window.location = downloadUrl;
}
}});
Is there a better solution out there?

Handling Json results in ASP.NET MVC with jQuery

I am working on a view containing two forms, handled by separate controller actions which return a string serilaized to Json:
return Json(message);
The forms are submitted using jQuery, by clicking on a button outside the two forms.
The button handler:
$('#inviteForm').ajaxSubmit({
success: function(html, status) {
$("#response").text(html);
}
})
$('#trialForm').ajaxSubmit({
success: function(html, status) {
$("#response").append(html);
}
});
The browser receives the result and prompts the user to download as it is interpreted as "application/json".
However, if I only submit one of these forms in the jQuery, the resulting Json message is displayed as a string in the #response element as desired.
Why does adding a second ajaxSubmit() cause this different behaviour?
Thanks.
The view contains the following forms:
<form action="/Controller1/SaveAttachments/<%=Model.ObjectId %>" id="trialForm" method="post" enctype="multipart/form-data">
<input type="file" name="trialForm" size=30/>
<input type="file" name="trialSheet" size=30/>
<input type="file" name="trialApproval" size=30/>
</form>
and...
<form action="/Controller1/UpdateTemplate/<%=Model.ObjectId %>" id="inviteForm" method="post" enctype="multipart/form-data">
<%=Html.TextArea("invitationSheet", Model.InvitationSheet,
new { #name = "invitationSheet"})
<script type="text/javascript">
window.onload = function() {
var sBasePath = '<%=Url.Content("~/Content/FCKeditor/")%>';
var oFCKeditor = new FCKeditor('invitationSheet');
oFCKeditor.BasePath = sBasePath;
oFCKeditor.HtmlEncodeOutput = true;
oFCKeditor.ReplaceTextarea();
}
</script>
</form>
Update:
You can't upload files directly via AJAX so it is doing an actual post of the form containing file inputs. You should look at a plugin that will let you upload files using the hidden iframe technique that works asynchronously instead of trying to upload using AJAX.

Categories

Resources