Uploading File using Ajax PHP [duplicate] - javascript

This question already has answers here:
Uploading both data and files in one form using Ajax?
(13 answers)
Closed 7 years ago.
I am trying to upload a file and sending it through AJAX.. but i am getting below error..
Notice: Undefined index: xlsFile in
Below is my Coding :
HTML FORM : (this form is in Modal Popup)
<form id="form2" class="importModal" enctype="multipart/form-data">
Upload Excel File : <input type="file" name="xlsFile" id="xlsFile" />
<button type="button" id="addType" name="addType">Submit</button>
</form>
AJAX Code :
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function () {
$("button#addTripType").click(function(){
alert("hello");
$.ajax({
type: "POST",
url: "ajax-Upload.php", //
data: $('form.importModal').serialize(),
success: function(msg){
alert("success");
},
error: function(){
alert("failure");
}
});
});
});
</script>
What should i Do..??? Need Help..??

I had the same issue, it is possible with FormData if you are using IE >= 10. For all and IE >= 8 one way to trick it is using form in iframe.
An easy way to do that is using jquery.form plugin : http://malsup.com/jquery/form/
You can put method and action in your form :
<form id="form2" method="post" action="ajax-Upload.php" class="importModal" enctype="multipart/form-data">
Upload Excel File : <input type="file" name="xlsFile" id="xlsFile" />
<input type="submit" id="addType" name="addType" value="Submit" />
</form>
And then with plugin api :
$('#form2').submit(function() {
$(this).ajaxForm({
success: function(msg) {
alert("success");
},
error: function(){
alert("failure");
}
});
return false;
});

Related

AJAX submit multipart form within textarea and inputs [duplicate]

This question already has answers here:
jQuery AJAX file upload PHP
(5 answers)
Closed 3 years ago.
Well, I have tried a lot of JS codes to post one form with multiple data [2 Files & 1 textarea] and they didn't work well.
But How to send non-empty form data to PHP using AJAX?
<form method="post" enctype="multipart/form-data">
<textarea id="acas"></textarea>
<input id="uimage" type="file" name="image" accept=".png,.jpg,.gif"/>
<input id="uaudio" type="file" name="audio" accept=".mp3"/>
<input id="armes" style="display: none;" name="send" type="submit"/>
</form>
By default I use this JS code below to submit form, But it reloads page:
$("#acas").on('keydown', function(e) {
if (e.key == "Enter") {
if (e.shiftKey) {
} else {
e.preventDefault();
$("#armes").click();
}
}
});
Use this code
$(document).on('submit', 'form', function (e)
{
var form = new FormData(this);
jQuery.ajax({
url: "",
method: 'POST',
processData: false,
contentType: false,
dataType: "json",
data: form,
success: function (response)
{
}
});
return false;
});

how to upload file and save to directory? [duplicate]

This question already has answers here:
How can I upload files to a server using JSP/Servlet and Ajax?
(4 answers)
Closed 6 years ago.
HTML
<div style="width:200px">
<form action="javascript:_bulkUser();" method="post" enctype="multipart/form-data">
Select File:<input type="file" name="fname"/><br/>
<input type="submit" value="upload"/>
</form>
</div>
js(ajax call)
_bulkUser : function(scope) {
try {
$.ajax({
type : "post",
url : "FileUploadServlet",
success : function(data) {
alert('Sucess');
},
error : function(data) {
console.log(data);
}
});
} catch (e) {
console.log(e);
}
}
Servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
System.out.println("working");
MultipartRequest mp = new MultipartRequest(request, "e:/new");
out.print("successfully uploaded");
}
To the point, as of the current XMLHttpRequest version 1 as used by jQuery, it is not possible to upload files using JavaScript through XMLHttpRequest. The common workaround is to let JavaScript create a hidden and submit the form to it instead so that the impression is created that it happens asynchronously. That's also exactly what the majority of the jQuery file upload plugins are doing such as jQuery Form plugin (example here).
Assuming that your JSP with the HTML form is rewritten in such way so that it's not broken when the client has JS disabled (as you have now...), like below:
<form id="upload-form" class="upload-box" action="/Upload" method="post" enctype="multipart/form-data">
<input type="file" id="file" name="file1" />
<span id="upload-error" class="error">${uploadError}</span>
<input type="submit" id="upload-button" value="upload" />
</form>
Then it's with help of jQuery Form plugin just a matter of
<script src="jquery.js"></script>
<script src="jquery.form.js"></script>
<script>
$(function() {
$('#upload-form').ajaxForm({
success: function(msg) {
alert("File has been uploaded successfully");
},
error: function(msg) {
$("#upload-error").text("Couldn't upload file");
}
});
});
</script>
As to the servlet side, no special stuff needs to be done here. Just implement it exactly the same way as you would do when not using Ajax: How to upload files to server using JSP/Servlet?
You'll only need an additional check in the servlet if the X-Requested-With header equals to XMLHttpRequest or not, so that you know how what kind of response to return for the case that the client has JS disabled (as of now, it are mostly the older mobile browsers which have JS disabled).
if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
// Return ajax response (e.g. write JSON or XML).
} else {
// Return regular response (e.g. forward to JSP).
}
Note that the relatively new XMLHttpRequest version 2 is capable of sending a selected file using the new File and FormData APIs. See also HTML5 File Upload to Java Servlet and sending a file as multipart through xmlHttpRequest.
This code also works fine for me :
$('#fileUploader').on('change', uploadFile);
function uploadFile(event)
{
event.stopPropagation();
event.preventDefault();
var files = event.target.files;
var data = new FormData();
$.each(files, function(key, value)
{
data.append(key, value);
});
postFilesData(data);
}
function postFilesData(data)
{
$.ajax({
url: 'yourUrl',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
processData: false,
contentType: false,
success: function(data, textStatus, jqXHR)
{
//success
},
error: function(jqXHR, textStatus, errorThrown)
{
console.log('ERRORS: ' + textStatus);
}
});
}
<form method="POST" enctype="multipart/form-data">
<input type="file" name="file" id="fileUploader"/>
</form>

How to pass file from JavaScript to PHP? [duplicate]

This question already has answers here:
Is it possible to use Ajax to do file upload?
(7 answers)
Closed 7 years ago.
Is it possible to pass file from JavaScript to PHP? (Best using ajax).If we have following code:
<!DOCTYPE html>
<html>
<body>
<input type='file' id='upld' onChange=' f=this.files[0] '>
<input type='button' onClick='ajax_pass()'>
<script>
function ajax_pass()
{
console.log(f);
//Send 'f' using ajax to php imaginary file...
}
</script>
</body>
</html>
I'm new to JS programming and can't imagine how POST or GET can contain whole image.Can you clarify it to me please?
HTML Code
<input id="myfile" type="file" name="myfile" />
<button id="upload" value="Upload" />
Jquery Code
$(document).on("click", "#upload", function() {
var file_data = $("#myfile").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({
url: "/upload_file.php",
dataType: 'script',
cache: false,
contentType: false,
processData: false,
data: form_data, // Setting the data attribute of ajax with file_data
type: 'post'
});
});
Php Code
print_r($_FILES);
print_r($_POST);

How to Upload and Display File Using Play Framework and jQuery?

I have one scenario: I am uploading one file at some server location using: https://www.playframework.com/documentation/2.0/JavaFileUpload ,
//Uploading file:
<input type="file" name="fileUpload">
<input type="submit" value="Upload">
And from the below code, I am uploading the above uploaded file and getting/displaying it on my view page like(After clicking the Submit button):
<input type="file" id="inputfile">
<input type="button" value="Submit" id="submitfile">
jQuery:
$("#submitfile").click(function(){
var path1 =$('input[type=file]').val().replace(/C:\\fakepath\\/i, '');//uploaded file names
//adding the Play framework server path for Application to get the image(s) file(s) path
var filespath = '/files/images/'+path1;//giving my uploaded files path here
});
But my requirement is that: I need only one type which does both: accepts/uploads the file at server location and returns/displays the same file path from server location on my view page ? I am struggling for it. Please help me.
This looks like a similar issue to 33163555. That question has the following example:
Edit: Reference 2320069 for support on ajax file uploads & alternatives:
FormData support starts from following desktop browsers versions. IE
10+, Firefox 4.0+, Chrome 7+, Safari 5+, Opera 12+
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<form enctype="multipart/form-data">
<input type="file" id="file" name="file" />
<input type="submit" id="submit" name="" value="Upload" />
</form>
<script>
$('#submit').click(function (event) {
event.preventDefault();
var file = $('#file').get(0).files[0];
var formData = new FormData();
formData.append('file', file);
$.ajax({
url: 'upload',
data: formData,
type: 'POST',
contentType: false,
processData: false,
beforeSend: function (data) {
alert('Are you sure you want to upload document?');
},
success: function (data) {
//call your jQuery action here
alert('Upload completed: ' + data);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus + ': ' + errorThrown);
}
});
return false;
});
</script>
In your routes you have:
POST /upload controllers.Application.upload()
Where your controller method returns the filepath:
public static Result upload() {
MultipartFormData body = request().body().asMultipartFormData();
FilePart fileP = body.getFile("file");
if (fileP != null) {
File file = fileP.getFile();
//If we want to move from temp
//FileUtils.moveFile(file.getCanonicalPath(), "FileB");
return ok(file.getCanonicalPath());
} else {
return badRequest("Upload Error");
}
}
And you can perform your custom jQuery action in the ajax success callback

send data from inputs like form by java script [duplicate]

This question already has answers here:
How to submit a form with JavaScript by clicking a link?
(9 answers)
Closed 9 years ago.
I have a table and every row has a form:
<td><input type="date" id='time'/></td>
<td><input type="text" id='info'/></td>
<td><input type="text" id='money'/></td>
<td><input type="buttond" id="submit_edit" value="edit"/></td>
The problem is I can't submit a form like this, so I need to submit this with JavaScript, and I need to submit it using the POST method. I want the POST method to do this as one row; I will change the id of the inputs later.
This is not like this question: How to submit a form with JavaScript by clicking a link?
I want to send data manually by id. The correct thing I need is like this
$(document).ready(function(){
$("#submit_edit").click(function(){
var time=$("#time").val();
var info=$("#info").val();
var money=$("#money").val();
$.ajax(
{
type: "POST",
url: "edit.php",
data: {time:time , info:info,:money:money},
success: function(html)
{
$("#edit_result").html(html).show();
}
});
});
});
If you want to do it via ajax it's like this:
// this is the id of the form
$("#form_id").submit(function() {
url="page.php";
data1=$("#selector").val();
data2="value";
$.ajax({
datatype:"html",
type: "POST",
url: url,
data: {data1:data1,data2:data2},
success: function(html)
{
alert(html);
}
});
});
you have jquery ?
First
if not, try this.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
you can download http://jquery.com/download/
also
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
Ok, now
u need send a form?
then
ur button:
<input type="submit" name="edit" id="button_submit"/>
ur form
<form action="" method="POST" id="form">
then the jquery
$('#button_submit').click(function(){
$('#form').submit();
});

Categories

Resources