I already having image upload code which is working good, It has only one image upload option in it.
Here image is sent to the function in which it will upload and return the image src code and image path, once returned it will be filled at the $('#image').html(data);
It works good when i have single option, while i have two upload it fails,
The error i faced is it works on the first
<input type="file" id="image" name="image" class="upload-img" style="opacity:0">
and while i tried the second
<input type="file" id="imagetwo" name="imagetwo" class="upload-img" style="opacity:0">
It replaces the image in the first input type,
I have the $('#image').html(data);
in first function and $('#imagetwo').html(data);
in the second function
I am using $("form#data").submit(function(){}
Here is the HTML :
<input type="file" id="image" name="image" class="upload-img" style="opacity:0">
<input type="hidden" class="imagetextbox" name="imagetextbox"/>
Here is the Script :
<script>
$(document).ready(function()
{
$("form#data").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: 'globalimageupload',
type: 'POST',
data: formData,
async: true,
success: function (data)
{
$('#image').html(data);
console.log(data);
},
cache: false,
contentType: false,
processData: false
});
return false;
});
$("input[type='file']").on("change", function()
{
$("form#data").submit();
});
});
</script>
Here is the Image Handle Function :
public function globalimageupload()
{
$file = Input::file('image');
if (Input::file('image'))
{
$valid_exts = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
$max_size = 2000 * 1024; // max file size (200kb)
$ext = $file->guessClientExtension();
$size = $file->getClientSize();
if (in_array($ext, $valid_exts) AND $size < $max_size)
{
$image=Input::file('image');
$destinationPath = public_path()."/assets/uploads/companylogo/";
$num_unique = md5(uniqid() . time());
$fileName=$num_unique.'.'.$ext;
Input::file('image')->move($destinationPath,$fileName);
$desPathimg=public_path()."assets/uploads/companylogo/".$fileName;
$desPath=$fileName;
return HTML::image('assets/uploads/companylogo/'.$fileName,'photo', array( 'width' => 128, 'id'=> 'po', 'name'=> 'po', 'height' => 128 )).'<input type="hidden" name="imagetextbox" id="imagetextbox" value="'.$desPath.'">';
}
else
{
return 'Check the Extension and file size';
}
}
else
{
return "Please upload any Image";
}
}
What is the mistake i am doing and how can i fix this ?
Use unbind function just before binding the submit event as below:
$("input[type='file']").on("change", function(){
$("form#data").unbind('submit');
$("form#data").submit();
});
happens when you bind the event (i.e here it is submit) again and again. Here on the page load you have bind the submit event, again u are binding the same on input change event, so the code will execute twice and will upload file twice.