jquery faking an ajax request - php

To make a nicer experience of a file upload, I am faking an ajax request i.e The user clicks submit, the form dissapears a loading graphic appears and after a view seconds the page refreshs to show their newley upload image.
However since adding the jquery in my file upload always returns the same errors,
You did not select a file to upload. Why is this? This is my form,
<div id="picture_upload">
<div class="loading"></div>
<?php echo form_open_multipart('my_profile/do_upload'); ?>
<strong>Choose pictures to upload</strong>
<p>Max file size: 1MB .jpeg, .gif, .png or .bmp</p>
<input type="file" name="userfile" />
</div>
<!--<div id="webcam_upload">
<p>Hello</p>
</div>-->
</div>
<div id="bottom"><table><tr><td><input type="submit" id="submit_upload" value="Upload a picture" class="button green rounded_5 small" /></td><td>or</td><td><a href="#" id="close_modal" />Cancel</a></td></tr></table></div>
and my js,
$("#submit_upload").click(function(e){
//alert("here");
setTimeout(function() { $("#picture_upload form").submit();}, 6000);
$("#picture_upload").children().hide();
$(".loading").show();
setTimeout( function() { location=$("#picture_upload form").attr('action') }, 1500 );
return false;
});
The upload function is just your basic upload function from codeigniter.

For security reasons You can't upload a file using an XmlHttpRequest object (AJAX).
Alternative solutions are:
Load your file submission form in an iframe and post that with JS
Use a flash file uploader
Use HTML5
Here's a jQuery plugin that appears quite popular: http://www.uploadify.com/

Try like this,
$("#submit_upload").click(function(e){
//alert("here");
setTimeout(function() { $("#picture_upload form").submit();}, 6000);
$("#picture_upload").children().hide();
$(".loading").show();
return false;
});
And then redirect/reload the page using php
header('Location: URL_TO_REDIRECT'); //put it in your end of upload script in php file
If you don't want to redirect from PHP then, you can use
jQuery Form plugin http://jquery.malsup.com/form/#file-upload
SWFUpload http://demo.swfupload.org/v220/index.htm
(there are many libraries for uploading file.)

If you want to learn how to build your own upload using jQuery here is a good article - http://www.peachpit.com/articles/article.aspx?p=1766159

Related

jQuery image upload with dynamic loading

I have a single image form I would like to upload my images with for a store page. It simply needs to be clicked, show the upload box, and then autoSubmit when they select the image and replace the one image with the new uploaded item.
Here is the current page layout, with no actual upload button. On image click, we will show the upload windows on users PC:
This is the code for the highlighted area in the HTML field
<div class="uploader">
<form method="POST" id="upload_image">
<img src="/img/upload.png" id="imageUpload" alt="upload" />
</form>
</div>
So once the form submits, using an Ajax request, when it returns and is successful I plan to store the image name (usually the current time() as filename) as a session variable, now I need to show a Loading... image while the upload process happens and then replace the imageUpload with the new image located in /img/thumbs/NEWIMAGENAMEHERE.png.
Question Time
Is there a jQuery function that I can use to replace the image with the loading image and then the loaded image once upload completes? Is there a jquery library already for SINGLE image upload like this? all the library's I have found work for multiple images and since we only support one image on this store layout, we don't want multiple image upload.
Thanks
Thanks to suggestion from #aron9forever I have decided instead of upload the image right away on it's own, I would simply display the image and then upload on form submit. This does pose the annoying issue that when they submit the form, if there is an issue, that they need to re-click upload image but I may have a way around that using $_POST variables.
<div class="uploader">
<img id="imagetoUpload" src="/com/img/upload.png" alt="upload">
</div>
<input type="file" id="productImage" style="display:none;" name="img" value="">
Using this jQuery
$(function() {
function readURL(input) {
if(input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#imagetoUpload').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
};
$("#productImage").change(function(){
readURL(this);
});
$("#imagetoUpload").click(function() {
$("input[id='productImage']").click();
});
});

How to upload an image to server on change

I have an input tag like
<form id="myForm">
<!-- has lots of inputs above like username password etc -->
<input type="file" id="user_photo" name="user_photo" tabindex="6" size="6" class="" accept="jpeg|png|jpg|gif|PNG|JPEG|GIF|JPG" >
OnChange, I would want to upload an image through AJAX and save it in server. After saving, it should display in a preview div where I can use jCrop to crop as user wishes and save it again to the server (after cropping) when user clicks submit button.
If you have a better method please tell me.
inshort, I just want to trigger an ajax post request with the file contents and save it into my uploads folder without sending the rest of the form elements.
I use codeigniter. I have tried fileuploader by valum.. didnt give me the result.
Answer was stolen from here: Can i preview the image file who uploaded by user in the browser?
Use the HTML5 File Api to load the image client side.
Then use jCrop at the after loading the image into a tag.
Then (I'm assuming) use jCrops onRelease method to do the Ajax call.
That way its only one ajax call, and its already modified
<img id="preview" src="placeholder.png" height="100px" width="100px" />
<input type="file" name="image" onchange="previewImage(this)" accept="image/*"/>
<script type="text/javascript">
function previewImage(input) {
var preview = document.getElementById('preview');
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
preview.setAttribute('src', e.target.result);
$('#preview').Jcrop({
onRelease: yourAjaxFunctionToSubmitToServer
});
}
reader.readAsDataURL(input.files[0]);
} else {
preview.setAttribute('src', 'placeholder.png');
}
}
</script>
Obviously this will need to be modified a bit to suit your needs, but you get the idea.

How to upload image with Jasny's bootstrap imagepreview?

I'm trying to use Jasny's Bootstrap. This is nice work!
I coudn't find solution for bootstrap upload image on page http://jasny.github.com/bootstrap/javascript.html#fileupload
With bootstrap-fileupload.js, how can I upload image using Ajax?
I asked this question to directly ARNOLD DANIELS who is owner of Jasny's Bootstrap.
Here is his answer:
The whole point of the image preview is that the picture is show right
away, without the need to upload it to the server using AJAX. So it
stays just a regular form. You can post a form using AJAX
http://api.jquery.com/jQuery.post/ if needed.
If you do want to upload the image using AJAX and don't want to use a
form, checkout
http://www.9lessons.info/2011/08/ajax-image-upload-without-refreshing.html
I used this sample with removing database releated lines and worked perfectly for me !
First you need to register the css and js files:
If you are using Yii Framework:
$cs = Yii::app()->clientScript;
$cs->registerCSSFile("/css/fileupload.css");
$cs->registerScriptFile('/js/fileupload.js', CClientScript::POS_END);
Or
<link rel="stylesheet" type="text/css" href="/css/fileupload.css">
<script type="text/javascript" src="/js/fileupload.js"></script>
Then register the following script:
$cs->registerScript("imageUpload", "$('.fileupload').fileupload({uploadtype: 'image'});", CClientScript::POS_END) ;
Or
<script type="text/javascript">
$('.fileupload').fileupload({uploadtype: 'image'});
</script>
Then add the following HTML code to your page:
<div class="fileupload fileupload-new" data-provides="fileupload">
<div class="fileupload-preview thumbnail" style="width: 200px; height: 150px;"></div>
<div>
<span class="btn btn-file"><span class="fileupload-new">Select image</span><span class="fileupload-exists">Change</span><input type="file" /></span>
Remove
</div>
</div>
I came across this question on Google and just wanted to show I did it for anyone else interested (even if it's not the most elegant way)
$(document).ready(function(){
$('.fileinput-preview').bind('DOMNodeInserted', function(event) {
var imgdata = ($('.fileinput-preview img').attr('src'));
$.post( "upload.php", { imgdata: imgdata})
.done(function( data ) {
alert( "Data Loaded: " + data );
});
})
})
This above piece of code detects when the file input preview has changed. It then finds the base64 data from the image tag, and uses jquery to post it to upload.php.
Upload.php simply takes the base64 image data and saves it as an image
$imgdata = $_POST['imgdata'];
$ifp = fopen("newimage.jpg", "wb");
$data = explode(',', $imgdata);
fwrite($ifp, base64_decode($data[1]));
fclose($ifp);
The upload on jasny is more than a preview or client side upload management instead an ajax, probably you need tp use other method or plugin, cause the jasny upload will send the preview path using the binary image displaying

Getting the uploaded file information using jquery-ajax

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.

jQuery - receiving the $_FILES array using $.post

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

Categories