Possible to send an image file to PHP with AJAX? - javascript

I'm trying to send an image file along with other text information using AJAX, however I can't get the file part to work, as I don't quite understand how to do it.
Here is the Javascript:
//The user selects a file using an input element with the ID "picInput"
var picInput = document.getElementById("picInput");
picValue = picInput.files[0];
//"postString" is the string with all the other text information that is being sent
//All the other info in it is received fine, it is just the picture having problems
postString += "pic=" + picValue;
var xmlhttp = new XMLHttpRequest;
xmlhttp.open("POST","handler.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(postString);
And here is the PHP:
$pic = $_FILES['pic'];
ftp_put($ftpCon,"pics/".$name,$pic,FTP_BINARY) or die(mysqli_error($con));
With this code, I get 'undefined index' for the "$pic = $_FILES['pic'];" line.
If I change $_FILES to $_POST I get "ftp_put([object File]): failed to open stream: No such file or directory"

Are you trying to ajax a form content? If yes you could try AJAX form Plugin
$("body").on('submit','form#someForm', function(e){
e.preventDefault();
$(this).ajaxSubmit({
target: '#output',
success: afterSuccess
});
});
Then you'll have to put the file and the rest of your contents in
<form id="someForm" method="post" action="handler.php"></form>
and name your file input like
<input type="file" name="pic" />
the afterSuccess function will be called after everything is done
the #output can be used to show progress or things like that

Related

JQuery's .load function won't pass variable to my PHP file

I'm aware that this is possible using JQuery's ajax functions but I'm specifically wanting to try do this using JQuery's .load() function.
Here's my code:
HTML:
<form class="form" action="" method="POST" enctype="multipart/form-data">
<input type="file" name="csv-file">
<p class="upload-button">Upload</p>
<p class="upload-output"></p>
</form>
Javascript:
$('.upload-button').click(function() {
var formData = $('.form').serializeArray();
$('.upload-output').load('upload.php', formData);
});
When I click on the upload-button the form is serialized and sent to my PHP file called upload.php. This is the contents of upload.php - I'm currently just checking to see if it recieves the file at all:
if(isset($_FILES['csv-file'])){
echo 'found file';
} else echo 'no file';
All of this looks fine but for some reason it returns no file every time and I'm not sure why.
I've tried different input types like a text field, textarea and they all work but whenever I try to pass an input with type file it doesn't work. Why is this? and how can I get the file through to my PHP file using .load()? Is it even possible?
Actually, you can't upload files with Ajax that way because .serialize() only gives you the file names.
Use FormData:
$('.upload-button').click(function() {
var formData = new FormData($('form')[0]);
$('.upload-output').load('upload.php', formData); });
Also see: Sending multipart/formdata with jQuery.ajax
And: How can I upload files asynchronously?

Ajax file upload: what happens by default in form.onsubmit()?

I have a Java servlet that receives a file, processes it and then writes the resulting file back through HttpServletResponse's OutputStream.
For upload, I use a simple form:
<form id="upload-form" action="MyServlet" method="POST" enctype="multipart/form-data">
Select file to convert:
<input type="file" id="file-select" name="myfile" />
<button type="submit" id="upload-button">Upload</button>
</form>
After the file has been processed, a download dialog opens automatically.
Since processing may take a while (something like 30 seconds plus upload time), I wanted to provide some progress information through a websocket on the same page. This works if I do this:
var uploadForm = document.getElementById("upload-form");
var fileSelect = document.getElementById("file-select");
var uploadButton = document.getElementById("upload-button");
var httpRequest = new XMLHttpRequest();
uploadForm.onsubmit = function(event) {
event.preventDefault();
event.stopPropagation();
var file = fileSelect.files[0];
var formData = new FormData();
formData.append("myfile", file, file.name);
httpRequest.open("POST", "MyServlet", true);
httpRequest.send(formData);
};
The essential commands here seem to be event.preventDefault and event.stopPropagation.
The thing is: with this code, I get my progress info - but my download window never appears. If I comment out the two commands, it's the other way around. What happens by default when submitting a form, and (how) can I trigger that manually, so that I get both progress info AND the resulting file?
Note: I'm not using jQuery so far.

How to post multiple files to server one by one (due to server side restriction) using javascript from html input type file control

I have some server side restriction.
I want to read file to server one by one using javascript, in such a way that second file will post only after the response from previous file is received.
I have a multiple file upload in my webform as below:
<form id="frmSearchByC2V" method="post" enctype="multipart/form-data">
<input class="file" style="width:50px" type="file" name="c2vFile" id="txtSearchC2V" disabled onchange="locateFiles();" />
</form>
In my javascript i have code something like
<script>
function locateFiles()
{
var fileChooserControl = document.getElementById("txtSearchC2V");
var selectedFileLength = fileChooserControl.files!=null?fileChooserControl.files.length:1;
for(var i=0; i < selectedFileLength; i++)
{
document.forms["frmSearchByC2V"].action="locateFiles.html;
//Ajax call to submit the form
AIM.submit(document.getElementById("frmSearchByC2V"), {'onStart' : function(){return true;}, 'onComplete' : function(response){
loadSearchTargetGrid(response);
}});
document.getElementById("frmSearchByC2V").submit();
}
}
function loadSearchTargetGrid(response)
{
alert(response);
}
</script>
My problem is that whenever i post multiple file using window browser button. Everytime a received the same file to server. eg i choose file.txt,file2.txt,file3.txt and submit the form via javascript, i receive file3.txt in every request i made to the server.
Please provide the solution to fix this issue
If you're using YUI, you can use the Uploader utility. Uploader will upload each file in its own POST request and additionally you can set its simLimit attribute to 1 so that it only makes one request at a time. See: http://yuilibrary.com/yui/docs/uploader/.

Upload files without refreshing the page by using ajax post

I have a page file-upload.jsp with the code snippet below:
<form action="" id="frmupload" name="frmupload" method="post" enctype="multipart/form-data">
<input type="file" id="upload_file" name="upload_file" multiple="" />
<input type="submit" value="Update" />
</form>
I have 2 questions:
The moment I select some files, i.e the onchange event of the input type file, the file(s) should get uploaded.
I have a Java page that receives multipart request parameter and uploads the file to the said location. My problem is the form submission onchange, so that the Java file can proceed with further operations.
I googled and went through lot of articles. Some say it's not possible to upload files directly via Ajax, some say submit the form to an iframe via Ajax/jQuery.
I tried a lot of code from internet, such as this:
$(document).ready(function(){
$('upload_file').change(function(){
var data = new FormData();
data.append('file', $(this[0].files[0]));
$.ajax({
url: 'photo.jsp',
type: 'post',
contentType: attr('enctype', "multipart/form-data"),
data: data,
success: function(data){
alert(data);
}
})
});
});
but could not get the expected results.
I also need a progress bar for the upload operation.
Look at this example using an IFrame, is in PHP but changing the action should do the trick
Ajax Style File Uploading Using Hidden IFrame
Since you're already using jQuery, I would definitely go for the jQuery Form Plugin, which allows you to do form uploads via AJAX, even if the form contains a file input.
There is an example on its website available that shows how to display a progress bar.
Look at this example it is exact as you want
http://www.asp.net/ajaxlibrary/ajaxcontroltoolkitsamplesite/asyncfileupload/asyncfileupload.aspx

How do I use ajax to upload a text field and a file?

I'm new at AJAX and am working on an implementation of a form that will upload a name and a file to a php file that processes the data and sends it to a database for insertion using mysqli. I've tested the php file and it does work. My problem is in the AJAX code. I've tried an implementation using XMLHTTP and using jQuery. Both leave the page and open the PHP file in the browser. As a disclamer, I posted this question to another coding site, a fight ensued between two posters, and so I'm trying here to hopefully get a reasoned and calm response with productive suggestions.
I realize that currently "get" is being sent to the PHP file rather than "post", but PHPStorm tells me that "post" is not available in that form. What's my alternative? Am I on the right track or is there another direction I should go? How do I refresh only the form and keep the PHP page from loading?
Here's the relevant snippet of my code,
<!DOCTYPE html>
<html>
<head>
<script src="jquery.min.js"></script>
<script src="jquery.validate.js"></script>
<script>
$(document).ready(function() {
$('#addForm').validate({
submitHandler: function (form) {
$('input[name="usingAJAX"]', this).val('true');
var url = $(form).prop('action');
var dataToSend = $(form).serialize();
var callback = function(dataReceived) {
$(form).hide();
//result message
$('body').append(dataReceived)
};
var typeOfDataToReceive = 'html';
$.get(url, dataToSend, callback, typeOfDataToReceive),
return false;
}
});
});
</script>
</head>
<body>
<form id="addForm" action="addInfo.php" enctype="multipart/form-data">
<input type="hidden" name="usingAJAX" value="false"/>
<label for="aname">Name: </label>
<input type="text" name="aname" id="aname" class=required/>
<label for="aimage">Photo: </label>
<input id="aimage" type="file" name="aimage" class="required">
<input type="submit" value="ADD"/>
</form>
</body>
</html>
Until recently you could not upload files with ajax.
You still cannot upload the file directly with ajax, but you can do it programatically with HTML5 File API.
Still, if you are looking for simple solutions, try traditional IFrame approach.
If you want bleading edge technology, use File API. Here is some tutorial how to read files with javascript.
The steps to upload with ajax:
Read file with javascript FileReader API.
Post the content of the file, encoded to base64 or something, to the server.
Serverside, decode the contents of the file programatically.
When using this approach, the file will not be handled as a file upload by the server. It will be just another request field with text inside. It is up to you to decode it on the server side.
The filereader API allows you to read the file portion by portion and upload fragments of file, so it would be possible to upload huge files in chunks, but you need to handle it yourself.
Try using plugin jQuery form.js http://www.malsup.com/jquery/form/#file-upload You can upload files with ajax and jQuery. It is easy to use, just need to give #form-id in ajaxSubmit function.
<script>
$(document).ready(function() {
$('#addForm').validate({
submitHandler: function (form) {
$('input[name="usingAJAX"]', this).val('true');
var options = {
url : $(form).prop('action'),
dataToSend : $(form).serialize(),
callback : function(dataReceived) {
$(form).hide();
//result message
$('body').append(dataReceived) },
typeOfDataToReceive = 'html';
//your options here
};
$('#yourFormid').ajaxSubmit(options);
return false;
}
});
});
</script>

Categories

Resources