Deleting a file with ajax javascript and php - javascript

I am creating a page where you can upload files and delete them.
My upload is working fine and my download also.
But i cant get my delete working, i want to have the delete using AJAX and a possible confirm box but when i click my button now it doesnt do anything.
The formatoverzicht.php and ajax.php are in the main folder and the files that need to be deleted are in a uploads folder in side the main folder.
Here is my code.
Formatoverzicht.php
<script src="/website/libraries/jquery.js"></script>
<script type="text/javascript">
$('.delete-btn').click(function(filename) {
$.ajax({
type: 'POST',
url: 'ajax.php',
data: { filename: filename },
success: function(data) {
if(data == 'success') {
$this = $(this).closest('tr');
$this.remove();
}
}
});
});
</script>
The Button:
<button data-file="<?php echo $file ?>" class="delete-btn">Delete</button>
Ajax.php:
<?php
if (isset($_POST['filename'])) {
if (unlink(htmlentities( $_POST['filename']))) {
echo "success";
}
}
?>
I am trying to get this fixed for a couple of days now but it still doesnt work.
EDIT:
I am not using this code:
<script src="/website/libraries/jquery.js"></script>
<script type="text/javascript">
$( document ).ready(function() {
$('.delete-btn').on('click',function() {
filename=$(this).attr('data-file');
$.ajax({
type: 'POST',
url: 'ajax.php',
data: { 'filename': filename },
success: function(data) {
if(data == 'success') {
$this = $(this).closest('tr');
$this.remove();
}
}
});
})
});
</script>
and i now get: event.returnValue is deprecated. Please use the standard event.preventDefault() instead. as an error. But the code still doesnt delete or do anything.

It is because filename is totally undefined. You should use something like this:
<script type="text/javascript">
$('.delete-btn').click(function() {
var filename = $(this).attr('data-file');
$.ajax({
type: 'POST',
url: 'ajax.php',
data: { 'filename' : filename },
success: function(data) {
if(data == 'success') {
$this = $(this).closest('tr');
$this.remove();
}
}
});
});
</script>

Shouldn't
$('.delete-btn').click(function(filename)
be:
$('.delete-btn').click(function(file) ?
Or retrieve the filename inside the anonymous function like:
$(this).attr('data-file'); ?

<script type="text/javascript">
$('.delete-btn').on('click',function() {
filename=$(this).attr('data-file');
$.ajax({
type: 'POST',
url: 'ajax.php',
data: { filename: filename },
success: function(data) {
if(data == 'success') {
$this = $(this).closest('tr');
$this.remove();
}
}
});
});
</script>
try doing it on('click'), also your filename is not passed to function.

Try this,
HTML:
<button data-file="<?php echo base64_encode($file); ?>" class="delete-btn">Delete</button>
ajax.php
<?php
if (isset($_POST['filename'])) {
$file = base64_decode($_POST['filename']);
if(is_file($file)){
if (unlink($file)) {
echo "success";
}
}else{
echo "there is no file found (". $file.")";
}
}
?>

Your button click is not handled because the javascript is not triggered. You need to wrap your javascript in jQuery 'ready()' statement, like so:
$( document ).ready(function() {
// your stuff
});
Then you should set your filename variable, as suggested by the others, like so:
filename=$(this).attr('data-file');
instead of passing it directly to the function...
Also, check that the filename that is send to ajax.php matches the original filename. The path should also match off course, since deleting is a filesystem action. Either use the full system path when deleting (or a relative path) or make sure that ajax.php is inside the same directory as the file you want to delete

Related

Why is my jquery/ajax post not registering in my php code?

So I am trying to build a single page application using PHP and AJAX but I am having some issues with my navigation.
I have a file controller.php that controls the page to be displayed. The code that handles a post request is as follows
EDIT: Forgot to mention that echoing $_POST['page'] shows nothing
if(!isset($_POST['page'])){
include('Pages/landing_page.php');
echo "empty";
}
else{
echo $_POST['page'];
if($_POST['page'] == 'landing_page'){
include('Pages/landing_page.php');
}
if($_POST['page'] == 'forum'){
include('Pages/forum.php');
echo "forum hit";
}
}
The post request is generated with $.ajax function as follows
$(document).ready(function(){
$("#home_link").on('click', ()=>{
alert("Working");
$.ajax({
type: "POST",
url: "controller.php",
data: "page=landing_page"
});
});
$('#forum_link').on('click', ()=>{
$.ajax({
type: "POST",
url: "controller.php",
data: "page=forum",
success: function(){
alert("Callback Works");
}
});
});
});
I know the jquery click is working because I get the original "Working" alert as well as the callback alert if I click on the forum link.
I am using the Netbeans built in PHP development server but I have also tested it on a proper apache2 server that is well configured for PHP and AJAX.
Any help would be appreciated, thanks!
As I understand the question, this should work:
PHP: (all the same)
if(!isset($_POST['page'])){
include('Pages/landing_page.php');
echo "empty";
}
else{
echo $_POST['page'];
if($_POST['page'] == 'landing_page'){
include('Pages/landing_page.php');
}
if($_POST['page'] == 'forum'){
include('Pages/forum.php');
echo "forum hit";
}
}
JS:
$(document).ready(function(){
$("#home_link").on('click', ()=>{
alert("Working");
$.ajax({
type: "POST",
url: "controller.php",
data: "page=landing_page"
});
});
$('#forum_link').on('click', ()=>{
$.ajax({
type: "POST",
url: "controller.php",
data: "page=forum",
success: function(data){
$("#container").html(data);
alert("Callback Works");
}
});
});
});
You need to take the data returned from the function and put it somewhere, presumably into a container element.
If this isn't what you are trying to do, please comment.

delete mysql using button and ajax

I want to delete files in my database instantly when I press a button. Files were deleted but I am obliged to refresh my navigator. Ajax doesn't operate.
HTML/PHP
echo '<button class="delete_video" id="'.$videoId.'" type="button">Delete</button>';
javaScript
$(document).ready(function()
{
$(".delete_video").click(function()
{
var del_id = $(this).attr('id');
$.ajax({
type:'POST',
url:'delete.php',
data:'delete_id='+del_id,
success: function(data)
{
//confirmation of deletion
}
});
});
});
PHP
$id = $_POST['delete_id'];
include('functions.php');
$DB = connexion();
$DB->query('DELETE FROM videos WHERE id = "'.$id.'"');
Add location.reload() to the success function.
That is the syntax to use.
Plus, you're also open to a serious SQL injection.
Consult the following:
http://php.net/manual/en/security.database.sql-injection.php
How can I prevent SQL injection in PHP?
$(document).ready(function()
{
$(".delete_video").click(function()
{
var del_id = $(this).attr('id');
$.ajax({
type:'POST',
url:'delete.php',
data:'delete_id='+del_id,
success: function(data)
{
//reload page
location.reload();
}
});
});
});
I am hoping there are rows you are deleting so make sure that you pass an id element to each row as
here goes your video
and when your AJAX return success just make the element disappear
<div id="del_id">
here goes your video to delete
</div>
$(document).ready(function()
{
$(".delete_video").click(function()
{
var del_id = $(this).attr('id');
$.ajax({
type:'POST',
url:'delete.php',
data:'delete_id='+del_id,
success: function(data)
{
jQuery('#del_id').fadeOut('slow');
}
});
});
});

post binary code not working from Jquery ajax

I made this code to make image upload function but the variable is not getting posted by ajax please help me !!
Jquery()
<script type="text/JavaScript">
$(document).ready(function() {
$("#btn").click(function() {
$.get("i.png", function(response) {
var img = response;
});
$.ajax({
type: "POST",
url: 'lol.php',
data: {r: img},
success: function(data){
$("#ol").html(data)
}
});
return false;
});
});
</script>
PHP Code
<?php
$conn = mysqli_connect("localhost","root","","image");
$r = $_POST['r'];
echo $r;
?>
If you only want to make an image upload (and not exactly match "binary upload")
I suggest you to use the proper functional and native input type file.
In a html form, put an :
<input type="file" id="upload">
<img src="blank.png" title="upload-preview">
and in you javascript:
this will load the preview thumbnail selected
fileInput.addEventListener("change", function(event)
{
var file = $("#upload")[0].files[0];
$(".upload-preview").attr('src', window.URL.createObjectURL(file));
});
and when you click the button, that will send the image
with a "multipart/form-data" Content-Type
$("#btn").on("click", function()
{
var inputs = new FormData();
inputs.append("upload", $("#upload")[0].files[0]);
$.ajax
({
url:"your.php",
type:"POST",
data: inputs,
cache: false, // don't cache the image
processData: false, // Don't process the files
contentType: false,
success: function(response)
{
// next instructions
}
});
});

Including JS file in html page errors

I have this JavaScript code inside an html and PHP page. But I've been told that it will works only if I had an internet connection, so the solution was to make a .JS file and include this file inside the page like that:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script language="javascript" type="text/javascript" src="/clinic form/appoint/dropscript.js">
</script>
Now I got an error while testing the page offline.
The JS file is taken from this link:
multiple java script in one page error
And the final code is:
$(document).ready(function(){
$("#Date").change(function(){
var seldate =$(this).val();
display_data(seldate);
});
// This is the function...
function display_data(seldate) {
$("#scheduleDate").html(seldate);
var dataString = 'seldate='+ seldate;
$.ajax({
type: "POST",
url: "getdata.php",
data: dataString,
cache: false,
success: function(data) {
$("#Schedule").html(data);
}
});
}
// Now here is the real code for retaining your Date...
/*<?php
if (!empty($_GET['date'])) {
?>
display_data('<?php echo $_GET["date"]; ?>')
<?php
}
?>*/
document.getElementById('Date').value = '<?php echo #$_GET["date"]; ?>';
});
$(document).ready(function(){
$("#Name").change(function(){
var selname =$(this).val();
display_name(selname);
});
// This is the function...
function display_name(selname) {
$("#scheduleName").html(selname);
var dataString = 'selname='+ selname;
$.ajax({
type: "POST",
url: "getdatabyname.php",
data: dataString,
cache: false,
success: function(data) {
$("#Schedule").html(data);
}
});
}
});// JavaScript Document
P.S. I am totally new to JS and I am experimenting.
Go to https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js, hit CTRL+S, move saved file to your project's directory and then include it as you did with dropscript.js.
Also do the same with the font if you need it. Include it into your CSS file using #font-face. More information: https://developer.mozilla.org/en-US/docs/Web/CSS/#font-face

Pass PHP array to external jQuery $.ajax

Basically what I want to do is get an array that has t.php, and alert it with JavaScript with the response of t.php.
The problem is that the variable doesn't exist in this file...
So, how you can pass this variable to JS?
I tried with 'return':
return $sqlData = $q->query_array_assoc();
But doesn't work.
Here is my $.ajax code:
<script type="text/javascript">
$(document).ready(function(){
$('#brand').change(function(e){
console.log(e);
$.ajax({
method: "GET",
url: "t.php",
data: { type: 1, brand: this.value }
})
.done(function(msg){
$('#debug').html(msg);
var pArray = <?php echo json_encode($sqlData);?>
for (var i = 0; i < pArray.length; i++) {
alert(pArray[i]);
};
});
});
</script>
Note: I sent
data: { type: 1, brand: this.value }
To validate a switch statement in the .php file, but there isn't problem with that. I get the data from the database and fetch in the variable $sqlData;
So the array has data, the problem is get it with $.ajax
in your php file, you need to echo instead of return
echo json_encode($q->query_array_assoc());
in javascript code:
$.ajax({
method: "GET",
url: "t.php",
data: { type: 1, brand: this.value },
success: function(data) {
$('#debug').html(data);
// if you want to use it as array
var json_data = JSON.parse(data);
}
});
Make 2 files please, a "t.php" file and a "t.html" file and add my code there. Run the code and see response. You just have to work with the response to get the values se perated by comma "," !!!
/******************** UPDATED ***********************/
//t.php
<?php
$a = array();
$a[]=1;
$a[]=2;
$a[]=3;
echo "$a[0],$a[1],$a[2]";
?>
//t.html
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
function fun(){
$.ajax({
method: "GET",
url: "t.php",
data: { },
dataType: "html", //expect html to be returned
success: function(response){
//$("#debug").html(response); //Outputs the html of php file into #dialog div
alert(response);
document.getElementById("debug").innerHTML = (response); //Outputs the html of php file into #dialog div
}
})
}
</script>
<button onclick="fun()">Call Ajax Fun</button>
<div id="debug"></div>
Did this help?

Categories

Resources