I created an ajax function that previews the uploaded image and saves it to a folder. The problem is is that the ajax is only called once. If the file I choose was not an image a string would be returned and a new input file html is inserted replacing the old file input field. I'm unfamiliar with XHR, only having a basic understanding of it. My question is, is it possible to call this ajax twice and if so how. Currently Firebug only receives one aja call. Afterwards, no matter what file I choose nothing happens.
var handleUpload = function (event) {
var fileInput = document.getElementById('url2');
var session_user_id = <?php echo $session_user_id; ?>;
var profile_user_id = <?php echo $user_id; ?>
var data = new FormData();
data.append('ajax', true);
data.append('file', fileInput.files[0]);
data.append('session_user_id', session_user_id);
data.append('profile_user_id', profile_user_id);
var request = new XMLHttpRequest();
request.upload.addEventListener('load',function(event) {
$('#upload_progress').css('display', 'none');
});
request.upload.addEventListener('error', function(event) {
$('#uploaded').html('Upload Failed!');
});
//code below is part of callback of ajax
request.addEventListener('readystatechange', function(event){
if (this.readyState == 4){
if (this.status == 200) {
var links = document.getElementById('uploaded');
var uploaded = eval(this.response);
$('#uploaded').empty();
if (uploaded[0] == 1 || uploaded[0] == 2 || uploaded[0] == 3) {
$('#uploaded').html('Some error occured!');
$('#container_for_url2').html('<input type="file" name="file" id="url2" />');
} else {
$('.preview_image_box2').html('<img width="' + uploaded[1] + '" height="' + uploaded[2] +'" style="position:relative;top:'+ uploaded[3]+'" src="' + uploaded[0] + '"/>');
}
}
} else {console.log('server replied with' + this.status)}
});
request.open('POST', 'ajax_upload_image_for_post.php');
request.setRequestHeader('Cache-Control', 'no-cache');
$('#upload_progress').css('display','block');
request.send(data);
};
Here I am setting up the ajax call when the input file field url2
has a file inserted into it. I suspect this is the problem.
$('#url2').change(function () {
handleUpload();
});
Since you're replacing the input #url2, $('#url2').change() would not work. try delegating it instead
$('#container_for_url2').delegate('#url2', 'change', function() {
handleUpload();
});
The line
$('#container_for_url2').html('<input type="file" name="file" id="url2" />');
implies that the element to which the change
handler is attached, is overwritten by its own action.
You can overcome this by delegating to the element's container as follows :
$('#container_for_url2').on('change', '#url2', handleUpload);
Note: We use .on()
since jQuery 1.7 . .bind()
, .live()
and .delegate()
are now deprecated.
... as I now realise you already know because I just read your comment under @suke's answer :)
Just in case it helps here is the format to using jquery for this. I usually like to keep things simple, but ajax is one of the things I do like jQuery for.
THIS IS THE CODE WITH JQUERY with no plugins needed
//Prepare params
var POSTParamsObject = {
file : fileInput.files[0],
session_user_id : session_user_id,
profile_user_id : profile_user_id
}
//Function for handle upload
function handleUpload() {
return $.ajax({
url : 'ajax_upload_image_for_post.php',
type : 'POST',
data : POSTParamsObject,
//dataType : 'json', //Uncomment if you don't use json as your response from server
beforeSend: function ( xhr ) {
$('#upload_progress').css('display','block');
}/*,
success : function(){//success code},
error : function(){//error}
*/
});
}
//Run ajax call and respond to server response. First argument is the status 200 response, and second argument is to respond to errors
$('#container_for_url2').on('change', '#url2', function(){
$.when(handleUpload()).then(function(uploaded){//If request was successful...status 200
var links = document.getElementById('uploaded');
$('#uploaded').empty();
if (uploaded[0] == 1 || uploaded[0] == 2 || uploaded[0] == 3) {
$('#uploaded').html('Some error occured!');
$('#container_for_url2').html('<input type="file" name="file" id="url2" />');
} else {
$('.preview_image_box2').html('<img width="' + uploaded[1] + '" height="' + uploaded[2] +'" style="position:relative;top:'+ uploaded[3]+'" src="' + uploaded[0] + '"/>');
}
},
function(response){//This is if there is a server error, or the wrong data type is returned
console.log(response);
});
});