I'm trying to upload a file send in a form. I'm trying it with php, but between html and php I use JS and Jquery and ajax (because I don't want the page to reload). And I'm having troubles with the $_FILES.
Here it is, I'm using a form (which contains a file input) with a javascript action (action="javascript: SendPresupMail();").
In that JS function I use a little Jquery and ajax, inside it, there is a call to a php function.
The problem is that inside that php function the $_FILES is empty, and I need to upload the file send in the form.
Here is the code:
HTML form, calling to JS:
<form action="javascript: sendPresupMail();" method="post" id="formId" enctype="multipart/form-data">
<input type="text" id="mail" name="mail" />
<input type="file" id="file_selected" name="file_selected" />
<input type="submit" value="Submit" />
JS function, and call to PHP with AJAX and JQUERY:
function sendPresupMail() {
$.ajax({
url: 'remote.php',
type: 'post',
data: {
'w': 'sendPresupMail',
'mail': document.getElementById('mail').value
},
success: function(data) {
if(data != "ok" && data != ""){alert(data);}
if(data == "ok"){alert("mail send.");}
}
});
}
Finally, the PHP code:
private function sendPresupMail(){
$filename = ($_FILES['file_selected']['name']);
...
...
}
The code there is irrelevant, the issue is that $filename is not receiving anything because $_FILES it's empty (I checked it with a var_dump, and it's empty). So I can not upload the file, what should I do?
SOLVED
Here is the solution:
Actually it was a lot simplier than I thought. First, I create an iframe, so now all the form, javascript, ajax, etc. is hapenning inside the iframe. So it seems like the page is not refreshing, because the iframe is doing it.
Thanks all for your answers anyway!
You can't do it with pure Ajax/jQuery, but you can do it in combination with the JavaScript FormData object which is supported in all latest versions of the major browsers.
A really simple jQuery example can be found here: https://coderwall.com/p/p-n7eq
A more detailed, yet pure JavaScript, can be found here: https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects?redirectlocale=en-US&redirectslug=Web%2FAPI%2FFormData%2FUsing_FormData_Objects
The $_POST variable on the page you are posting to is populated from the data you are submitting in the $.ajax call. That data has no file inputs, and I'm not sure it can. Take a look around for some handy plugins.
This recommends using the jQuery Form Plugin: jQuery AJAX post with fileupload
I've personally used Uploadify previously: http://www.uploadify.com/
Or manually do it: http://net.tutsplus.com/tutorials/javascript-ajax/uploading-files-with-ajax/
Check if $_POST is also empty. $_POST and $_FILES tend to be empty when the file uploaded exceeds upload_max_filesize or post_max_size
Related
I was wondering how I could go about sending a .csv file from a file input container in HTML to another .php file in ajax.
Here's my code:
$(document).ready(function () {
$(".Rsubmit").click(function () {
?????What would I declare to contain the .csv file?
var checkurl = './CSVRemove/getAccountsCSV.php';
runCSVcheck(checkurl);
});
});
function runCSVcheck(checkurl)
{
$.ajax({
type: "POST",
//dataType: "json",
url: checkurl,
data:
{
???? what would I put here?
},
success: function(response) {
code....
});
}
HTML:
Input boxes.....
<span>Enter .csv File: </span><input type="file" name="file" value="" />
Please let me know if there is a solution!
David
If you're planning on sending a file upload via Ajax, I suggest using a jQuery form plugin that support file uploads.
There are a number of them available, but I've had good success with this one: http://www.malsup.com/jquery/form/
It allows you to post a form via Ajax, even if the form includes file upload fields. PHP will receive the form post exactly as it would have done normally if it had been posted via a regular form submit.
Alternatively, you could use HTML5's file API, but only if you don't need to support older browsers like IE8. The jQuery form plugin is probably the safer way to go for now.
hope that helps.
i have a simple form:
<input type="hidden" name="MAX_FILE_SIZE" value="2097152" id="MAX_FILE_SIZE">
<input type="file" name="file_upload" id="file_upload" class="picture_main">
<input type="submit" name="upload_picture" id="upload_picture" value="Submit">
i am trying to to an ajax upload:
submit.on("click", function(){
var file = $('#file_upload').val();
uploadImageAjax(file);
return false;
});
var uploadmageAjax = function(file)
{
$.ajax({
type: "POST",
url: "/test/index/imageupload",
data: {
'file': file
},
dataType: "json",
success: function (data) {
console.log(data);
}
});
}
what i get back is, for example, file: "C:\fakepath\weirdan003-10.jpeg"
but im not sure what that fakepath is !?
if i were to do it in php only i would get the image like this:
if (isset($_POST['upload_picture']) ) {
$data = $formImageUpload->getValues();
$pictureName = $data['picture'];
....
and then upload it.
So what i want to figure out is if the ajax call POST's to that action the right file so i can then upload it to the disk.
will $('#file_upload').val(); hold the $_FILE??
any ideas?
thanks
var file = $('#file_upload').val();
This will return only a path to file on client machine. for securit reason it is returned like c:\fakepath\file_name.ext. If I remember correctly, in some older browsers it was possible to get a real path. But still, it does not helps you to get a file on server.
For ajax style upload you can use some of plugins you got recommended. Or just use jQuery Forms plugin. It will work very similar to $.ajax.
Now, when file is uploaded correctly, you will find all required info about it in $_FILES
In your case it will be something like $_FILES['file_upload'] where 'file_upload' is a name of your file input.
Now you can move it from temporary storage with move_uploaded_file. And do whatever you want with that file
EDIT:
And I see you are using Zend. Take a look at this about how to work with FileUpload element on the server side. With Zend you may use FileUpload methods instead of move_uploaded_file
jQuery ajax does not support asynchronous file uploads. See jQuery upload file using jQuery's ajax method (without plugins).
If you want to use ajax file upload, it is recommended to implement plugins:
http://valums.com/ajax-upload/ (is my favorite)
http://www.webdeveloperjuice.com/2010/02/13/7-trusted-ajax-file-upload-plugins-using-jquery/ lists several more
For client side, I suggest you to use a plugin.
http://blueimp.github.com/jQuery-File-Upload/
http://valums.com/ajax-upload/
For server side, you will need to handle it to read from the stream. I think there is a full example (client and server side) on valums git.
I need to make a button, and when I click on it I'll do the same if I had such form:
<form action="myscript.php" method="post">
<input type="hidden" name="items[]" value="..." />
<input type="submit">
</form>
and clicked submit. On the PHP side I use proper headers and make the force download.
The reason why I can't use a form here, because I have a lot of parameters, and it's not that easy to use a form tag in my HTML markup. Moreover, these parameters are dynamically made, so...
But if I use just $.ajax of course It won't work, I'll just get php response in this ajax request, but the browser won't start downloading the file
Any suggestions?
Just redirect to the download page, if it has the correct headers on that page, it wont change what page they're on, just download the file with a prompt.
Simple answer: Don't use GET. Use POST instead!
<script>
var info = ""; // Somewhere for the response to go
var obj = $.post(
raw_url,
{ var1:value1, var2:value2 },
function(data) { info = data; } );
</script>
On the PHP side, you'll receive any array based data AS an array (thus if value2 were a javascript array, you'll receive it in PHP as an array as well.)
I have this HTML:
<form action='uploadhandle.php' method='POST' enctype="multipart/form-data">
<input type='file' class='fileinput' id='photo1' name='photo1'>
<input type='button' id='upload1' name='upload1' value='Upload'>
</form>
My jquery code is:
$('#upload1').click(function(){
$.ajax({
url: "uploadhandle.php",
data: 'photo1='+photo1,
success: function(data){$('#result_div').html(data)}
});
In my uploadhandle.php, when I try to display the $_POST['photo1'], nothing comes up, it's "undefined".
Does anyone know what I did wrong?
Thanks a lot,
Regards
You cannot upload a file via AJAX. It isn't possible.
What IS possible is using a plugin or another method that "simulates" ajax by creating an iframe and submitting the info in the background. There are several plugins that handle this, some are very complex, some simply extend the ajax function itself.
That being said, your syntax server side is also wrong. You have to deal with $_FILES not $_POST to find and use the submitted file.
Good luck.
You can't upload file data through XHR (i.e. ajax). There is a file upload API in XHR2, but the most practical and cross browser compatible way today seems to use a hidden iframe to do the file upload.
Edit: See How do you post to an iframe?
I have an HTML form that previously was only used for text attributes for users, that was all using AJAX to call a PHP controller functions via URLs to refresh page content via database and server-side calls (abridged version)
<input type="text" id="firstname" name="FIRSTNAME"/>
<input type="text" id="lastname" name="LASTNAME"/>
<input name="Submit"type="submit" value="Submit" />
This "create user" form now needs to incorporate a file uploading mechanism, for user images
<input type="file" name="userImage" />
The problem is that the form is being submitted via .serialize in the .ajax #create form submit
$.ajax({
url: 'controller.php?command=create',
type: 'POST',
data: $( form ).serialize(),
create URL calls the PHP controller echo $dmv->create(); , which is the model public function create(){ //execute database insert and execute
I have read that serialize does not make sense for files, which is true, but I also want to try to figure out how to update my existing form to incorporate file upload functionality to it
I have tried to understand the jquery.form.js plugin ( http://malsup.com/jquery/form/#file-upload ) but cannot understand how to tie it all together.
I believe what I need to do is have the file upload execute as a separate logic, then tie back with the original logic for file name , this is file storage with the unique image name stored in the database under the record, not BLOB image storage.
Let me know if I can provide any further info, and thanks to any help that can be given.
You can't upload files via AJAX. The only possibilites you have are using Flash (such as Uploadify: http://www.uploadify.com/), an iFrame, or just submitting the form. The form must have an enctype set to multipart.
<form action="script.php" method="post" enctype="multipart/form-data">
Plugins may mimic AJAX file uploads by creating a "hidden" iframe.
Example: http://valums.com/ajax-upload/
You can mimic an AJAX call by using a hidden iframe. You can even achieve a callback function and get the server response just like an AJAX call:
HTML --
<form enctype="multipart/form-data" target="workFrame"></form>
<iframe id="workFrame" style="display:none;"></iframe>
JS--
//bind an event handler to the form with the file input
$('form').on('submit', function () {
//check to make sure the user has selected an image, if not then stop the form from submitting
if ($('#userImage').val().length == 0) return false;
//bind an event handler to the `load` event for the iframe so we will have a callback for the form submission
$('#workFrame').on('load', function () {
var $this = $(this);
//remove this event handler
$this.off('load');
//get the response from the server
var response = $this.contents().find('body').html();
//you can now access the server response in the `response` variable
});
//return true so the form submits normally
return true;
});
Note that .on() is new in jQuery 1.7 and is the same as .bind() in this case.
Here is a example of what Michael is talking about. http://www.phpletter.com/Our-Projects/AjaxFileUpload/