September 14, 201511 yr Morning all, I've had an account here for a while but for the life of me can't remember the login details, so I created a new account. This has been bugging me for hours and after trawling the web I thought I'd best bite the bullet and ask... This is a bit PHP and a bit Jquery/Javascript, so apologies if this is in the wrong forum. I have a user profile page and I want to be able to upload a profile image (via dropzone), get the new upload path, retrieve the path via JSON and then update the image via some javascript. At the moment, the image disappears after a new upload (great), but the src is "undefined". For some reason I am not being able to retrieve the JSON data. Here is a screenshot... Here is the relevant code for the USER_edit.php page... <div class="row"> <div class="col-xs-7" id="photo"> <?php if(!empty($user[0]['profile_photo_path'])){ ?> <img src="<?php echo $user[0]['profile_photo_path']; ?>" class="droppable-area" id="advancedDropzone"> <?php }else{ ?> <div id="advancedDropzone" class="droppable-area"> No Profile Photo </div> <?php } ?> </div> <div class="col-xs-5"> <table class="table table-bordered table-striped" id="example-dropzone-filetable"> <tbody> <tr> <td colspan="5">Click circle or drag and drop to change photo</td> </tr> </tbody> </table> <div class="well well-sm">150px width & 150px height recommended. JPEG/GIF/PNG only.</div> <script type="text/javascript"> jQuery(document).ready(function($) { var i = 1, example_dropzone = $("#advancedDropzone").dropzone({ url: 'data/USER_edit_photo_upload.php', method: 'POST', dataType: 'json', acceptedFiles: ".jpeg,.jpg,.png,.gif", parallelUploads: 999, maxFilesize: 100, params: {"id": "<?php echo $_GET['id']; ?>"}, // Events addedfile: function(file) { if(i == 1) { $example_dropzone_filetable.find('tbody').html(''); } var size = parseInt(file.size/1024, 10); size = size < 1024 ? (size + " KB") : (parseInt(size/1024, 10) + " MB"); var $entry = $('<tr>\ <td><div class="progress progress-striped"><div class="progress-bar progress-bar-warning"></div></div></td>\ </tr>'); $example_dropzone_filetable.find('tbody').append($entry); file.fileEntryTd = $entry; file.progressBar = $entry.find('.progress-bar'); }, uploadprogress: function(file, progress, bytesSent) { file.progressBar.width(progress + '%'); }, success: function(file,resp) { file.fileEntryTd.find('td:last').html('<span class="text-success">Uploaded</span>'); file.progressBar.removeClass('progress-bar-warning').addClass('progress-bar-success'); $("#photo").html('<img src="' + resp.changePhoto + '">'); }, error: function(file) { file.fileEntryTd.find('td:last').html('<span class="text-danger">Failed</span>'); file.progressBar.removeClass('progress-bar-warning').addClass('progress-bar-red'); } }); $("#advancedDropzone").css({ minHeight: 200 }); }); </script> </div> </div> Here is the USER_edit_photo_upload.php <?php session_start(); header('Content-Type: application/json'); include('DB_centre.php'); $resp = array('changePhoto' => ''); // For ajax response if(function_exists('http_response_code')) http_response_code(200); // begin Dave B's Q&D file upload security code $allowedExtensions = array("txt","csv","htm","html", "css","doc","xls","rtf","ppt","pptx","pdf","swf","flv","avi", "wmv","mov","jpg","jpeg","gif","png","docx","xlsx","zip","rar","pub","pubx","msg","xps","xlsm","pptm","mp4","docm"); foreach ($_FILES as $file) { if ($file['tmp_name'] > '') { if (!in_array(end(explode(".", @strtolower($file['name']))), $allowedExtensions)) { // Need to send message here exit(); } } } // end Dave B's Q&D file upload security code $fileName = $_FILES['file']['name']; $remove[] = "'"; $remove[] = '"'; $remove[] = '\\'; $fileName = str_replace( $remove, "", $fileName ); $lastDot = strrpos($fileName, "."); $fileName = str_replace(".", "", substr($fileName, 0, $lastDot)) . substr($fileName, $lastDot); $fileDesc = $_FILES['file']['name']; $tmpName = $_FILES['file']['tmp_name']; $fileSize = $_FILES['file']['size']; $fileType = $_FILES['file']['type']; $fp = fopen($tmpName, 'r'); $content = fread($fp, filesize($tmpName)); $content = addslashes($content); fclose($fp); if(!get_magic_quotes_gpc()) { $fileName = addslashes($fileName); } // Make folder if it doesn't exist if (!file_exists('../assets/images/profile-photos/'.$_SESSION['centre_id'].'/')) { mkdir('../assets/images/profile-photos/'.$_SESSION['centre_id'].'/', 0777, true); } $target_path = "../assets/images/profile-photos/".$_SESSION['centre_id']."/"; $currdate = date("Y-m-d-hh-ss"); //strip unwanted characters from filename $fileName = preg_replace(array('/\s/', '/\.[\.]+/', '/[^\w_\.\-]/'), array('_', '.', ''), $fileName); $fileName_actual = $fileName; $fileName = $currdate . "-" . $fileName; $target_path = $target_path . $fileName; if(!move_uploaded_file($_FILES['file']['tmp_name'], $target_path)){ }else{ $target_path = "assets/images/profile-photos/".$_SESSION['centre_id']."/" . $fileName; $id = $_POST['id']; /// GENERATE SQL TO ENTER FILE DETAILS $sql_add_file = "UPDATE users SET profile_photo_path = ? WHERE id = ?"; // PREPARE THE STATEMENT $stmt_add_file = $conn->prepare($sql_add_file); if($stmt_add_file === false) { trigger_error('Wrong SQL: ' . $stmt_add_file . ' Error: ' . $conn->error, E_USER_ERROR); exit(); } // BIND THE PARAMETERS... s = string, i = integer, d = double, b = blob */ $stmt_add_file->bind_param('si',$target_path,$id); if ($stmt_add_file->execute()) { $resp['changePhoto'] = $target_path; }else{ } echo json_encode($resp); } ?> Is an there a PHP warning on the USER_edit_photo_upload.php page perhaps? Causing the JSON headers to be incorrect? If anyone could point me in a good direction I'd appreciate it!
September 14, 201511 yr Author Thanks for the reply Nock. I added it... success: function(file,resp) { file.fileEntryTd.find('td:last').html('<span class="text-success">Uploaded</span>'); file.progressBar.removeClass('progress-bar-warning').addClass('progress-bar-success'); $("#photo").html('<img src="' + resp.changePhoto + '">'); console.log(resp); }, and I still get.. <img src="undefined"> I tried adding console.log(resp); before and after the call for changePhoto
September 14, 201511 yr Author Thanks for the help with this by the way. (I can only make 19 more posts today, darn)
September 14, 201511 yr Author Wow, thanks guys. Due to you introducing me properly to the chrome dev options I figured this out. My image processing PHP was throwing up a warning due to this... if(@!in_array(end(explode(".", strtolower($file['name']))), $allowedExtensions)) { } I supressed the error for the time being with @, and it works great. Thank you all
September 14, 201511 yr Author Hmmm. This worked. But I have encountered a new problem. When changing the HTML via... $("#photo").html('<img src="' + resp.changePhoto + '" class="droppable-area dz-clickable" id="advancedDropzone" style="min-height: 200px">'); The dropzone no longer functions. I click the image but I do not get shown a file browser.
September 14, 201511 yr Hmmm. This worked. But I have encountered a new problem. When changing the HTML via... $("#photo").html('<img src="' + resp.changePhoto + '" class="droppable-area dz-clickable" id="advancedDropzone" style="min-height: 200px">'); The dropzone no longer functions. I click the image but I do not get shown a file browser. You will need some sort of callback that reinitiates the Dropzone plugin, because once your AJAX request has finished, your code can no longer locate the #advancedDropzone element as it has been changed. Why don't you simply alter the SRC of the image rather than replace the image itself? e.g. $('#advancedDropzone').attr('src', resp.changePhoto);
September 14, 201511 yr Author You will need some sort of callback that reinitiates the Dropzone plugin, because once your AJAX request has finished, your code can no longer locate the #advancedDropzone element as it has been changed. Why don't you simply alter the SRC of the image rather than replace the image itself? e.g. $('#advancedDropzone').attr('src', resp.changePhoto); That worked immediately! Thank you so much Lyndsey, and Nock D4Y0
Create an account or sign in to comment