I am doing image upload without using submit button. When user choose a image, he upload immediately. But I have a problem, Ajax only print "succes", but image is not in folder. PHP without ajax work.
This is my html:
<form action="../PHP/fotogaleria.php" method="post" class="form_fotogaleria" enctype="multipart/form-data">
<div class="obal_fotogalerie">
<div class="stvorcek">
<label class="file_nahod">
<input type="file" name="odoslat_fotogaleria" class="odid">
<img class="priecinok" src="../Obrazky/folder.png">
<p> NahraƄ</p>
</label>
</div> <!-- koniec "stvorcek" -->
</div> <!-- koniec "obal_fotogalerie" -->
</form>
PHP:
$name = $_FILES['odoslat_fotogaleria']['name'];
$tmp_name = $_FILES['odoslat_fotogaleria']['tmp_name'];
$path = '../Obrazky-zvieratok/';
$cielovy_file = $path . basename($name);
move_uploaded_file($tmp_name,$path.$name);
echo "success";
And here is AJAX:
$('.odid').change(function(e) {
e.preventDefault();
$.ajax({
url: '../PHP/fotogaleria.php',
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function(data){
console.log(data);
}
Can someone help?
You're passing the input element to the FormData constructor. You should pass the form element instead.
data: new FormData($(this).closest('form').get(0)),
Related
Meanwhile I'm getting stuck on this issue. Normally, it's pretty simple but somehow it doesn't work for what I'm trying to do. I want to get all data from my form input fields by either Jquery or JS and then send them through AJAX to the server sided script (PHP). Even by using append or do it by serialize, I only obtain the object from input field with ID #file. I'm not using a submit button to confirm the uploaded image - only select the file and send it off.
I already tried too add
formdata.append("_token", document.getElementById('_token').val());
but whenever I try to append another element to the formdata the entire script stops working
By using $('#picUploadForm').serialize(); I do not get the any result from the input element with ID #file.
HTML:
<form enctype="multipart/form-data" id="picUploadForm">
<input type="file" name="file" id="file" style="display:none;" >
<input type="hidden" name="_token" id="_token" value="<?php echo $_SESSION['_token']; ?>" />
</form>
<!-- Default Avatar Image -->
<div class="click-slide overlay">
<!-- Profile Image-->
<img src="<?php if(isset($avatar['filelink']) && $avatar['filelink'] !='') { echo $avatar['filelink']; } else { echo "assets/images/avatars/default_avatar_large.png"; }?>" alt="" class="img-full-width-tight" id="imagePreview" />
<!-- Image update link -->
<div id="editLink" >
<span>
<a href="javascript:void(0);" class="pop-inline ti ti-image" ></a>
</span>
</div>
</div><!--/ click-slide-->
JS:
//On select file to upload
$('#file').on('change', function(e){
e.preventDefault();
var formdata = new FormData();
// any other code here....
} else {
// Upload Image to backend
formdata.append("file", document.getElementById('file').files[0]);
// formdata.append("_token", document.getElementById('_token').val()); // does not work!!!
// $('#picUploadForm').serialize(); // only returns data from input #_token
$.ajax({
url: "./serversided.php",
type: "POST",
data: formdata,
dataType: 'json',
cache: false,
contentType: false,
processData: false,
beforeSend: function(){
$("#statusav").removeClass().html('');
$('.overlay').LoadingOverlay("show");
HideLoadingOverlay();
},
success: function(data){
if(data.status === true){
// alert(data.imgURL);
setTimeout(function(){$("#statusav").removeClass('alert alert-danger').addClass('alert alert-success').html(data.reply)}, 2000);
$("#imagePreview").attr('src', data.imgURL);
} else {
// alert(data.error);
setTimeout(function(){$("#statusav").removeClass('alert alert-success').addClass('alert alert-danger').html(data.error)}, 2000);
}
}
});
}
});
.val() is a jQuery method - it is not a vanilla JS method, so it doesn't work when called on a plain element. document.getElementById will return an element (or null); $('selectors here') will return a jQuery object, on which you can use jQuery functions.
Try this instead, with vanilla JS:
formdata.append("_token", document.querySelector('#_token').value);
Or select the element with jQuery and use the jQuery method:
formdata.append("_token", $('#_token').val());
I have multiple input fields of type file generated using php foreach loop.Below is a snippet html form generated
<input name="userImage" id="a1Cym4V" type="file" />
<button type="button" onclick="upload_proof('a1Cym4V')">Upload</button>
<input name="userImage" id="pe7h6Cx" type="file" />
<button type="button" onclick="upload_proof('pe7h6Cx')">Upload</button>
<input name="userImage" id="L9iCaxV" type="file" />
<button type="button" onclick="upload_proof('L9iCaxV')">Upload</button>
If i upload an image using the first input form, it works fine, all others will return empty value even when a file is selected.
This is the javascript code i use to process the file upload via ajax.
function upload_prooff(id){
var formData = new FormData();
formData.append('file', $('input[type=file]')[0].files[0]);
formData.append('id', id);
formData.append('upload_proof', '1');
$.ajax({
url: "convert.php",
type: "POST",
data: formData,
contentType: false,
cache: false,
processData:false,
success: function(data){
console.log(data);
}
});
}
The data contains var_dump($_FILES) from the server.
What is the best approach to solve this problem?
so i have a form update but my problem is i cant save my image into my database only the file path..
here is my code.
<form action="" id="update_profile" method="POST" enctype="multipart/form-data">
<div class="col-md-4">
<img class="img-responsive" id="profile_image" name="profile_image" src=""/>
<input class="btn-success" type="file" name="image" id="image" onchange="loadFile(event)">
</div>
<input type="text" id="users_lastname" name="users_lastname" class="form-control" value="">
</form>
from the form update i use ajax to display the data from my database to the form fields..
$.ajax({
url:'../ajax/getprofile.php',
type:'POST',
data:{userid:user},
dataType:'JSON',
success: function(result){
$('#profile_image').attr('src',result.profile_image);
$('#users_lastname').val(result.users_firstname);
},
error:function(status){
}
});
$('#update_profile').submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: '../ajax/update_profile.php',
type:'POST',
data: formData,
dataType: 'JSON',
contentType: false,
cache: false,
processData:false,
success:function(result){
console.log(result);
},
error:function(status){
// console.log(status.responseText);
}
});
});
and use another ajax for submitting the form so basically what happens is from the <img src="../assets/img/faces/avatar.jpg"> this is where i display my image from my db. and when i click the <input class="btn-success" type="file" name="image" id="image" onchange="loadFile(event)"> <img src="../assets/img/faces/koala.jpg"> will change its value...
if (isset($_POST)) {
$users_lastname = $_POST['users_lastname'];
$profile_image = $_POST['profile_image'];
$imgFile = $_FILES['image']['name'];
$tmp_dir = $_FILES['image']['tmp_name'];
$imgSize = $_FILES['image']['size'];
}
if($imgFile)
{
$upload_dir = '../assets/img/faces/'; // upload directory
$imgExt = strtolower(pathinfo($imgFile,PATHINFO_EXTENSION)); // get image extension
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
$userpic = rand(1000,1000000).".".$imgExt;
if(in_array($imgExt, $valid_extensions))
{
if($imgSize < 2000000)
{
// unlink($upload_dir.$_SESSION['image']);
move_uploaded_file($tmp_dir,$upload_dir.$userpic);
}
else
{
echo '<script>
alert("Sorry, your file is too large it should be less then 2MB");
</script>';
}
}
else
{
echo '<script>
alert("Sorry, only JPG, JPEG, PNG & GIF files are allowed.");
</script>';
}
}
else
{
$userpic = $imgs; // old image from database
$userpic = substr($userpic,20);
}
if(!isset($errMSG))
{
$path = '../assets/img/faces/'. $userpic;
$action= 'Updated his/her information';
$logs= $log->insertLogs($usernm,$action);
$res = $users->Userupdated($user,$users_firstname,$users_lastname,$users_email);
$data = $users->updateUserdetail($user,$path,$profile_contact,$profile_address,$profile_department,$profile_specialization,$profile_aboutme);
}
else{
$errMSG = "Sorry Data Could Not Updated !";
}
but when i tried to upload without replacing the image from the src. what happens is it only uploads the location path not the exact image. also when i replace the image it only uploads the location path.. i dont know if this is the correct approach for getting the src image any idea for this?
Try this, I used this in one of my proect:
var form = $("#update_profile").get(0);
e.preventDefault(); //keeps the form from behaving like a normal (non-ajax) html form
$.ajax({
url: '../ajax/update_profile.php',
type: 'POST',
data: new FormData(form),
dataType: 'json',
mimeType: 'multipart/form-data',
processData: false,
contentType: false,
success: function (response) {
},
error: function (data) {
}
});
I'm in the process of building a function in uploading a file(CSV) using AJAX. This is just a rough code since that I'm working and currently following a tutorial. I'm using XAMPP for server side languages
After executing i'm getting an alert that displays (obect FormData) inside and aside from that, the uploads directory is empty after submitting the file. Project currently has three items. (Uploads Folder, index.php and upload.php)
HTML
<form method="post" enctype="multipart/form-data">
<input id="file-uploading" type="file" name="fileUploading" />
<button id="upload" value="upload">Upload</button>
</form>
JAVASCRIPT
$('#upload').on('click', function() {
var file_data = $('#file-uploading').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
alert(form_data);
$.ajax({
url: 'upload.php',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(){
console.log('success');
}
});
});
PHP
<!doctype html>
<html>
<body>
<?php
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error' . $_FILES['file']['error'] . '<br/>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}
?>
</body>
</html>
I test successful.I think "uploads" permissions is not right.You should do:
sudo chown -R www-data:www-data uploads
I think you are missing out on enctype attribute on form.
The enctype attribute specifies how the form-data should be encoded when submitting it to the server.
<form method="post" enctype="multipart/form-data">
// your content
</form>
Hope this helps..
I am making a simple page where user can upload a image without refreshing the whole page. But if(isset($_post[oneimgtxt])) is not working..
here is my serverSide Code that upload image :
<?php
$maxmum_size = 3145728; //3mb
$image_type_allowed = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_BMP);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(isset($_POST["oneimgtxt"])){//<!------------------ this line is not working
if((!empty($_FILES[$_FILES['upimage']['tmp_name']])) && ($_FILES["upimage"]['error'] == 0)){
$file=$_FILES['upimage']['tmp_name'];
$image_count = count($_FILES['upimage']['tmp_name']);
if($image_count == 1){
$image_name = $_FILES["upimage"]["name"];
$image_type = $_FILES["upimage"]["type"];
$image_size = $_FILES["upimage"]["size"];
$image_error = $_FILES["upimage"]["error"];
if(file_exists($file)){//if file is uploaded on server in tmp folder (xampp) depends !!
$filetype =exif_imagetype($file); // 1st method to check if it is image, this read first binary data of image..
if (in_array($filetype, $image_type_allowed)) {
// second method to check valid image
if(verifyImage($filename)){// verifyImage is function created in fucrenzione file.. using getimagesize
if($ImageSizes < $maxmum_size){//3mb
$usr_dir = "folder/". $image_name;
move_uploaded_file($file, $usr_dir);
}else{
$error_container["1006"]=true;
}
}else{
$error_container["1005"]=true;
}
}else{
$error_container["1004"]=true;
}
}else{
$error_container["1003"]=true;
}
}else{
$error_container["1002"]=true;
}
}else{
$error_container["1007"]=true;
}
}else{//this else of image issset isset($_POST["oneimgtxt"])
$error_container["1001"]=true;//"Error during uploading image";
}
echo json_encode($error_container);
}
?>
in chrome inspect element i got this..
image
and this is my js code with ajax...
$(".sndbtn").click( function(e){
var form = $("#f12le")[0];
var formdata = new FormData(form)
$.ajax({
type:'POST',
//method:'post',
url: "pstrum/onphotx.php",
cache:false,
data: {oneimgtxt : formdata},
processData: false,
contentType: false,
success:function (e){console.log(e);}
});
});
Here is html code:
<form method="post" id="f12le" enctype="multipart/form-data">
<input type="file" name="upimage"/>
<label for="imgr">Choose an Image..</label>
<textarea placeholder="Write something about photo"></textarea>
<input type="button" name="addimagedata" value="Post" class="sndbtn"/>
</form>
Thanks for any help.
You should send your FormData as a whole data object not a part of another data object. So, it should be like this -
$(".sndbtn").click( function(e){
var form = $("#f12le")[0];
var formdata = new FormData(form)
$.ajax({
type:'POST',
//method:'post',
url: "pstrum/onphotx.php",
cache:false,
data: formdata,
processData: false,
contentType: false,
success:function (e){console.log(e);}
});
});
Now, you should be able to access the form as it is. For example if you have any input with name inputxt inside the form, you should be able to access it with $_POST['inputxt']. And if you have any input type="file" with the name upimage, you need to access through $_FILES['upimage']. So, if you want to do isset() for that. You can do like this :
if(isset($_FILES['upimage'])){
add enctype on form any time using file inputs
<form enctype="multipart/form-data" >
<input type=file />
...
</form>
and make sure it's always a POST request.
Good luck...!
I had headaches for this thing! you should use $_FILES['name_of_dom_element']; in your php code.