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