I am using dropzone for file upload. I want to delete the files on the server when the removeLink is clicked. For that I use Ajax which opens the .php site. But somehow I can't pass the filename of the file which should be deleted (the delete_image.php works). How can I pass the filename so it can be deleted?
addRemoveLinks: true,
removedfile: function(file) {
$.ajax({
type: 'POST',
url: 'delete_image.php',
data: {name: +file, dir: "<? echo $_GET['id']; ?>"},
});
var _ref;
return (_ref = file.previewElement) != null ? _ref.parentNode.removeChild(file.previewElement) : void 0;
}
Credit: code from this site
Most simple way
JS file,this script will run when you click delete button
this.on("removedfile", function(file) {
alert(file.name);
$.ajax({
url: "uploads/delete.php",
type: "POST",
data: { 'name': file.name}
});
});
php file "delete.php"
<?php
$t= $_POST['name'];
echo $t;
unlink($t);
?>
Related
I have this ajax post to the server to send some data to an SQL db :
$.ajax({
method: "POST",
url: "https://www.example.com/main/public/actions.php",
data: {
name: person.name,
age: person.age,
height: person.height,
weight: person.weight
},
success: function (response) {
console.log(response)
}
})
in the server i get this data with php like this :
<?php
include "config.php";
if(isset ( $_REQUEST["name"] ) ) {
$name = $_REQUEST["name"];
$age = $_REQUEST["age"];
$height = $_REQUEST["height"];
$weight = $_REQUEST["weight"];
$sql = "INSERT INTO persons ( name, age, height, weight )
VALUES ( '$name', '$age', '$height', '$weight' )";
if ($conn->query($sql) === TRUE) {
echo "New person stored succesfully !";
exit;
}else {
echo "Error: " . $sql . "<br>" . $conn->error;
exit;
}
};
?>
I also have this input :
<input id="myFileInput" type="file" accept="image/*">
and in the same directory as actions.php i have the folder /images
How can i include an image ( from #myFileInput ) in this ajax post and save it to the server using the same query in php ?
I have searched solutions in SO but most of them are >10 years old,i was wondering if there is a simple and modern method to do it,i'm open to learn and use the fetch api if its the best practice.
You should use the formData API to send your file (https://developer.mozilla.org/fr/docs/Web/API/FormData/FormData)
I think what you are looking for is something like that:
var file_data = $('#myFileInput').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'https://www.example.com/main/public/actions.php',
contentType: false,
processData: false, // Important to keep file as is
data: form_data,
type: 'POST',
success: function(php_script_response){
console.log(response);
}
});
jQuery ajax wrapper has a parameter to avoid content processing which is important for file upload.
On the server side, a vrey simple handler for files could look like this:
<?php
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'];
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}
?>
via ajax FormData you can send it . refer here . Note : data: new FormData(this) - This sends the entire form data (incldues file and input box data)
URL : https://www.cloudways.com/blog/the-basics-of-file-upload-in-php/
$(document).ready(function(e) {
$("#form").on('submit', (function(e) {
e.preventDefault();
$.ajax({
url: "ajaxupload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
beforeSend: function() {
//$("#preview").fadeOut();
$("#err").fadeOut();
},
success: function(data) {
if (data == 'invalid') {
// invalid file format.
$("#err").html("Invalid File !").fadeIn();
} else {
// view uploaded file.
$("#preview").html(data).fadeIn();
$("#form")[0].reset();
}
},
error: function(e) {
$("#err").html(e).fadeIn();
}
});
}));
});
If you are not averse to using the fetch api then you might be able to send the textual data and your file like this:
let file=document.querySelector('#myFileInput').files[0];
let fd=new FormData();
fd.set('name',person.name);
fd.set('age',person.age);
fd.set('height',person.height);
fd.set('weight',person.weight);
fd.set('file', file, file.name );
let args={// edit as appropriate for domain and whether to send cookies
body:fd,
mode:'same-origin',
method:'post',
credentials:'same-origin'
};
let url='https://www.example.com/main/public/actions.php';
let oReq=new Request( url, args );
fetch( oReq )
.then( r=>r.text() )
.then( text=>{
console.log(text)
});
And on the PHP side you should use a prepared statement to mitigate SQL injection and should be able to access the uploaded file like so:
<?php
if( isset(
$_POST['name'],
$_POST['age'],
$_POST['height'],
$_POST['weight'],
$_FILES['file']
)) {
include 'config.php';
$name = $_POST['name'];
$age = $_POST['age'];
$height = $_POST['height'];
$weight = $_POST['weight'];
$obj=(object)$_FILES['file'];
$name=$obj->name;
$tmp=$obj->tmp_name;
move_uploaded_file($tmp,'/path/to/folder/'.$name );
#add file name to db????
$sql = 'INSERT INTO `persons` ( `name`, `age`, `height`, `weight` ) VALUES ( ?,?,?,? )';
$stmt=$conn->prepare($sql);
$stmt->bind_param('ssss',$name,$age,$height,$weight);
$stmt->execute();
$rows=$stmt->affected_rows;
$stmt->close();
$conn->close();
exit( $rows ? 'New person stored succesfully!' : 'Bogus...');
};
?>
I'm beginner in OpenCart and I'm trying to upload the file in server using PHP. I have done the following code. My problem is, files are sucessfully uploading in server but if there is some error I'm trying to loading the LoadA() function, but the result is not showing in site instead it is showing in console.log I don't know what is the error.
controller/boxupload/upload.php
public function add()
{
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file))
{
if(success) //files are succesfully uploading
{
//doing stuff
}
if (it is fail)
{
$this->LoadA(); // this is not loading in site. Instead it is showing in console.log
}
}
}
public function LoadA()
{
$data['token'] = $this->session->data['token'];
$this->document->setTitle("!!!!!!!!!!!!Upload failed!!!!!!!!");
$data['add'] = $this->url->link('boxupload/upload/add', 'token=' . $this->session->data['token'], 'SSL');
$data['header'] = $this->load->controller('common/header');
$data['column_left'] = $this->load->controller('common/column_left');
$data['footer'] = $this->load->controller('common/footer');
$this->response->setOutput($this->load->view('boxupload/upload.tpl', $data));
}
Then the tpl file for this one
controller/boxupload/upload.tpl
$('#button-upload').on('click', function() {
$('#progress-bar').css('width', '0%');
$('#form-upload').remove();
$('body').prepend('<form enctype="multipart/form-data" id="form-upload" style="display: none;"><input type="file" name="file" /></form>');
$('#form-upload input[name=\'file\']').trigger('click');
if (typeof timer != 'undefined') {
clearInterval(timer);
}
var WID = 30;
timer = setInterval(function() {
if ($('#form-upload input[name=\'file\']').val() != '') {
clearInterval(timer);
// Reset everything
$('.alert').remove();
$('#progress-bar').css('width', '0%');
$('#progress-bar').removeClass('progress-bar-danger progress-bar-success');
$('#progress-text').html('');
$.ajax({
url: '<?php echo "index.php?route=boxupload/upload/add&token=$token"; ?>',
type: 'post',
//dataType: 'json',
data: new FormData($('#form-upload')[0]),
cache: false,
contentType: false,
processData: false,
beforeSend: function() {
$('#button-upload').button('loading');
$('#progress-bar').css('width', '50%');
},
complete: function() {
$('#button-upload').button('reset');
$('#progress-bar').css('width', '100%');
},
success: function()
{ $('#progress-bar').css('width', '80%');
},
});
}
}, 500);
});
Please see the highlighted area in image.
Try this:
dataType: 'html',
success: function(html)
{
$('#progress-bar').css('width', '80%');
$('#your-div').html(html);
},
Your .tpl file should be in a view.
$this->response->setOutput($this->load->view('boxupload/upload.tpl', $data));
loads the file
view/theme/default/template/boxupload/upload.tpl
Also, look at some other template files. They're generally mostly HTML.
Also, you're going to want to refactor your names so they use normal OpenCart naming conventions.
controller/extension/boxupload/upload.php
view/theme/default/template/extension/boxupload/upload.tpl
etc.
I am building a news page for my website but I'm stuck displaying the right comments with ajax...
commentsLoad.php
<?php
include('config.php');
$newsid = $_GET['newsid'];
$comments=array();
$commentsQuery = "SELECT * FROM comments
where fk_news like ".$newsid;
$result = $conn->query($commentsQuery);
if($result->num_rows>0){
while($row = $result->fetch_assoc()){
$comments[]=array('id' => $row['id'], 'name' => $row['cnick'], 'text' => $row['ctext'], 'date' => $row['cdate']);
}
}
//header('Content-type: application/json');
echo json_encode($comments);
exit;
?>
I dont know how to pass the right 'NEWSID'.
Website picture: http://prntscr.com/8nwy8k
How I want to pass that ID to the SQL Query
$.ajax({
type: 'GET',
url: commentsUrl,
dataType: "json",
data:{newsid:'1'},
success: function(comments){
//console.log(komentarji);
$.each(comments, function(i, komentar){
addComment(komentar);
})
},
error: function(e){
console.log(e);
}
});
So right now if I change the line data:{newsid:'1 or 2 or 3...'} I get the comments I want, but I dont know how to get that ID into a variable.
You can use onClick event for this.
Explanation:
Comment link will look as follows
Comments
Then you can have a fucntion in your JQuery code to pass it to PHP file.
function getComments(article_id)
{
var artid = article_id;
$.ajax({
type: 'POST',
url: commentsUrl,
dataType: "json",
data:{newsid: artid},
success: function(comments){
$.each(comments, function(i, komentar){
addComment(komentar);
})
},
error: function(e){
console.log(e);
}
});
}
Try set onclick function in the comment link.
<a href="javascript:void(0)" onclick='myfunction <?php echo newsid ?>'Comment</a>
Get the newsid form the link.
<script>
function myfunction(newsid){
$.ajax({
type: 'GET',
url: commentsUrl,
dataType: "json",
data:{newsid:newsid},
success: function(comments){
//console.log(komentarji);
$.each(comments, function(i, komentar){
addComment(komentar);
})
},
error: function(e){
console.log(e);
}
});
}
</script>
Get the newid from commenntsUrl page.
I newbie in this webpage area and I was try to upload image to my file by using ajax and send it to php. But I have done some coding here. Can some one correct me where I'am wrong ?
here is my form with file upload and a button
<form method="post" enctype="multipart/form-data" action="">
<input type="file" name="images" id="images" multiple="" />
<input type="submit" value="submit" id="harlo">
</form>
Once I click on button the file will send it here and receive the src and ajax to php file
but I guess is about getting source problem. Need some one correct it for me.
(function upload() {
var input2 = document.getElementById("harlo"),
formdata = false;
if (window.FormData) {
formdata = new FormData();
}
input2.addEventListener("click", function () {
var i = 0, len = $('input[type="file"]')[0].files;
for ( ; i < len.length; i++ ) {
file = len.files[i];
if (formdata) {
formdata.append("images", file);
}
}
if (formdata) {
$.ajax({
url: "upload.php",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (res) {
document.getElementById("response").innerHTML = res;
}
});
}
}, false);
}());
<?php
foreach ($_FILES["images"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$name = $_FILES["images"]["name"][$key];
move_uploaded_file( $_FILES["images"]["tmp_name"][$key], "uploads/" . $_FILES['images']['name'][$key]);
}
}
echo "<h2>Successfully Uploaded Images</h2>";
?>
Use something like:
$("form").on("submit", function(
// Your ajax request goes here
$.ajax({
url: "upload.php",
type: "POST",
data: $("form").serialize(),
processData: false,
contentType: false,
success: function (res) {
$("#response").innerHTML = res;
}
});
return false;
));
But there seems to be a problem with sending files trough ajax anyway. Cause they're missed by the serialize() method because JS has no access to files content on users computer. So the form must be sent to the server to get the file data.
See here: https://stackoverflow.com/a/4545089/1652031
I do believe am over-complicating this, but I have a jQuery modal that talks with a PHP file. The file has all the form and validation, but it's included in the modal. The event is triggered on right-click (so a user right clicks the folder to edit, selects "Edit", the action below triggers. It's supposed to send the folder id to the modal, so the modal displays the edit form with the correct folder. Right now, it doesn't send anything.)
So I have the jquery (script.js):
"action": function(obj) {
var data = {'pid': obj.attr("id")};
$.post("/folder/edit.php", data, function (response) {
$('#modalEditFolder').modal('show');
});
}
// also tried this:
$.post("/folder/edit.php", data, function (response) {
$('#modalEditFolder').data('pid', obj.attr("id")).modal('show');
});
// and this
$.ajax({
type: "POST",
url: "/view/folder/edit.php",
data: {pid: obj.attr("id")},
success: function(html) {
$('body').append(html);
$('#modalEditFolder').modal('show');
}
});
The modal (modal.php):
<div class="modal-body">
<?php include_once("/folder/edit.php"); ?>
</div>
The PHP file (edit.php):
<?php echo $_POST['pid']; ?>
How can I get both the modal and php form to get the PID variable?
try this :
$.ajax({
type: "POST",
url: "/view/folder/edit.php",
cache: false,
data: {'pid': obj.attr("id")}
}).done(function(html) {
$('body').append(html);
$('#modalEditFolder').modal('show');
});