dropzone.js edit (add/delete) pre-exisitng image files in Magento - javascript

below is my code for deleting images when clicked on "remove file" CTA on the dropzonejs box. However, when the "remove file" is clicked, only the thumbnail image is deleted, and not the actual file.
By calling the delete function in Magento through Ajax when the "removedfile" is called, it should delete the thumbnail as well as the file, but it does not seem to work as the server still keeps the pre-loaded image file.
this.on("removedfile", function(file) {
alert("here");
jQuery.ajax({
url: "<?php echo Mage::getUrl("*/*/deleteimage"); ?>",
type: "POST",
dataType: "json",
data: {'pid': "<?php echo $loadpro->getId(); ?>",'file':file.name},
success: function (data) {
Success = true;//doesnt goes here
},
error: function (textStatus, errorThrown) {
jQuery("#vals").text('');
var det = checkfile('<?php echo $loadpro->getId(); ?>');
if(det != null)
{
maxcount = 1;
}
else {
maxcount = null;
}
}
});
Below is the code for the Magento controller that is called in the function above that listens for the "removedfile."
public function deleteimageAction()
{
$id= $this->getRequest()->getParam('pid');
$imagename= $this->getRequest()->getParam('file');
$product = Mage::getModel('catalog/product')->load($id);
$productMediaConfig = Mage::getModel('catalog/product_media_config');
$mediaGallery = $product->getMediaGalleryImages();
foreach($mediaGallery as $mediagg){
$file = $mediagg->getUrl();
$fileName = basename($file);
if($fileName == $imagename){
$filepath = $mediagg->getFile();
}
}
try{
$storeId=Mage::app()->getStore()->getStoreId();
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$newimage = '';
$data= $this->getRequest()->getParams();
//error_log(print_r($data, TRUE));
$_product = Mage::getModel('catalog/product')->load($data['pid'])->getMediaGalleryImages();
$main = explode('/',$filepath);
foreach($_product as $_image) {
$arr = explode('/',$_image['path']);
if(array_pop($arr) != array_pop($main)){
$newimage = $_image['file'];
$id = $_image['value_id'];
break;
}
}
$mediaApi = Mage::getModel("catalog/product_attribute_media_api");
$mediaApi->remove($data['pid'],$filepath);
if($newimage){
$objprod=Mage::getModel('catalog/product')->load($data['pid']);
$objprod->setSmallImage($newimage);
$objprod->setImage($newimage);
$objprod->setThumbnail($newimage);
$objprod->save();
}
Mage::app()->setCurrentStore($storeId);
} catch (Exception $e) {
$this->getResponse()->setHeader('Content-type', 'text/html');
$this->getResponse()->setBody('');
}
}
I have tried most of the methods that are in google, as well as stackoverflow, but could not find an answer that works in this case.
If you know a solution to this problem, please let me know.

Related

how to upload image from codeigniter to mysql

I am new in CodeIgniter. I am not getting how to update form data in the database. Insertion and showing data from database is done but can't understand how to update data in the database.
I've tried researching this link but data not successfully uploaded.
This is my Controller
//npwp
$temp1 = explode(".", $_FILES['file_npwp']['name']);
$new_name1 = time().'.'.end($temp1);
$config1['upload_path'] = APPPATH.'/file_npwp/';
$config1['file_name'] = $new_name1;
$config1['overwrite'] = TRUE;
$config1['allowed_types'] = 'jpg|jpeg|png|pdf';
$this->load->library('upload',$config1);
$this->upload->initialize($config1);
if(!$this->upload->do_upload('file_npwp')){
$this->data['error'] = $this->upload->display_errors();
}
$media1 = $this->upload->data('file_npwp');
This is my Model
$data_service['file_npwp']= $file_lampiran1;
$data_service['file_ktp']= $file_lampiran2;
$data_service['file_po']= $file_lampiran3;
$data_service['file_registrasi']= $file_lampiran4;
$this->db->where('id_service',$this->input->post('id_service'));
$this->db->update('service_sis', $data_service);
This is my View
<div class="form-group">
<label for="">File NPWP</label>
<input type="file" name="file_npwp" id="file_npwp" class="form-control">
</div>
<br>
<div id="hasilloadfoto"></div>
<br>
<p>*Pastikan semua form sudah terisi dengan benar</p>
<button id="SaveAccount" class="btn btn-success">Simpan</button>
This is my Javascript in my view
$( function() {
var $signupForm = $( '#myForm' );
$signupForm.validate({errorElement: 'em'});
$signupForm.formToWizard({
submitButton: 'SaveAccount',
nextBtnName: 'Selanjutnya',
prevBtnName: 'Sebelumnya',
nextBtnClass: 'btn btn-primary btn-flat next',
prevBtnClass: 'btn btn-default btn-flat prev',
buttonTag: 'button',
validateBeforeNext: function(form, step) {
var stepIsValid = true;
var validator = form.validate();
$(':input', step).each( function(index) {
var xy = validator.element(this);
stepIsValid = stepIsValid && (typeof xy == 'undefined' || xy);
});
return stepIsValid;
},
progress: function (i, count) {
$('#progress-complete).width(''+(i/count*100)+'%');
}
});
});
function filePreview(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#hasilloadfoto + img').remove();
$('#hasilloadfoto').after('<img src="'+e.target.result+'" width="450" height="300"/>');
}
reader.readAsDataURL(input.files[0]);
}
}
$(document).ready(function(){
$("#file_npwp").change(functio () {
filePreview(this);
});
Need help in update operation. I appreciate any help.
you can do in two ways,
You can upload the image to any cloud storage(Aws, Azure, etc) then update the link on your Db
Convert the image into base64 and update it as the string on your DB.
I will prefer to go with step one, I have the sample where I have uploaded it to Azure and update my DB
// This is on Js , Using ajax , I will send to controller
function uploadImage() {
var base_url = '<?php echo BASEURL ?>';
// call ajax to upload image
//event.preventDefault();
var file_data = $('#post-image').prop('files')[0];
var form_data = new FormData();
form_data.append('uploaded_file', file_data);
$.ajax({
url: base_url + "dashboard/uploadImage",
dataType: 'json',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (aData) {
},
error: function (data) {
alert(data);
}
});
}
On Controller ,
public function uploadImage() {
// get the 'api-key' key from Request Headers
$data = array();
if (isset($_FILES ['uploaded_file']['name']) && !empty($_FILES ['uploaded_file']['name'])) {
$userId = $this->input->post("userId");
$file_name = $userId . "_" . uniqid() . ".jpg";
$S3ImgUrl = uploadImageToS3($_FILES ['uploaded_file']['tmp_name'], "app_feed_images", $file_name);
$data = array(
'code' => 555,
'message' => 'Image has been uploaded successfully',
'url' => $S3ImgUrl
);
} else {
$data['code'] = -111;
$msg = "failed to upload image to s3";
$data ['status'] = $this->failed_string;
}
// var_dump($data);
echo json_encode($data);
}
Helper Class
function uploadImageToS3($tmp, $bucket, $file_name) {
$connectionString = "DefaultEndpointsProtocol=https;AccountName=" . azure_bucket_name . ";AccountKey=" . azure_bucket_key;
$blobClient = MicrosoftAzure\Storage\Blob\BlobRestProxy::createBlobService($connectionString);
$containerName = "app-image/" . $bucket;
$containerUrl = "https://hbimg.blob.core.windows.net/";
$content = fopen($tmp, "r");
$options = new MicrosoftAzure\Storage\Blob\Models\CreateBlockBlobOptions();
$content_type = $_FILES['uploaded_file']['type'];
$options->setContentType($content_type);
$blobClient->createBlockBlob($containerName, $file_name, $content, $options);
return $containerUrl . $containerName . "/" . $file_name; }
On the controller side, I have just uploaded the image, you can call you model class with the uploaded image link and update on your DB.
Happy coding :)
All you need is to send the name of the photo in database right then in model you have to add
$this->input->post('databse_column_name')=$variable_name_which_content_file_name

Problem with uploading a image via Ajax Call in php?

I want to upload an image via Ajax call but I am not able to upload the image. Kindly check my code what I am doing wrong:
HTML File:
<input class="form-control" type="file" name="photo1" id="photo1" accept="image/*" onchange="loadFile2(event)">
<button type="button" class="btn btn-secondary btn-lg btn-block" onclick="createDocsVerify()">Update Details</button>
Ajax Call:
<script>
function createDocsVerify () {
var data = {
'photo1' : jQuery('#photo1').val(),
};
//Ajax call Start Here
jQuery.ajax({
url : '/myproject/adminseller/sellerdocsverify.php',
method : 'POST',
data : data,
success : function(data){
if (data != 'passed') {
jQuery('#modal_errors_3').html(data);
}
if (data == 'passed') {
jQuery('#modal_errors_3').html("");
location.reload();
}
},
error : function (){alert("Something went wrong.");},
});
}
</script>
Php File: sellerdocsverify.php
if (isset($_POST['photo1'])) {
$photo1 = sanitize($_POST['photo1']);
// var_dump Output: string(20) "C:\fakepath\0553.jpg"
}
$errors = array();
$required = array(
'photo1' => 'Please select Photo 1',
);
// check if all required fileds are fill out
foreach ($required as $field => $display) {
if (empty($_POST[$field]) || $_POST[$field] == '') {
$errors[] = $display.'.';
}
}
$allowed = array('png', 'jpg', 'jpeg', 'gif');
$photoNameArray = array();
$tmpLoc = array();
$uploadPath = array();
**// Here is the problem**
$name1 = $_FILES['photo1']['name']; // Here is the problem
Var_dump($name1); // OUTPUT: NULL
**// Here is the problem**
$nameArray = explode('.',$name1);
$fileName = $nameArray[0];
$fileExt = $nameArray[1];
$mime = $_FILES['photo1']['type'];
$mimeType = $mime[0];
$mimeExt = $mime[1];
$tmpLoc = $_FILES['photo1']['tmp_name'];
$fileSize = $_FILES['photo1']['size'];
$uploadName = md5(microtime().$j).'.'.$fileExt;
$uploadPath = BASEURL.'images/products/'.$uploadName;
if ($mimeType != 'image') {
$errors[] = 'The file must be an image.';
}
if (!empty($errors)) {
echo display_errors($errors);
}else{
echo 'passed';
// upload file and insert into database
if ($photoCount > 0) {
move_uploaded_file($tmpLoc1, $uploadPath1);
}
$insertSql = "INSERT INTO docTable (`photo1`)
VALUES ('$photo1')";
$db->query($insertSql);
$_SESSION['success_flash'] = '<span style="color:#FFFFFF;text-align:center;">Data Saved Successfully!</span>';
}
?>
Kind check my code and suggest what I am doing wrong, am I doing something wrong in Ajax call or in php, I am getting the value in $photo1.
Any idea or suggestion would be welcome.
You need to do some special "things" to upload files via AJAX. You need to create a FormData object and manually add the file data to it, and also set the contentType, processData and cache options of your AJAX call to false. Your javascript should look like this:
<script>
function createDocsVerify() {
var formdata = new FormData();
var file = jQuery('#photo1').prop('files')[0];
formdata.append('photo1', file);
//Ajax call Start Here
jQuery.ajax({
url: '/myproject/adminseller/sellerdocsverify.php',
method: 'POST',
cache: false,
contentType: false,
processData: false,
data: formdata,
success: function(data) {
if (data != 'passed') {
jQuery('#modal_errors_3').html(data);
}
if (data == 'passed') {
jQuery('#modal_errors_3').html("");
location.reload();
}
},
error: function() {
alert("Something went wrong.");
},
});
}
</script>
That should upload the photo.

Magento insert data into database through ajax

I'm new to ajax so I'm not sure if i'm approaching this correctly, basically I have a variable in javascript that need to be inserted into the database, this is what I have so far...
onInit: function() {
window.fcWidget.on('widget:loaded', function() {
window.fcWidget.user.get().then(function(resp) {
var status = resp && resp.status,
data = resp && resp.data;
if (status === 200) {
if (data.restoreId) {
// Update restoreId in database
$.ajax({
type: "POST",
url: "insert.php",
data: data.restoreId,
success: function(data) { alert("Success"); },
failure: function(data) { alert("Failure"); }
})
}
}
});
});
}
I have placed the file "insert.php" in the same folder but it seem like it doesn't get called at all...
This is what insert.php looks like
<?php
if(Mage::getSingleton('customer/session')->isLoggedIn()){
if(isset($_POST['data.restoreId']){
$restoreId =$_POST['data.restoreId'];
}
$first = Mage::getSingleton('customer/session')->getCustomer()->getFirstname();
$last = Mage::getSingleton('customer/session')->getCustomer()->getLastname();
$fullName = $first . "." . $last;
//get resource model
$resource = Mage::getSingleton('core/resource');
//retrieve write connection
$writeConnection = $resource->getConnection('core_write');
//read connection
$readConnection = $resource->getConnection('core_read');
$exId = $fullName;
$resId = $restoreId;
$testQuery = "SELECT `externalId` FROM `freshchat_user` WHERE `restoreId` = '$fullName'";
$result = $readConnection->fetchAll($testQuery);
if(count($result) == '0'){
$query = "INSERT INTO `freshchat_user`(`externalId`, `restoreId`) VALUES ('$exId','$resId')";
$writeConnection->query($query);
}else{
//echo "nope";
}
}
?>
I checked the network tab but insert.php doesn't seem to be called at all, what is wrong with my code?
//Please put your insert.php file in root path(Magento installation path) and change below line in your javascript code.
url: "www.yourwebsite.com/insert.php",

Codeigniter: Uploading image through Ajax and storing in db

I am using CI 3.0.1 was uploading and inserting image to db successfully before i used ajax, i guess trying to do it with ajax i'm missing something which isn't even sending data to upload maybe because we have to use multipart() in form while in ajax we are just sending data direct to controller, another thing i don't know how to receive the variable in response
my Ajax request function is:
<script type="text/javascript">
$(document).ready(function() {
alert("thirddddddddd");
$('#btnsubmit').click(function()
{
alert("i got submitted");
event.preventDefault();
var userfile = $("input#pfile").val();
alert("uploading");
$.ajax({
url: '<?php echo base_url(); ?>upload/do_upload', //how to receive var here ?
type: 'POST',
cache: false,
data: {userfile: userfile},
success: function(data) {
alert(data);
$('.img_pre').attr('src', "<?php echo base_url().'uploads/' ?>");
$('.dltbtn').hide();
},
error: function(data)
{
console.log("error");
console.log(data);
alert("Error :"+data);
}
});
});
});
And my controller Upload's function do_upload is:
public function do_upload()
{
$config['upload_path'] = './uploads/'; #$this->config->item('base_url').
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('userfile'))
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('layouts/header');
$this->load->view('home_page', $error);
$this->load->view('layouts/footer');
}
else
{
$data = array('upload_data' => $this->upload->data());
$imagedata = $this->input->post('uerfile');
$session_data = $this->session->userdata('logged_in');
$id = $session_data['id'];
$result = $this->model_edit->update_dp($id, $imagedata);
$image_name = $result->images;
$this->session->set_userdata('image', $image_name);
echo json_encode($name = array('image' => $image_name));
// $image_name = $this->upload->data('file_name');
// $data = array('upload_data' => $this->upload->data());
// redirect("account");
}
}
Now image is not even going to uploads folder, if any other file is needed tell me i'll post it here. Thanks
You cannot send file data using $("input#pfile").val();
var len = $("#pfile").files.length;
var file = new Array();
var formdata = new FormData();
for(i=0;i<len;i++)
{
file[i] = $("input#pfile").files[i];
formdata.append("file"+i, file[i]);
}
and send formdata as data from ajax
Hope it helps !
Try with the below ajax code
var formData = new FormData($('#formid'));
$.ajax({
url: '<?php echo base_url(); ?>upload/do_upload',
data: formData ,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
}
});
The file contents may not send through ajax as per your code. Try with the attributes mentioned in above code.

jQuery AJAX with PHP to upload contents to MYSQL DB

I am looking for a jQuery AJAX script alongside a PHP script that allows for the storage of information on a button click. The function defined within the jQuery should take three variables, all of which are defined pre-method call. I have the basis of operation complete but at the end of all operations - after the button is clicked and some time has passed - no data is added to the appropriate mysql database.
Here is my jQuery function "store"
<script type="text/javascript">
function store(ud, ld, tp) {
$.ajax({
url: 'http://www.exampledomain.com/folder/store.php',
type: 'POST',
data: 'ud='+ud+'&ld='+ld+'&tp='+tp
success : function() {
alert("WORKED!");
},
error : function() {
alert("DIDN'T WORK!");
},
complete : function() {
}
});
}
</script>
Here is the store.php file (very basic I know, I have also yet to secure this script via sanitizing user input)
<?php
require ('../mysqli_connect.php');
$errors = 0;
if(isset($_POST['ud']) && is_numeric($_POST['ud'])) {
$ud = $_POST['ud'];
} else {
++$errors;
}
if(isset($_POST['ld']) && is_numeric($_POST['ld'])) {
$ld = $_POST['ld'];
} else {
++$errors;
}
if(isset($_POST['tp'])) {
$tp = strip_tags(stripslashes($_POST['tp']));
} else {
++$errors;
}
if($errors == 0) {
$q = "INSERT INTO table_name (column_1, column_2, column_3, column_4) VALUES ('$ld', '$ud', NOW(), '$tp')";
mysqli_query($mysqli, $q);
} else {
echo 'There was a problem!';
}
?>
Assume that I have onclick="store(3, 3, A)" as an attribute for a certain element. How can I fix this? If I remove the onclick attribute how do I pass the necessary parameters to the jQuery function? I appreciate any and all help!
<-- EDIT -->
New jQuery & AJAX Script ...
<script type="text/javascript">
function store(ud, ld, tp) {
$.ajax({
url: 'http://www.exampledomain.com/folder/store.php',
type: 'POST',
data: 'ud='+ud+'&ld='+ld+'&tp='+tp,
error : function() {
alert("error");
},
success : function(data) {
alert(data);
},
complete : function() {
alert("complete");
}
});
}
$(function () {
$("a.rec").on("click", function () {
var $this = $(this),
ud = $this.data("ud"),
ld = $this.data("ld"),
tp = $this.data("tp");
store(ud, ld, tp);
});
});
</script>
Revised PHP
<?php
if($_SERVER['REQUEST_METHOD'] === "POST"){
require ('../mysqli_connect.php');
$errors = 0;
if(isset($_POST['ud'])) {
$ud = $_POST['ud'];
} else {
++$errors;
}
if(isset($_POST['ld'])) {
$ld = $_POST['ld'];
} else {
++$errors;
}
if(isset($_POST['tp'])) {
$tp = $_POST['tp'];
} else {
++$errors;
}
if($errors == 0) {
$q = "INSERT INTO table_name (column_1, column_2, column_3, column_4) VALUES ('$ld', '$ud', NOW(), '$tp')";
mysqli_query($mysqli, $q);
} else {
echo 'There was a problem!';
}
} else {
$url = 'http://www.exampledomain.com/error.php';
ob_end_clean();
header("Location: $url");
exit();
}
?>
Now for my HTML
<li>
<div class="sample classes">
<a class="rec" data-ud="13" data-ld="10" data-tp="SCI">
<input type="submit" title="Something" value="Something" />
</a>
</div>
</li>
However, when this button is clicked, it still does not do anything!
As you said onclick is something you are going to want to avoid. This is how you do it.
$(function () { //This function will be ran when the page loads
$(".button-class").on("click", function () { //This will run when any button is clicked
var $this = $(this),
ud = $this.data("ud"),
ld = $this.data("ld"),
tp = $this.data("tp");
store(ud, ld, tp);
});
});
HTML
<input type="button" class="button-class" data-ud="3" data-ld="3" data-tp="A"/>
I find it easier to use JSON and pass variables in an object to the server:
<script>
(function(){
var store = function (ud, lrid, type) {
var data = {
ud:ud,
lrid:lrid,
type:type
};
$.ajax({
url: 'http://www.exampledomain.com/folder/store.php',
type: 'POST',
data: data,
success : function(data) {
alert(data);
},
error : function() {
alert("DIDN'T WORK!");
},
complete : function() {
}
});
};
$('#btn').on('click', function(){
store(1,2,3);
});
}());
</script>
Use this script to test you are getting the variables on the server side:
<?php
# Put this in http://www.exampledomain.com/folder/store.php to test it works
if($_SERVER['REQUEST_METHOD'] === "POST"){
if(
isset($_POST['ud']) &&
isset($_POST['lrid']) &&
isset($_POST['type'])
)
{
$var = $_POST['ud'] . ", ".$_POST['ud'] . ", ".$_POST['type'] ." passed successfully via ajax!";
echo json_encode($var);
}
}
?>

Categories

Resources