I want to delete files from a directory using check-box for selecting files and button event for deleting selected ones.
so basically I want it looks like this:
the problem, I retrieve the files via php but I put this checkbox via jquery
and I dont know how to relate these elements with each other
How can I delete these selected files?
My code is down here:
$dir = 'C:\directory\of\files\here';
$files1 = scandir($dir);
$cnt = count($files1);
//var_dump($cnt);
echo "<h1><u> delete files from directory </u></h1>";
echo "<div class='container'>";
for($n=0; $n< $cnt; $n++)
{
if ( ($files1[$n])!= '.' && $files1[$n] != '..')
{
print_r("<input type='checkbox' />".($files1[$n])."<br/> ");
}
}
echo "</br>";
echo " <button>DELETE</button>";
echo "</div>";
?>
<html>
<head>
<script>
$(function() {
$( "input[type=submit], a, button" )
.button()
.click(function( event ) {
event.preventDefault();
});
</script>
</head>
<body>
</body>
</html>
Here is your main file
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8/>
<title>delete</title>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.js"></script>
</head>
<body>
<form id="myform">
<?php
$filesss = array_diff(scandir(__DIR__), array('..', '.'));
foreach ($filesss as $file) {
echo "<label>";
echo "<input type='checkbox' name='file[]' value='$file'>";
echo "$file </label><br>";
}
?>
<button type="submit">delete</button>
</form>
<script>
$(document).ready(function () {
$("#myform").submit(function (event) {
$.ajax({
type: 'POST',
url: 'delete.php',
data: $(this).serialize(),
success: function () {
alert("success");
}
});
event.preventDefault();
});
});
</script>
</body>
</html>
and your delete file
<?php
foreach ($_POST['file'] as $file) {
if (file_exists($file)) {
unlink($file);
}
}
Basically what you do with this code is that you collect file paths from the page and you send via ajax to delete.php what deletes the files (with unlink).
But ALWAYS use form and input validation especially when you want do delete files!
You'll need to set a <form> tag, which creates a form.
Then you'll need to set a name and value to the checkboxes.
Last but not least, when the form is submitted, PHP checks if $_POST['filenames'] is set, if yes, it loops the array and deletes all the files that are selected.
<?php
$dir = 'C:\directory\of\files\here';
if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
if( isset( $_POST['filesnames'] ) ) {
foreach( $_POST['filesnames'] as $key => $file ) {
unlink( $dir . '\\' . $file );
}
echo 'Files deleted';
}
else {
echo 'No files selected';
}
}
$files1 = scandir($dir);
$cnt = count($files1);
//var_dump($cnt);
echo "<h1><u> delete files from directory </u></h1>";
echo "<div class='container'>";
echo "<form action='".$_SERVER['PHP_SELF']."' method='post'>";
for($n=0; $n< $cnt; $n++)
{
if ( ($files1[$n])!= '.' && $files1[$n] != '..')
{
print_r("<input name='filesnames[]' value='".($files1[$n])."' type='checkbox' />".($files1[$n])."<br/> ");
}
}
echo "</br>";
echo " <submit>DELETE</submit>";
echo "</form>";
echo "</div>";
?>
you can do something like this
<?php
$dir = 'C:\directory\of\files\here';
if($_SERVER['REQUEST_METHOD'] == 'POST') {
foreach($_POST['files'] as $file) {
$file = addslashes($file);
if(is_readable($file)) {
unlink($file);
}
}
} else {
$files = scandir($dir);
}
?>
<html>
<head>
<script>
$(document).ready(function() {
$('#deleteFiles').on('submit', function(e) {
e.preventDefault();
$.ajax({
url: location.href,
}).done(function() {
alert('Done !!!');
});
})
});
</head>
<body>
<h1><u> delete files from directory </u></h1>
<div class="container">
<form action="#" method="post" id="deleteFiles">
<?php foreach($files as $file): ?>
<?php if($file === '.' || $file === '..') { continue; } ?>
<lable>
<input type="checkbox" name="files[]" value="<?php echo $file; ?>">
$<?php echo $file; ?>
</lable>
<?php endforeach; ?>
<input type="submit" value="Delete">
</form>
</body>
</html>
Related
I have this code that deletes a student record from the database, it deletes the student information as well as where an image is stored on the server however, I also want it to delete the image file itself, not just the record. How can I do this.
This code is where the user clicks to delete the student.
<a href="javascript:void();" onclick="deleteItem
(<?php echo $student_row->id;?>,<?php echo $_REQUEST['regNumber'];?>,
<?php echo $student_row->id;?>,'parent')">Delete</a>
This code is the JS code referenced above:
function deleteItem(registration_number,parent_id,id,type)
{
var parent_id = "<?php echo $_REQUEST['regNumber'];?>";
var url_pass="<?php echo get_site_url();?>/student-delete/?
regNoIndivid="+registration_number+
"&parentId="+parent_id+"&id="+id+"&type="+type;
if (confirm("Are you sure?")) {
window.location.href = url_pass;
}
return false;
}
This is from student-delete:
if($_REQUEST['type'] == "teacher")
{
$where=array("id"=>$_REQUEST['id']);
//echo "<pre>";print_r($where);echo "</pre>";
//$delete_row=$wpdb->delete('wp_new_student_user', $where);
$delete_row = $wpdb->query('DELETE FROM wp_new_student_user WHERE id
='.$_REQUEST['id']);
$wpdb->show_errors();
if($delete_row)
{
$url_location=get_site_url()."/my-account-teacher/?
regNumber=".$_REQUEST['parentId']."&type=tea&back_list=yes";
?>
<script type="text/javascript">
window.location.href="<?php echo $url_location;?>";
</script>
<?php
}
}
elseif ($_REQUEST['type'] == "parent") {
$where=array("id"=>$_REQUEST['id']);
//echo "<pre>";print_r($where);echo "</pre>";
//$delete_row=$wpdb->delete('wp_new_student_user', $where);
$delete_row = $wpdb->query('DELETE FROM wp_new_student_user WHERE id
='.$_REQUEST['id']);
$wpdb->show_errors();
if($delete_row)
{
$url_location=get_site_url()."/my-account-parent/?
regNumber=".$_REQUEST['parentId']."&type=par&back_list=yes";
?>
<script type="text/javascript">
window.location.href="<?php echo $url_location;?>";
</script>
<?php
}
}
Please use PHP UNLINK function to delete the file
if($delete_row)
{
unlink(Path to the file);
}
I want when I add a product to the cart and reload the same page, but the problem did not this product.
The controller
public function detail()
{
$data=array('title' =>'Ecommerce Online | Detail Product',
'username' => $this->session->userdata('id'),
'categories' => $this->categories_model->get_categories(),
'details' => $this->categories_model->get_details($this->uri->segment(3)),
'isi' =>'member/detail');
$this->load->view('template_home/wrapper',$data);
}
function addtocart()
{
if($this->cart_model->validate_add_cart_item() == TRUE){
if($this->input->post('ajax') != '1'){
redirect('member/detail/'); // this problem
}else{
echo 'true';
}
}
}
I add my models
function validate_add_cart_item()
{
$id = $this->input->post('product_id');
$cty = $this->input->post('quantity');
$this->db->where('productID', $id);
$query = $this->db->get('product', 1);
if($query->num_rows > 0){
foreach ($query->result() as $row)
{
$data = array(
'id' => $id,
'qty' => $cty,
'price' => $row->price,
'name' => $row->productName
);
$this->cart->insert($data);
return TRUE;
}
}else{
return FALSE;
}
}
I add my view
<?php foreach ($details as $s) { ?>
<div class="col-md-5">
<div class="box text-center">
<img src="<?php echo base_url('upload/'.$s->photo); ?>" width="150px" height="150px">
<br><?php echo $s->productName; ?>
<br><strong>Rp. <?php echo $s->price; ?></strong>
<br>
<?php echo form_open('member/add'); ?>
<fieldset>
<label>Quantity</label>
<?php echo form_input('quantity', '1', 'maxlength="2"'); ?>
<?php echo form_hidden('product_id', $s->productID); ?>
<?php echo form_submit('add', 'Add'); ?>
</fieldset>
<?php echo form_close(); ?>
</div>
</div>
<?php } ?>
Jquery script
<script type="text/javascript">
$(document).ready(function() {
/*place jQuery actions here*/
var link = "<?php echo site_url('member/detail')?>/"; // Url to your application (including index.php/)
$(".detail-product").submit(function(){
var id = $(this).find('input[name=product_id]').val();
var qty = $(this).find('input[name=quantity]').val();
$.post(link + "member/add", { product_id: id, quantity: qty, ajax: '1' },
function(data){
if(data == 'true'){
$.get(link + "member/detail", function(cart){ // Get the contents of the url cart/show_cart
$("#cart_content").html(cart); // Replace the information in the div #cart_content with the retrieved data
});
}else{
alert("Product does not exist");
});
return false; // Stop the browser of loading the page defined
});
});
</script>
This is problem url: http://localhost/scientificwriting/member/detail/ and productid can not be invoked. Do I need to replace the IF statement on my controller and my jquery?
Please help me thanks
I got the plugin from the net and made some required changes. But I think PHP is not responding.
exp1.html code
<html>
<head>
<meta charset="UTF-8">
<title>AutoSuggestion using Ajax, Jquery and PHP</title>
<link rel="stylesheet" href="exp1.css">
</head>
<body>
<div class="serch-wrap">
<div class="form-wrapper cf">
<input type="text" class="abhijitscript" name="search_word">
<input type="submit" value="Search">
</div>
<div class="autodropdown">
<ul class="suggestresult"></ul>
</div>
</div>
</body>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="exp1.js"></script>
</html>
exp1.php
<?php
$host="localhost";
$user="root";
$password="jatin";
$link=mysqli_connect($host,$user,$password);
if(#mysqli_select_db($link,'books')){
// echo "Database connected..<br>";
}
else
echo mysqli_connect_error();
if(isset($_POST['name']))
{
$name = mysqli_real_escape_string($link,trim($_POST['name']));
$sql = "SELECT `name` FROM `books` WHERE `name` LIKE 'l%'";
$myquery = mysqli_query($link,$sql) or die(mysql_error());
if(mysqli_num_rows($myquery) !=0)
{
while(($row = mysqli_fetch_array($myquery)) !== false)
{
echo '<li>'.$row['name'].'</li>';
}
}
else
{
echo '<li>Not Found</li>';
}
} else{
echo "not set!";
}
?>
exp1.js
$(document).ready(function(){
$('.abhijitscript').keyup(function(){
var query_string = $(this).val();
$.ajax({
type: "POST",
url: "exp1.php",
data: { name:query_string },
success: function(data)
{ console.log(data);
$('.suggestresult').html(data);
$('.suggestresult li').click(function(){
var return_value = $(this).text();
$('.abhijitscript').attr('value', return_value);
$('.abhijitscript').val(return_value);
$('.suggestresult').html('');
});
}
});
});
});
Console also not showing any error, which points to some mistake in php code. I have provided complete code. Thank you!
I edited your code a bit and it is working fine for me now.
<?php
$host="localhost";
$user="root";
$password="jatin";
$link=#mysqli_connect($host,$user,$password);
if( !$link || !#mysqli_select_db($link,'books')){
echo mysqli_connect_error();
exit ;
}
if(isset($_POST['name'])) {
$name = mysqli_real_escape_string($link,trim($_POST['name']));
$sql = "SELECT DISTINCT(`name`) FROM `books` WHERE `name` LIKE '%{$name}%'";
$myquery = mysqli_query($link,$sql) or die(mysql_error());
if(mysqli_num_rows($myquery) !=0) {
while(($row = mysqli_fetch_array($myquery)) !== NULL) {
echo '<li>'.$row['name'].'</li>';
}
} else {
echo '<li>Not Found</li>';
}
} else {
echo "not set!";
}
?>
As I wrote in the title I have this part of code in page page.php that is in a subfolder admin. So the path of page is ../admin/page.php:
<select name="my_select" id="my_select" onchange="function(this.value);">
<?php
include "../db/db_config.php";
$conn = mysql_connect($host,$user,$password)or die(mysql_error());
mysql_select_db($db, $conn);
$query="Query";
$res=mysql_query($query,$conn);
while($row=mysql_fetch_array($res)){
$id=$row['id'];
$text=$row['text'];
echo "<option value='$id'>$text</option>";
}
}
?>
</select>
$var = $_POST['my_select'];
echo "I have selected $var";
I use a function that I have found on internet:
function fetch_select(val)
{
$.ajax({
type: 'post',
url: 'page.php',
data: {
get_option:val
},
success: function (response) {
document.getElementById("my_select").innerHTML=response;
}
});
}
What I have to do to take value in $var? Because I need this value to build other things. Is it possible?
EDIT:
Probably I don't explain very well my problem. I don't have very good with ajax because I never use it. I have a deadline so I can't study it now.
Now I have this situation:
I have a select-form with an input submit. After click on the button I use $_POST['myoption'] and I get the value.
Then I do it:
if($var == 1)
//a query from database
else if($var == 2)
//another different query
else
//other but no query
This work correctely. I need to change it and use in the same page. How can I do the same?
You don't to do a POST to do this you can do it with jQuery.
<?php
include "../db/db_config.php";
$conn = mysql_connect($host,$user,$password)or die(mysql_error());
mysql_select_db($db, $conn);
$query="Query";
$res=mysql_query($query,$conn);
?>
<select name="my_select" id="my_select">
<?php
while($row=mysql_fetch_array($res)){
$id=$row['id'];
$text=$row['text'];
echo "<option value='$id'>$text</option>";
}
?>
</select>
<span id="selected"></span>
<script>
$("#my_select").change(function() {
$("#selected").html($("#my_select option:selected").text());
});
</script>
This will give the select value to PHP:
<?php
include "../db/db_config.php";
$conn = mysql_connect($host,$user,$password)or die(mysql_error());
mysql_select_db($db, $conn);
$query="Query";
$res=mysql_query($query,$conn);
if (isset($_POST['my_select'])) {
$var = $_POST['my_select'];
} else {
$var = '';
}
?>
<form id="my_form" action="" method="POST">
<select name="my_select" id="my_select">
<?php
while($row=mysql_fetch_array($res)){
$id=$row['id'];
$text=$row['text'];
echo "<option value='$id'>$text</option>";
}
?>
</select>
</form>
<span id="selected">I have selected <?php echo $var; ?></span>
<script>
$("#my_select").change(function() {
$('#my_form').submit();
});
</script>
Hi i have a simple form and implemented an ajax script. My question is how to display the echo messages form the other php file which is user-file-upload.php?
I would also like to ask if i am doing ajax the right way. I am a total noob right now in ajax. Hope you could help me in the right direction. Thanks
Here is my form
echo "<form action='portal-files/user-file-upload.php' method='post' enctype='multipart/form-data' id='test_ajax'>";
echo "<input type='hidden' name='MAX_FILE_SIZE' value='100000' />";
echo "<input type='hidden' name='admin_id' value='$user->id' />";
echo "<select name='id' id='form-option' class='test-only'>";
echo '<option selected="selected">' .'Choose a User'. '</option>';
foreach ($registeredUsers as $key => $value) {
$registered = JFactory::getUser($value);
echo '<option value="'.$registered->id.'">'.$registered->name.'</option>';
}
echo "</select>";
echo "<input name='uploadedfile' type='file' id='custom-file-input' class='test-only' /> <br/>";
echo '<input type="submit" name="submit" value="Upload" id="custom-submit-input" disabled="disabled" >';
echo '<span id="display_file"></span>';
echo '<span id="display_user" style="visibility:hidden"></span>';
echo "</form>";
Here is the user-file-upload.php
<script src="https://cdn.rawgit.com/t4t5/sweetalert/master/dist/sweetalert.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.rawgit.com/t4t5/sweetalert/master/dist/sweetalert.css">
<?php
define( '_JEXEC', 1 );
define( 'DS', DIRECTORY_SEPARATOR );
define( 'JPATH_BASE', realpath(dirname(__FILE__).DS.'..' ));
require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );
$target_dir = "../portal-files/";
$target_file = $target_dir . basename($_FILES["uploadedfile"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["uploadedfile"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "doc" && $imageFileType != "docx" && $imageFileType != "xlsx") {
echo "Sorry, only DOC, DOCX, XLXS.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["uploadedfile"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["uploadedfile"]["name"]). " has been uploaded.";
if(isset($_POST['id']))
{
$selectedValue = $_POST['id'];
$adminabc = $_POST['admin_id'];
$imageFileName = basename( $_FILES["uploadedfile"]["name"]);
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query = "INSERT INTO joom_fss_user_files (user_id,admin_id) VALUES ($selectedValue,$adminabc)";
$db->setQuery($query);
$result = $db->execute();
$db = JFactory::getDbo();
$query_user = $db->getQuery(true);
$query_user = "INSERT INTO joom_fss_files (user_id,admin_id,file_type,file_name,path_url) VALUES ($selectedValue,$adminabc,'$imageFileType','$imageFileName', '$target_file')";
$db->setQuery($query_user);
$result = $db->execute();
sweetAlert("You have successfuly uploaded a file.");
}
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
Here is my jquery script
<script src="http://malsup.github.com/jquery.form.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
jQuery(document).ready(function() {
jQuery('#test_ajax').ajaxForm(function() {
e.preventDefault();
});
});
</script>
I think you should use this way, response is everything that you echo in .php page.
$("#test_ajax").ajaxForm({
success: function(response, textStatus, xhr, form) {
alert(response); //alert
$('#some-container').html(response); //show in html element
},
error: function(xhr, textStatus, errorThrown) {
console.log("in ajaxForm error");
},
complete: function(xhr, textStatus) {
console.log("in ajaxForm complete");
}
});