I'm using jquery-ajax to check whether the file already exist in my server.
I have this code:
Upload an Event Photo <br>
<input type='file' name='imageSrc' id='imageSrc' /><br>
<a href='#' class='uploadPhoto'>Upload Image</a><br>
<div class='uploadMessage'></div>
<span>Maximum size: 1MB (jpg,png,gif)</span>
This is my jquery code:
jQuery(document).ready(function() {
jQuery('.uploadPhoto').click(function(){
// alert(1);
jQuery.ajax({
type: "POST",
url: "index.php?option=com_eventsandrsvp",
data: "task=uploadEventPhoto&format=raw",
success: function(data) {
jQuery(".uploadMessage").html(data);
}
})
});
});
I want to get the information that was there in the <input type='file' name='imageSrc' id='imageSrc' />
I know that that is a file type so there are information such as:
name,type,size, and tmp_name.
How would I do that using ajax?
I am trying to use a GET method but it doesn't work. maybe because it only works on <input type='text' />
Any help would be greatly appreciated.
Thanks!
You can't upload files using just jQuery.ajax(), to upload files via ajax, you can resort to:
Flash
Iframe trick
Above methods have their own drawbacks though.
Fortunately, there exists nice script uploadify you can use to upload files via ajax easily.
Related
I am trying to upload a image using AJAX jquery in a Joomla MVC framework.
Below is the default.php which adds the below javascript script code
$('#icon-submit').on('click',(function(e) {
$.ajax({
url: "index.php?option=com_jsmdownload&task=imageUpload",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
alert(data);
},
error: function(){
}
});
}));
Below is the HTML code which contains a simple file box and a button
<form action="<?php echo JRoute::_('index.php'); ?>" method="POST" name="adminForm" id="adminForm" enctype="multipart/form-data">
<input type="file" id="and_36x36" name="and_36x36">
<input id='icon-submit' type='button' value='Next ->' />
</form>
Below is the PHP code in controller.php for the imageUpload task.
function imageUpload(){
JFactory::getDocument()->setMimeEncoding( 'application/json' );
print_r($_FILES);
JFactory::getApplication()->close();
}
Once I select the file and click on the button the ajax function called and the PHP function also called but the form data is not available inside.
The print_r command always prints an empty array. I don't know what I am doing wrong. I want to get the selected file and upload them into the server and return back to the browser.
I referred multiple posts and cant able to find an answer. Can someone please advice.
UPDATE 1
If I set a independent PHP file as URL then it works. For example
url: "http://localhost/test/indextest.php",
But If I set the Joomla component path with controller it doesn't work.
You have to pass the form to the FormData object, what you have is the button.
in the button click event handler this refers to the button not the form.
Select the form and pass it to the FormData constructor
new FormData($(this).closest('form')[0]),
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.
My form uses javascript alerts to communicate with the user as this is the preferred method in the company I work for (as opposed to constant redirects to and from the php handler file).
Because of this, I pass all my form data through some simple validation in jquery and send it on to the php handler via ajax. Here's a basic look at how I'm doing it...
var first_name = $(sender + ' #first_name');
var email = $(sender + ' #email');
var tel = $(sender + ' #telephone');
var comments = $(sender + ' #comments');
$.ajax({
type: 'POST',
url: 'sendmail.php',
data: { first_name: first_name.val(),
email: email.val(),
telephone: tel.val(),
comments: comments.val(),
success: function clearFields() {
first_name.val('');
email.val('');
tel.val('');
comments.val('');
alert('Thank you. We will contact you as soon as possible.');
}
}
});
Having added an file input field to one such form as follows, I'm having trouble with the upload. While the email sends correctly, I don't think the ajax is sending any usable data for the upload on to the php file
<input type="file" name="upload" id="upload" />
<script>
var upload = $("#upload");
$.ajax({
type: 'POST',
url: 'sendmail.php',
data: { first_name: first_name.val(),
email: email.val(),
telephone: tel.val(),
upload: upload.val(),
comments: comments.val(),
success: function clearFields() {
first_name.val('');
email.val('');
tel.val('');
upload.val('');
comments.val('');
alert('Thank you. We will contact you as soon as possible.');
}
}
});
</script>
I've found a number of options for this, but all the ones I've looked at such as this seem "hackish" to me.
Is there a simpler way to do this?
Ajax does not support file upload operation. But there are many plugins which make use of iframes to upload files asynchronously. You can read more about this technique here.
Few jQuery plugins which supports form uploads are
1. jQuery form
2. jQuery-File-Upload
There are a lot of question answers regarding this in many Q&A sites, like this one.
Another solution using html 5 is discussed here which uses FormData.
You have to do this through an IFrame
So you create a hidden iframe
<iframe id="upload_target" name="upload_target" style="display: none;" src="#"></iframe>
<!-- note the src="#" -->
Then you create a form with some button and all fields you wish to have
<form action="path/to/uploadscript.php" method="POST" enctype="multipart/form-data" target="upload_target">
<!--target will tell the browser to run it in the iFrame with name="upload_target" -->
then in uploadscript.php you can use all form values as if they are regular $_POST values:
<?php upload_file($_FILES['file'], $_POST['name'], $_POST['whatever']); ?>
This almost feels the same as using AJAX.
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 am attempting to submit a form via jQuery. My form contains fields and a file that must be uploaded. It is of type ENCTYPE="multipart/form-data".
I can receive all my field values using: post = $('#myForm').serialize();
But how do I receive the $_FILES array? I need this to process the uploaded file.
Is this possible using jQuery, and if so how? Or do I need to use a special upload plugin for jQuery?
jquery form is the best way to do it,
you can add it to any normal form,
<form method="post" action="URL">
<input type="file" name="file">
<input type="text" name"text">
<input type="submit">
</form>
<script type="text/javascript">
$(document).ready(function() {
$(form).ajaxForm();
})
</script>
will work as expected, but with ajax.
http://malsup.com/jquery/form/#code-samples
You cannot upload files through javascript.
Check out this related question:
Is it possible to use Ajax to do file upload?
Essentially, the two most popular ways of "faking" AJAX for file uploads is using a Flash plugin such as SWFUpload or submitting the form to a hidden iframe that processes the request.
Form contains a file input, but is missing method=POST and enctype=multipart/form-data on the form. The file will not be sent
Use FormData
<form>
<label for="imageToSend">Cargar imagen a la galeria</label>
<input type="file" name="imageToSend" id="imageToSend" value="Cargar imagen" />
</form>
<script>
$('#imageToSend').on('change',function(event){
var dialog = $('#dialog');
var Data = new FormData();
Data.append('imageToSend',$('#imageToSend')[0].files);
$(this).val('');//Clear input file
$.ajax({
url: "/upload",
data: Data,
processData: false,
contentType: false,
type:'POST',
success: function(data){
if(data.success){
//success handler
}else if(!data.success){
//error backend handler
}
},
error: function(data){
//error handler Ej:404 status
}
})
});
</script>
If you can control the environment, like, say, you're writing an admin app for an intranet in which you recommend the browser, then real AJAX file uploads are possible with Firefox 3 and above. In all other cases, the iframe workaround or a Flash based uploader is the way to go.
It's possible, but not working in Google Chrome )
Look!
...
<form method='post' enctype='multipart/form-data'>
<input type="file" id="imf" name="imf"/>
<input type="button" id="Save"/>
</form>
...
$("#Save").live("click", function(){
var photo = document.getElementById("imf");
var file = photo.files[0];
$.post('/user/saveNewPhoto', {'imf':file.getAsDataURL(), fname:file.fileName }, function( data ){
alert ( data );
});
});
upload side script
need decode base64 ) and that is all
but i don't test this script on big size file