PHP unlink not working when using PHP and Javascript - javascript

I have a process for deleting post entries in a PHP app. I want to delete the image associated with the post, if an image exists.
The post itself is deleted from the database successfully, but the image is not deleted from the image folder.
Here's delete_post.php:
if (isset($_GET['post_id'])) {
$post_id = $_GET['post_id'];
if (isset($_POST['result'])) {
if ($_POST['result'] == 'true') {
$delete_img = $pdo->prepare("SELECT image FROM posts WHERE id = ?");
$delete_img->execute([$post_id]);
$img_row = $delete_img->fetch();
$img = $img_row['image'];
if (file_exists($img)) {
unlink($img);
}
$sql = "DELETE FROM posts WHERE id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$post_id]);
}
}
}
...the form handler
<?php include '../../inc/config.php';
if (isset($_GET['post_id'])) {
$post_id = $_GET['post_id'];
if (isset($_POST['result'])) {
if ($_POST['result'] == 'true') {
$delete_img = $pdo->prepare("SELECT * FROM posts WHERE id = ?");
$delete_img->execute([$post_id]);
$img_row = $delete_img->fetch();
$filename = $_SERVER['DOCUMENT_ROOT']. '/' .$img_row['image'];
if (file_exists($filename)) {
unlink($filename);
}
$get_gallery_img = $pdo->prepare("SELECT * FROM files WHERE post_id = ?");
$get_gallery_img->execute([$post_id]);
while ($row = $get_gallery_img->fetch()) {
$galleryName = $_SERVER['DOCUMENT_ROOT'] . '/' . $row['file_name'];
unlink($galleryName);
}
$delete_gallery = "DELETE FROM files WHERE post_id = ?";
$stmt = $pdo->prepare($delete_gallery);
$stmt->execute([$post_id]);
$sql = "DELETE FROM posts WHERE id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$post_id]);
}
}
}
...and the Javascript that executes the form handler.
<script>
$(document).ready(function() {
$('#post<?=$id?>').on('click', function() {
bootbox.confirm("Are you sure you want to delete this post?", function(result){
$.post("inc/form_handlers/delete_post.php?post_id=<?=$id?>", {result:result});
if(result) {
location.reload();
}
});
});
});
</script>
I've tried moving the statement for deleting the image to just below the $_GET['post_id'] if statement, as well as just below the the $_POST['result'] if statement. I know it needs to be above the delete post statement since the path to the image is in the image column of the database - neither worked.
I have tried the unlink statement in another PHP file to make sure that it works - it does. So far I haven't found where I am going wrong, but I continue to look.
Since I'm still new to both PHP I am not sure where I should focus, or more to the point, what I am missing.

In case it helps someone else it was a path issue. Here's the final PHP:
if (isset($_GET['post_id'])) {
$post_id = $_GET['post_id'];
if (isset($_POST['result'])) {
if ($_POST['result'] == 'true') {
$delete_img = $pdo->prepare("SELECT * FROM posts WHERE id = ?");
$delete_img->execute([$post_id]);
$img_row = $delete_img->fetch();
$filename = $_SERVER['DOCUMENT_ROOT']. '/' .$img_row['image'];
unlink($filename);
$sql = "DELETE FROM posts WHERE id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$post_id]);
}
}
}
The part to note is $filename = $_SERVER['DOCUMENT_ROOT']. '/' .$img_row['image']; - using document root was the missing link.
I hope this helps any with a similar issue.

Related

How to get an value from a php page with js

I am trying to capture a value that is calculated on a PHP page called "classes_day.php" at the same time as I pass a value per GET, "? Day = YYYY-mm-dd" to it. How do I do this with JS or JQuery?
<?php
// aulas_dia.php
include '../config.php';
$exped_duration = 14*60;
if (isset($_GET['data'])) {
$data = $_GET['data'];
$query = "SELECT * FROM `task` WHERE `dia` LIKE ".$data."";
$result = mysqli_query($link,$query);
$soma = 0;
while ($row = mysqli_fetch_assoc($result)) {
$soma = $soma+$row['duration'];
}
$aulas_free = floor(($exped_duration-$soma)/50);
echo $aulas_free;
}
?>
I already tried using an iframe and contentwindow, but iframe gets the value and the contentwindow is empty (weird isn't it?).
Following Barmar's tip, I'm using $ .get, but I don't know why this loop is not working, can anyone help me?
for (i = 0; i < num_days; i++) {
x = (first_day+i)%7;
y = (first_day+i-x)/7;
h_dia(String(y)+String(x),i+1);
data_c = ano+"-"+mes+"-"+String(i+1);
$.get("aulas_dia.php?data="+data_c, function(data){
console.log(String(y)+String(x)+" - "+data_c+" - "+data);
set_aulas_fun(String(y)+String(x),data);
});
}
Use $.get() to send an AJAX request.
$.get("classes_day.php?data=YYYY-MM-DD", function(response) {
console.log(response);
});
BTW, you can add up all the durations in the SQL query instead of using a PHP loop. And you should use a prepared statement to prevent SQL injection.
<?php
include '../config.php';
$exped_duration = 14*60;
if (isset($_GET['data'])) {
$data = $_GET['data'];
$query = "SELECT SUM(duration) AS total FROM `task` WHERE `dia` LIKE ?";
$stmt = $link->prepare($query);
$stmt->bind_param("s", $data);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
$soma = $row['total'];
$aulas_free = floor(($exped_duration-$soma)/50);
echo $aulas_free;
}

make a deactivate account with jquery, ajax and php prob

I am adding a deactivate feature on a website i am working on, so I added a form with a textarea to tell the reason why the user is deactivating his account and a button that become enabled when the textarea is filled out so I sent the call via jquery ajax to a php script which will update the users_table in the database to 1 for deactivated then must log the user out and redirect them to the index page of the website. So everything works fine except the log out it is not happening and no redirect. I need help with that please
here is my php script :
require_once '../includes/session.php';
require_once '../includes/functions.php';
require_once '../includes/validation_functions.php';
// this to prevent from accessing this file by pasting a link to it
if(!is_ajax_request()) {
exit;
}
$user_id = (int)$_SESSION["user_id"];
if(isset($_POST['deactivate_reason'])) {
$deactivate_reason = mysql_prep($_POST['deactivate_reason']);
// INSERT into table
$query1 = "INSERT INTO deactivate_reason_table ( ";
$query1 .= "user_id, reason";
$query1 .= ") VALUES (";
$query1 .= " $user_id, '$deactivate_reason'";
$query1 .= ")";
$result1 = mysqli_query($connection, $query1);
$confirm_query1 = confirm_query($result1);
// if query1 is successful and replies deleted then we make the second query to delete the board comments
if ($confirm_query1 == 0) {
echo "error";
exit();
} else {
// UPDATE table
$query2 = "UPDATE users_table ";
$query2 .= "SET deactivated = 1";
$query2 .= "WHERE user_id = $user_id";
$result2 = mysqli_query($connection, $query2);
$confirm_query2 = confirm_query($result2);
if ($confirm_query2 == 0) {
echo "error";
exit();
} else {
if (isset($_COOKIE['username'])) {
// setcookie($name, $value, $expiration_time)
setcookie("username", '', time() - 42000, '/', $_SERVER['SERVER_NAME'] );
}
if (isset($_COOKIE['user_id'])) {
setcookie("user_id", '', time() - 42000, '/', $_SERVER['SERVER_NAME'] );
}
session_destroy();
// redirect_to() is a custom function in the functions.php that redirects
redirect_to("../index.php");
}
}
}
and here is my jquery ajax script :
$(document).on("click", "#deactivate_button", function(e){
e.preventDefault();
var text = $("#deactivate_reason_textarea").val();
var url = "widgets/deactivate.php";
$.ajax({
url: url,
method: "POST",
data: {
deactivate_reason: text
},
beforeSend: function() {
CustomSending("Processing...");
},
success: function(data){
$("#deactivate_reason_textarea").val("");
$("#dialogoverlay").fadeOut("Slow");
$("#sending_box").fadeOut("Slow");
$("body").css("overflow", "auto");
}
});
});
To redirect the user for a another page in PHP you can use something like header('Location: ...') (manual), but you are calling the script in ajax, then you need to put the redirect in this, not in the called PHP script.
To redirect in JavaScript you can use window.location (tutorial).
window.location = "my/another/script.php";
In your case, you need to put it in the success of ajax.
$.ajax({
... # your occulted script
success: function(data){
$("#deactivate_reason_textarea").val("");
$("#dialogoverlay").fadeOut("Slow");
$("#sending_box").fadeOut("Slow");
$("body").css("overflow", "auto");
window.location = "another/script.php";
// or you can put it in a timeout to show a message for the user or other thing
// setTimeout(function() {
// window.location = "another/script.php";
// }, 10000);
}
});
ok guys thanks a lot for your help, I managed to solve this with your help
after i added widow.location = "insert.php" like tadeubarbosa suggested then i went to my index.php page and added these lines :
if (logged_in()) {
$email = $user_data['email'];
$id = $user_data['user_id'];
$edited = account_edited($email);
if ($edited == 0){
redirect_to("editprofile.php?id=$id");
}
$is_deactivated = is_deactivated($_SESSION['user_id']);
if ($is_deactivated == 1) {
$query = "UPDATE users_table SET online = 0 WHERE user_id = $id";
$result = mysqli_query($connection, $query);
if (isset($_COOKIE['username'])) {
// setcookie($name, $value, $expiration_time)
setcookie("username", '', time() - 42000, '/', $_SERVER['SERVER_NAME'] );
}
if (isset($_COOKIE['user_id'])) {
setcookie("user_id", '', time() - 42000, '/', $_SERVER['SERVER_NAME'] );
}
session_destroy();
redirect_to("index.php");
}
}
then went to the login.php script and added a query to update deactivated = 0 if the user logs in so the account reactivates

Multiple AJAX functions on one functions page

I'd like to find a way of having a single page in the root of each of my web sections to hold all of the databae queries I'm calling.
I'm using a little script .....
<script type="text/javascript">
$(function() {
var availableTags = <?php include('fn-search-em.php'); ?>;
$("#quick-add").autocomplete({
source: availableTags,
autoFocus:true
});
});
</script>
.... to do SQL searches that appear as the user is typing. Similar to this ....
$sql = "SELECT * FROM stock_c_colours WHERE current_c_status = 'current' AND deleted = 'no'";
$result = mysqli_query($conn, $sql);
$results_list = array();
while($row = mysqli_fetch_array($result))
{
$colour_id = $row['id'];
$range_name = $row['range_name'];
$range_colour = $row['colour'];
$colour_code = $row['code'];
$p1 = $row['piece_size_1'];
$p2 = $row['piece_size_2'];
if($p1 > 1){
$p_mark = 'x';
}
else {
$p_mark = '';
}
$results_list[] = $range_name.' ('.$range_colour.' '.$colour_code.' '.$p1.$p_mark.$p2.') ID:'.$colour_id;
}
echo json_encode($results_list);
Echos a list in the form of a JSON array back to the text box and voila, a list. However, the site I'm working on at the moment has about 20 search boxes for various reasons scattered around (user request), does this mean I have to have 20 separate php function pages, each with their own query on, or can a single page be used?
I suspect the java needs modifying a little to call a specific function on a page of multiple queries, but I'm not good with Java, so some help would be greatly appreciated.
I did initially try adding ?action= to the end of the PHP address in the Java script, hoping a GET on the other end would be able to separate the PHP end into sections, but had no luck.
You need to change <?php include('fn-search-em.php'); ?>; to <?php $action = 'mode1'; include('fn-search-em.php'); ?>;.
Then in your fn-search-em.php file, use the $action variable to determine what kind of MySQL query you make.
For example:
if ($action == 'mode1')
$sql = "SELECT * FROM stock_c_colours WHERE current_c_status = 'current' AND deleted = 'no'";
else
$sql = "SELECT * FROM stock_c_colours WHERE current_c_status = 'mode1' AND deleted = 'no'";
You can do this with by creating a php file with a switch statement to control what code is executed during your Ajax call:
JS:
$.ajax({url: 'ajax.php', method: 'POST', async:true, data: 'ari=1&'+formData,complete: function(xhr){ var availableTags = JSON.parse(xhr.responseText);}});
PHP:
<?php
switch($_REQUEST['ari']){
case 1:
$sql = "SELECT * FROM stock_c_colours WHERE current_c_status = 'current' AND deleted = 'no'";
$result = mysqli_query($conn, $sql);
$results_list = array();
while($row = mysqli_fetch_array($result)){
$colour_id = $row['id'];
$range_name = $row['range_name'];
$range_colour = $row['colour'];
$colour_code = $row['code'];
$p1 = $row['piece_size_1'];
$p2 = $row['piece_size_2'];
if($p1 > 1){$p_mark = 'x';}
else { $p_mark = ''; }
$results_list[] = $range_name.' ('.$range_colour.' '.$colour_code.' '.$p1.$p_mark.$p2.') ID:'.$colour_id;
}
echo json_encode($results_list);
break;
case 2:
// another SQL Query can go here and will only get run if ARI == 2
break;
}
?>
This allows you to keep multiple AJAX handlers in the same file, you just need to pass the index for the desired handler when you make calls to the PHP file or nothing will happen.

Ajax database insert isnt working

I am trying to insert values from an input field into a database with ajax as part of a conversation system.I am using an input form as follows.
<input data-statusid="' .$statuscommentid. '" id="reply_'.$statusreplyid.'" class="inputReply" placeholder="Write a comment..."/>
with the following jquery I carry out a function when the enter key is pressed by the user.
$(document).ready(function(){
$('.inputReply').keyup(function (e) {
if (e.keyCode === 13) {
replyToStatus($(this).attr('data-statusid'), '1',$(this).attr("id"));
}
});
});
within this function is where I am having the problem ,I have no problems calling the function with jquery but I have done something wrong with the ajax and I don't know what?
$.ajax({ type: "POST", url: $(location).attr('href');, data: dataString, cache: false, success: function(){ $('#'+ta).val(""); } });
Additionally this is the php I am using to insert into the database
<?php //status reply input/insert
//action=status_reply&osid="+osid+"&user="+user+"&data="+data
if (isset($_POST['action']) && $_POST['action'] == "status_reply"){
// Make sure data is not empty
if(strlen(trim($_POST['data'])) < 1){
mysqli_close($db_conx);
echo "data_empty";
exit();
}
// Clean the posted variables
$osid = preg_replace('#[^0-9]#', '', $_POST['sid']);
$account_name = preg_replace('#[^a-z0-9]#i', '', $_POST['user']);
$data = htmlentities($_POST['data']);
$data = mysqli_real_escape_string($db_conx, $data);
// Make sure account name exists (the profile being posted on)
$sql = "SELECT COUNT(userid) FROM user WHERE userid='$userid' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
if($row[0] < 1){
mysqli_close($db_conx);
echo "$account_no_exist";
exit();
}
// Insert the status reply post into the database now
$sql = "INSERT INTO conversation(osid, userid, postuserid, type, pagetext, postdate)
VALUES('$osid','$userid','$postuserid','b','$pagetext',now())";
$query = mysqli_query($db_conx, $sql);
$id = mysqli_insert_id($db_conx);
// Insert notifications for everybody in the conversation except this author
$sql = "SELECT authorid FROM conversation WHERE osid='$osid' AND postuserid!='$log_username' GROUP BY postuserid";///change log_username
$query = mysqli_query($db_conx, $sql);
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$participant = $row["postuserid"];
$app = "Status Reply";
$note = $log_username.' commented here:<br />Click here to view the conversation';
mysqli_query($db_conx, "INSERT INTO notifications(username, initiator, app, note, date_time)
VALUES('$participant','$log_username','$app','$note',now())");
}
mysqli_close($db_conx);
echo "reply_ok|$id";
exit();
}
?>
Thanks in advance for any help it will be much appreciated
Why didn't you set the proper URL for Ajax calls instead of using location.href?
var ajax = ajaxObj("POST", location.href);
In additional, I guess ajaxObj is not defined or well coded. You are using, jQuery, why don't you try jQuery ajax?
http://api.jquery.com/jquery.ajax/
var ajax = ajaxObj("POST", location.href);
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
var datArray = ajax.responseText.split("|");
if(datArray[0] == "reply_ok"){
var rid = datArray[1];
data = data.replace(/</g,"<").replace(/>/g,">").replace(/\n/g,"<br />").replace(/\r/g,"<br />");
_("status_"+sid).innerHTML += '<div id="reply_'+rid+'" class="reply_boxes"><div><b>Reply by you just now:</b><span id="srdb_'+rid+'">remove</span><br />'+data+'</div></div>';
_("replyBtn_"+sid).disabled = false;
_(ta).value = "";
alert("reply ok!");
} else {
alert(ajax.responseText);
}
ajax.send("action=status_reply_ok&sid="+sid+"&user="+user+"&data="+data);
}
}

using phpfile output inside js file file as variable

Recently I am learning single page application, but I got a problem, the project I am working on is inside a folder that contain many folders, php js are folders in side the main folder, and each contain its type of files, the problem is that one of the php file called getmax.php gives me the maximum id ,I want to use this max(id) in a js file called module.js in order to give the new module the next id , the module.js should gives this id to another php file called insert.php ,the connection between the module.js and insert.php is working properly if I set the id manually . but I could not figure out how can I make it use the max(id) from the getmax.php file.
note: I noticed lately I'm using MySQL and I should used mysqli I will fix it later.
the getmax.php is:
<?php
// alle relevanten Tabellen abfragen und als json zurückgeben.
$json["status"] = "running";
$details[] = "started get_tables ";
// Include confi.php
include_once('confi.php');
//var_dump($_POST);
$request_body = file_get_contents('php://input');
// first store the given set of data to keep it for future analysis
$statement = "INSERT INTO tbl_archive (content) VALUES ('$request_body' );";
mysql_query($statement);
$input = json_decode($request_body, true);
// now check if valid user
$user = $input["user"];
$username = $user["username"];
$password = $user["password"];
if($password and $username){
$mySQLstring = "SELECT username, password, id, create_user FROM tbl_user where username = '$username' ;";
$json["statement"][] = $mySQLstring;
$qur = mysql_query($mySQLstring);
//var_dump ( $qur );
if ($qur){
$max = mysql_fetch_assoc($qur);
}
if ($max){
$json["max"] = $max;
if ($max["password"] == $password){
$json["username"] = $username;
$json["id"] = $max["id"];
$json["create_user"] = $max["create_user"];
$json["status"] = "ok";
$tables = array("class", "class_user", "module", "module_class", "module_user", "rating", "student", "student_class");
//$tables = array("class");
foreach($tables as $table){
if ( $table == 'module' ){
$statement ='SELECT create_user, MAX(id) FROM tbl_'.$table;
//$statement .= ' GROUP BY create_user' ;
$statement .= ' WHERE create_user = 19 ' ;
$qur = mysql_query($statement);
if ($qur){
while($r = mysql_fetch_array($qur, MYSQL_ASSOC)){
//var_dump($r);
//echo (json_encode($r));
$result[$table][] = $r;
}
}
}
}
$json = array("status" => "ok", "data" => $result);
}
}
}
#mysql_close($conn);
/* Output header */
header('Content-type: application/json');
echo json_encode($json);
?>
PHP and JS are run on the server and client respectively, and as such you cannot call methods/functions of one from the other. AJAX exists to pass values between JS and serverside code.

Categories

Resources