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?
Related
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
I am using a custom options framework which is working in all browsers except for Internet Explorer (what a surprise!). The submit form is configured like this;
<form action="<?php echo site_url() .'/wp-admin/admin-ajax.php'; ?>" method="post" id="mobeus-form">
In all other browsers, when the form is submitted, the changes are saved as expected. But, in Internet Explorer, it seems to be accessing the PHP file directly, as it has this in the url bar;
http://mydomain.com/wp-admin/admin-ajax.php
The page itself has a line of text;
{"error":false,"message":"Settings Successfully Saved!","type":""}
Nothing else happens, the settings are not saved, and I am left baffled. If anyone could help I'd appreciate it!
admin-ajax.php file is meant for ajax process, so instead of trying it in form action attribute try with jquery stuff to pass the data to admin-ajax and retrieve the value, or try something like below to use the same form with jquery submission.
var data = jQuery("#myForm :input").serializeArray();
jQuery.post(jQuery("#myForm").attr("action"),data, function(info) {
// success code ;
});
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 have a form which automatically refreshes the page on submit, I have tried adding:
onSubmit="return false;" to the form element, but then the form just stops and nothing happens when you click submit.
I wouldnt mind the page refresh so much but the form is at the bottom of the page and the refresh kicks you back to the top. So I tried this approach:
<form name='test' method='POST' action="index.php" onSubmit="window.scrollTo(5000,500);">
This works for a split second but then something else overrides it (not sure what)
I have also tried using php: header.location just to get a "headers have already been sent" error.
The site in question can be seen here, and the form is at the very bottom.
The only two jquery libraries I am using that I could foresee any conflicts with are nicescroll and (more likely) waypoints, but i dug through them both and couldn't find any conflicting issues.
If anyone knows of a way to keep the functionality of the form but stop the refresh of the page, that would be wonderful
Thanks
EDIT: After reading the answers below, it looks like I will have to use ajax to acomplish this, I have absolutely no experience with ajax, so I will see how that goes.
It seems you need to go through of way of AJAX submission in that case. In that case, you can use jQuery $.ajax() method to do that. A sample below:
HTML
<form name='test' method='POST' action="index.php">
jQuery
$('form[name=test]').submit(function(e) {
e.preventDefault();
window.scrollTo(5000,500);
// a sample AJAX request
$.ajax({
url : this.action,
type : this.method,
data : $(this).serialize(),
success : function(response) {
}
});
});
Here, .preventDefault() is for stop page refresh on form submit.
Why not submit the form to a hidden IFRAME?
<iframe name="myiframe" style="display: none;"></iframe>
<form name='test' method='POST' action="index.php" target="myiframe">
...
</form>
What about using AJAX instead of a normal form submit?
I am trying to submit a form via ajax using:
$(document).ready(function(){
$("#ajax-form").submit(function(){
$.post(
"albums.php",
$("#ajax-form").serialize(),
function(){
}
);
return false;
});
});
I am posting data to the facebook graph api. I need to send the form text fields and image data to the remote facebook api server. Is this possible? Thanks!
This is a simple jQuery plugin to implement and works for me for running file uploads seemingly via AJAX. It is meant to run on forms of all kinds, but it does support file uploads. Though it uses iFrames, it runs everything silently without notice, and it works flawlessly every time for me:
http://jquery.malsup.com/form/
Is this possible? Thanks!
No, doesn't look like it:
How can I upload files asynchronously?