So the html code i have:
<form id="loginIMGForm">
<input type="file" name="file" id="loginIMG" />
<br />
<input type="submit" name="submit" value="Submit" id="submitloginIMG" />
</form>
<div id="loginIMGStatus">Select an image and upload.</div>
and then PHP code i have:
<?php
$imageinfo = getimagesize($_FILES['loginIMGForm']['tmp_name']);
if($imageinfo['mime'] != 'image/gif' && $imageinfo['mime'] != 'image/jpeg') {
echo "Sorry, we only accept GIF and JPEG images\n";
exit;
}
$uploaddir = 'uploads/';
$uploadfile = $uploaddir . basename($_FILES['loginIMGForm']['name']);
if (move_uploaded_file($_FILES['loginIMGForm']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "File uploading failed.\n";
}
?>
and jquery is:
$('#loginIMGForm').submit(function() {
// 'this' refers to the current submitted form
var str = $(this).serialize();
alert(str);
$.ajax({
type: "POST",
url: "modules/upload.php",
data: str,
success: function(msg){
$("#loginIMGStatus").ajaxComplete(function(event, request, settings){
if(msg == 'OK'){ result = 'Login Image is updated'; }
else{ result = msg; }
$(this).html(result);
});
}
});
return false;
});
I did debuging using alert, the data is empty. What did I do wrong.
Thanks.
Why are you calling ajaxComplete?
Just do this instead:
$.ajax({
type: "POST",
url: "modules/upload.php",
data: str,
success: function(msg){
var result;
if(msg == 'OK'){ result = 'Login Image is updated'; }
else{ result = msg; }
$(this).html(result);
});
}
});
Also, when you say the data is empty, do you mean when you call alert or the html component?
Edit You can't use serialize on a file. It isn't supported and doesn't really make sense. See this page. Also, although it wasn't an issue yet, I do suspect you're going to have problems with calling ajaxComplete. The success parameter already handles calling your function when the ajax request completes. I'm not really sure what will happen with your code.
Related
I am building a PHP application where a new user has to upload an avatar.
I managed to save the uploaded file path into my database,
but now I have to move the uploaded image from the temporary to the permanent directory, which is the folder 'avatars'.
I have searched through many answers on the same problem but haven't managed to find a working one. Since I am really new to PHP I'm gonna need some help for a working solution.
I have also tried copy() instead of move_uploaded_file with no luck.
HTML:
<div class="input-form">
<label for="avatar">Kies een profielfoto</label>
<input type="file" id="avatar-input" name="avatar" accept="image/*" onchange="loadFile(event)">
<img id="output" width="150" />
<input type="submit" id="submit-btn" name="vervolledig-submit" value="START">
</div>
PHP:
if(!empty($_POST)){
$fileSize = $_FILES["avatar"]["size"];
if($fileSize < 2000000){
$fileSizeOk = true;
}else{
throw new Exception("Je profielfoto heeft een grotere file size dan is toegelaten (max 2MB)");
$imgSizeOk = false;
}
$img = $_FILES["avatar"]["name"];
if($imgSizeOk == true){
move_uploaded_file($_FILES["avatar"]["tmp_name"], "avatars/$img");
}
}
EDIT: was asked to share my JS code:
a function that shows a preview of the uploaded picture:
let loadFile = function(event) {
let image = document.getElementById('output');
image.src = URL.createObjectURL(event.target.files[0]);
};
Suggested solution with AJAX
$('#submit-btn').on('click', function() {
var file_data = $('#avatar-input').prop('files')[0];
var form_data = new FormData();
form_data.append('avatar', file_data);
alert(form_data);
$.ajax({
url: 'profielVervolledigen.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
alert(php_script_response); // display response from the PHP script, if any
}
});
});
with the following php code:
if(!empty($_POST)){
if ( 0 < $_FILES['avatar']['error'] ) {
echo 'Error: ' . $_FILES['avatar']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['avatar']['tmp_name'], 'avatars/' . $_FILES['avatar']['name']);
}
}
the alert gives [object FormData]
Thanks for any help
First of all, I've just met with ajax and jquery and I must admit they seem pretty interesting. But I lost quite some time on figuring out why are my results in uploading img-s always the same.The idea is creating a page where I could import multiple images with some restrictions such as size and extension,but for some reason errors just aren't printing. It just prints alert("Image Uploaded") no matter what the result. This is the ajax part of my html:
<script>
$(document).ready(function(){
$('#uploadForm').on('submit', function(e){
e.preventDefault();
$.ajax({
url: "upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
processData:false,
success: function(data)
{
$("#gallery").html(data);
alert("Image Uploaded");
}
});
});
});
</script>
And this is the upload.php that I simply call in my html file:
<?php
//upload.php
$output = '';
if(is_array($_FILES))
{
foreach ($_FILES['files']['name'] as $name => $value)
{
$totalImageIndex = ($name+1);
$file_name = explode(".", $_FILES['files']['name'][$name]);
$file_size = $_FILES['files']['size'][$name];
$allowed_ext = array("png", "gif");
if(in_array($file_name[1], $allowed_ext))
{
if($totalImageIndex <= 5 ) {
// 2 MB is 2097152 bytes.
if($file_size < 2097152){
$new_name = $totalImageIndex . '.' . $file_name[1];
$sourcePath = $_FILES['files']['tmp_name'][$name];
$targetPath = "slike/".$new_name;
if(move_uploaded_file($sourcePath, $targetPath))
{
$output .= '<img src="'.$targetPath.'" width="150px" height="180px" />';
}
}
else { continue ; }
} else echo 'file is too big!';
} else echo 'wrong file format!';
}
echo $output;}
?>
Any idea or suggestion would be appriciated, thank u in advance!
In ajax on success you will get the data back that you echoed on your php file so either you get the image back or the error back you can simply alert(data); only and see what you getting in your ajax code you are alerting alert(image uploded) which will always be called as you are getting an error data also as success just remove that alert and do only alert(data) and you will see the error if any
I have a form for a user to upload a profile picture and show them live validation without refreshing. I am trying to use AJAX but it does not seem to reach the PHP file. Also even though I am using preventDefault after I submit the form it reloads the page and opens the first tab which does not have the form on.
FORM
$avatar_form = '<div class="bhoechie-tab-content" id="uploadphoto">';
$avatar_form .= '<center>';
$avatar_form .= '<form id="avatar_form" method="post" enctype="multipart/form-data">';
$avatar_form .= '<h1>Change avatar</h1>';
$avatar_form .= '<input type="file" name="avatar" required>';
$avatar_form .= '<p><input type="submit" value="Upload"></p>';
$avatar_form .= '<p id="status"></p>';
$avatar_form .= '</form>';
$avatar_form .= '</center></div>';
PHP Snippet
if (isset($_FILES["avatar"]["name"]) && $_FILES["avatar"]["tmp_name"] != ""){
$fileName = $_FILES["avatar"]["name"];
$fileTmpLoc = $_FILES["avatar"]["tmp_name"];
$fileType = $_FILES["avatar"]["type"];
$fileSize = $_FILES["avatar"]["size"];
$fileErrorMsg = $_FILES["avatar"]["error"];
$kaboom = explode(".", $fileName);
$fileExt = end($kaboom);
list($width, $height) = getimagesize($fileTmpLoc);
if($width < 10 || $height < 10){
$result = "That image has no dimensions";
exit();
}
$db_file_name = rand(100000000000,999999999999).".".$fileExt;
if($fileSize > 1048576) {
$result = "Your image file was larger than 1mb";
echo $result;
} else if (!preg_match("/\.(gif|jpg|png)$/i", $fileName) ) {
$result = "Please only JPG, GIF or PNG images";
echo $result;
} else if ($fileErrorMsg == 1) {
$result = "An unknown error occurred";
echo $result;
}
AJAX
$('#avatar_form').submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'photo_system.php',
data: $(this).serialize(),
dataType: 'json',
success: function (result) {
console.log(result);
$('#status').html(result);
}
});
});
I have done something similar in the past myself as part of a plugin that has been written, the code that handles the image data and ajax is below:
var form_data = new FormData();
form_data.append($(_file).attr('name'), _file.files[0]);
var _this = this;
$.ajax({
type: "POST",
url: <<URL>>,
data: form_data,
cache: false,
contentType: false,
processData: false
})
This will submit the image that is loaded in the 'file' dialog box to the server and have it in the expected format for $_FILES superglobal.
Also bear in mind that this is just a snippet of the plugin.
Just use this Jquery parseJSON function and json_encode:
Keep this PHP code as it is:
$Stuff = 'Hello world';
$Success = true;
$Content = $Stuff;
$Response = array('Success' => $Success, 'Content' => $Content);
echo json_encode($Response);
And for the JS:
$.ajax({
type: "GET",
url: "../pgs/UpdateEditAStudent.php",
data: "FirstName="+ $('#student_first_name').val(),
success: function(data){
// Here is the tip
var data = $.parseJSON(data);
alert(data.Content);
}
});
I have fair knowledge of JS, PHP and Ajax but this simple problem has driven me nuts.
I am trying to upload an image silently, without using a form. I am not using a form because that will lead to nested forms in my HTML, which I read, can cause additional issues.
I have been able to use oFReader, to preview the images.
To upload the image, I am attempting an AJAX call as given below:
HTML
<div id="loginButton2">
<div id="personalimg" >
<img src="photos/seller_photos/<?php echo $profile_pic; ?>" width="70" hight="70" />
</div>
</div>
<div id="loginBox2" style="display:none">
<div id="loginForm2" class="floatLeft" >
<fieldset>
<input id="file" type="file" name="profile_img" value="photos/seller_photos/<?php echo $profile_pic;?>"/>
<input id="file_submit" type="hidden" name="submit4" value="1" >
</fieldset>
</div>
</div>
JS
$('#file').change(function(){
var oFReader = new FileReader();
oFReader.readAsDataURL(this.files[0]);
var fd = new FormData();
var file = $("#file").prop("files")[0];
fd.append('profile_img', file);
fd.append('submit4', 1);
fd.append('filename', 1);
oFReader.onload = function (oFREvent) {
$.ajax({
url: "upload.php",
dataType: 'image',
cache: false,
contentType: false,
processData: false,
type: "POST",
data: fd,
success: function(data){
console.log(data);
},
error: function(){
console.log("image upload failed");
}
});
$('#loginForm2').toggle();
$('#personalimg').html('<img src="'+oFREvent.target.result+'" width="70" height="70">');
};
});
PHP
if(isset($_POST['submit4'])) {
$check_sql = "select profile_pic from profile where user_id=$user_id";
$check_rs = mysql_query($check_sql);
$check_num = mysql_num_rows($check_rs);
if($check_num==0) {
$sql = "insert into profile(user_id) values($user_id)";
$rs = mysql_query($sql);
}
$fName = $_FILES["profile_img"]["name"] ;
$data = explode(".", $fName);
$fileName = $user_id.'.'.$data[1];
if($fName!='')$user->update('profile_pic',$fileName);
$fileTmpLoc= $_FILES["profile_img"]["tmp_name"];
//image store path
$pathAndName = "photos/seller_photos/".$fileName;
$moveResult = move_uploaded_file($fileTmpLoc, $pathAndName);
if(move_uploaded_file) {
$response['status'] = '1';
header('Location: edit_profile_new.php');
} else {
$response['status'] = '0';
}
return $response;
}
But somehow, I have not been able to get this to work. I am using chrome. I get 302 Found status code and "image upload failed" in console.
Can someone please help me out?
ps: I know, mysql is deprecated and will migrate to pdo. This code is inherited and hence has old standards.
To start things off, I've looked at a few similar problems on here but still can't resolve my issue here.
HTML:
<input type="file" name="filename" multiple="multiple" data-classIcon="icon-plus" data-buttonText="Upload Your File">
PHP:
$name = $_FILES['filename'];
$temp_name = $_FILES['filename']['tmp_name'];
if(isset($name)){
if(!empty($name)){
$location = 'uploads/';
if(move_uploaded_file($temp_name, $location.$name)){
echo 'uploaded';
}
}
} else {
echo 'error: not uploaded';
}
JS:
$('#cc-submit').on('click', function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "balanced/example.php",
data: $('#creditcardpost').serialize(),
success: function(data)
{
alert(data);
}
});
});
Error:
Undefined index: filename in /public_html/script.php on line xx (the two lines that collect the $_FILES variables.
"error: not uploaded"
You must use:
$name = $_FILES['filename']['name'];
I used print_r on $_FILES and found my files were coming through as "file-0". I'm not doing multi file uploads, so this works for me. And here is the solution. PHP:
$name = $_FILES['file-0']['name'];
$temp_name = $_FILES['file-0']['tmp_name'];
$location = '../uploads/';
if(move_uploaded_file($temp_name, $location.$name)){
}
print_r($name);
And the JS that sends it needed to be worked a bit:
var data = new FormData();
jQuery.each($('#file')[0].files, function(i, file) {
data.append('file-'+i, file);
});
$.ajax({
url: 'balanced/upload.php',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
$('#creditcardpost').append('<input type="hidden" value="' + data + '" name="filename" />');
}
});
I've got it working. Thanks for helping out guys.