onclick function fails to update sql - javascript

I have this button
<button id = "addBtn-1" onclick = "noneAdd();add1()">Add to My Classes</button>
It calls a function called add1() from my js file, which adds and removes classes and also calls add():
function add(){
$.ajax({url:"add.php",
success:function(result){
alert("Added to My Classes");
}
});
}
which calls my php file, add.php:
require_once "config.php";
include "classes.php";
$myun = $_SESSION["un"];
function bookmark1Add(){
$sql = "SELECT testclass1 FROM classes WHERE username = ?";
if($stmt = mysqli_prepare($db, $sql)){
mysqli_stmt_bind_param($stmt, "s", $param_un);
$param_un = $myun;
if(mysqli_stmt_execute($stmt)){
mysqli_stmt_bind_result($stmt, $myclass1);
if(mysqli_stmt_fetch($stmt)){
if($myclass1 == 0){
$sql2 = "UPDATE classes
SET testclass1 = 1";
if($stmt2 = mysqli_prepare($db, $sql2)){
mysqli_stmt_bind_param($stmt2, "s", "param_un");
$param_un = $myun;
if(mysqli_stmt_execute($stmt2)){
header("Refresh:0");
}
else{
echo "Something went wrong, please try again later!";
}
}
mysqli_stmt_close($stmt2);
}
}
}
}
mysqli_stmt_close($stmt);
}
bookmark1Add();
This line of code is supposed to update the data in my table, but it doesn't seem to be working. When I click the button, nothing changes in the database, however the adding and removing of classes from add1() works so it succeeded in calling the function

nvm I made the code much simpler since the one above was way too complicated and rat it on its own to see if there were any bugs.
<?php
require_once "config.php";
include "classes.php";
$myun = $_SESSION["un"];
$sql = "UPDATE classes SET testclass1 = 1 WHERE username = '$myun'";
if (mysqli_query($db, $sql)) {
header: "Refresh:0";
}
?>
this worked way better

Related

PHP unlink not working when using PHP and 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.

I don't want my php page to refresh after function executes

I got function that collects and display's all posts, and for each have upvote/downvote buttons.
On button click I call function called upvotePost and downvotePost.
It all works fine, but it refreshes page, I want to understand how to make it not-refresh page.
I know it's done by ajax/jquery, but don't understand how to make it.
My button example:
<a href="fun.php?upvote-btn=true?action=select&image_id=<?php echo $post['id'];?>">
Function calling:
if(isset($_GET['upvote-btn'])){
$fun->upvotePost();
}
And my function:
public function upvotePost(){
try
{
if(isset($_SESSION['user_session'])){
$user_id = $_SESSION['user_session'];
$stmt = $this->runQuery("SELECT * FROM users WHERE id=:id");
$stmt->execute(array(":id"=>$user_id));
$myRow=$stmt->fetch(PDO::FETCH_ASSOC);
}else{
$_SESSION["error"]='Sorry, You have to login in you account!';
}
$id = $_GET['image_id'];
$user_id = $myRow['id'];
$stmt2 = $this->conn->prepare("SELECT count(*) FROM fun_post_upvotes WHERE image_id=('$id') AND user_id=('$user_id')");
$stmt2->execute();
$result2 = $stmt2->fetchColumn();
if($result2 == 0){
$stmt3 = $this->conn->prepare("INSERT INTO fun_post_upvotes (image_id,user_id) VALUES(:image_id,:user_id)");
$stmt3->bindparam(":image_id", $id);
$stmt3->bindparam(":user_id", $user_id);
$stmt3->execute();
$stmt4 = $this->conn->prepare("SELECT * FROM fun_posts WHERE id=('$id')");
$stmt4->execute();
$result4 = $stmt4->fetchAll();
foreach($result4 as $post){
$newUpvotes = $post['upvotes']+1;
$stmt5 = $this->conn->prepare("UPDATE fun_posts SET upvotes=$newUpvotes WHERE id=('$id')");
$stmt5->execute();
$_SESSION["result"]='You have succesfully liked this post!';
}
}else{
$_SESSION["error"]='You have already liked this post!';
}
$stmt6 = $this->conn->prepare("SELECT count(*) FROM fun_post_downvotes WHERE image_id=('$id') AND user_id=('$user_id')");
$stmt6->execute();
$result6 = $stmt6->fetchColumn();
if($result6 > 0){
$stmt7 = $this->conn->prepare("DELETE FROM fun_post_downvotes WHERE image_id=('$id') AND user_id=('$user_id')");
$stmt7->execute();
$stmt8 = $this->conn->prepare("SELECT * FROM fun_posts WHERE id=('$id')");
$stmt8->execute();
$result8 = $stmt8->fetchAll();
foreach($result8 as $post){
$newDownvotes = $post['downvotes'] - 1;
$stmt9 = $this->conn->prepare("UPDATE fun_posts SET downvotes=$newDownvotes WHERE id=('$id')");
$stmt9->execute();
}
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
Ajax is the perfect answer for your question. Please check out this. you may need to alter this snippet according to your requirement.
before doing this you should import jquery.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
your upvote button should be like this,
<button id="upvote"> upvote </button>
add below snippet in your javascript section.
$(function(){
$("#upvote").click(function(){
$.ajax(
{ url: "fun.php?upvote-btn=true?action=select&image_id=<?php echo $post['id'];?>",
type: "get",
success: function(result){
// todo something you need to perform after ajax call
}
});
});
});
Basically you have to create a php file which will route the call(let's call it a controller) to the intended function. Then create an ajax function which will hit that controller. Have a look at
Ajax Intro
Or look at the Jquery Implementation

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.

Jquery AJAX is working but displayed message bugged

In changename.php I have this DIV:
<div id="resultDiv"></div>
In the same file I have the PHP code:
<?php
include_once ('connect.php');
if(isset($_POST['name']))
{
$postedname = $_POST['name'];
$safename = mysqli_real_escape_string($con, $postedname);
$checkname = "SELECT * from accounts where name='$safename' LIMIT 1";
$query = mysqli_query($con, $checkname);
$row = mysqli_num_rows($query);
if($row) {
echo 'Name is already taken!';
} else {
$changename = "UPDATE accounts SET name='$safename' WHERE Name='$_SESSION[username]'";
$query = mysqli_query($con, $changename);
if($query)
{
echo 'Name is changed!';
$_SESSION['username'] = $safename;
}
}
}
?>
And this is my Jquery script (in a seperate file):
$(function(){
$("form").submit(function() {
event.preventDefault();
var name = $('#inputName').val();
$.post("changename.php",
{
name: name
},
function(data)
{
$("#resultDiv").text(data);
});
});
});
The code is just working fine, it successfully changes my name. If I want my name to be 'John', it successfully changes it in the DB.
The problem is, it's supposed to change the div with ID resultDiv to Name is already taken!. Instead of that, it takes the whole changename.php HTML code and puts it into that DIV. So instead of 1 line, I have 100+ lines of my page in there. So it looks like this:
https://gyazo.com/9320a5f15ed67a8ad9298d6172ab6909
Any idea why it's not just the message I want?
Ajax will fetch all data from file given as url for it.
If you want to avoid that, you have 2 options.
Write condition in changename.php in such a way that only update to db part will be executed.
On changename.php keep only required code to update to db.

Ensure that each user's click only is sent once in a defined time period

Hi I have the following code which I am trying to adapt to make sure that when Like is clicked by a user who is logged in, then only one request is sent in a predetermined period of time that can be adjusted i.e Like can be clicked and a request sent only once every 5 minutes. There must be a javascript function I can use but I can't figure it out.
index.php:
<?php
include 'init.php';
include 'connect.php';
?>
<!doctype html>
<html>
<body>
<?php
$userid = $_SESSION['user_id'];
echo '<a class="like" href="#" onclick="like_add(', $userid,');">Like</a>';
?>
<script type ="text/javascript" src="jquery-1.11.1.min.js"></script>
<script type ="text/javascript" src="like.js"></script>
</body>
</html>
connect.php:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "DB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
init.php:
<?php
session_start();
$_SESSION['user_id']='1';
$userid = $_SESSION['user_id'];
include 'connect.php';
include 'like.php';
?>
like.js:
function like_add(userid) {
$.post('like_add.php', {userid:userid}, function(data) {
if (data == 'success'){
add_like($userid);
} else {
alert(data);
}
});
}
like.php:
<?php
function add_like($userid) {
include 'connect.php';
$stmt = $conn->prepare("INSERT INTO clicks (user) VALUES (?)");
$stmt->bind_param("s", $userid);
$stmt->execute();
$stmt = $conn->prepare("SELECT max(id) FROM clicks WHERE user=?");
$stmt->bind_param("s", $userid);
$stmt->execute();
$stmt->bind_result($click);
$stmt->fetch();
echo $click;
$stmt->close();
}
?
like_add.php
<?php
include 'init.php';
if (isset($userid)) {
$userid = $userid;
add_like($userid);
}
?>
If you pass the a tag into like_add like so:
<?php
$userid = $_SESSION['user_id'];
echo '<a class="like" href="#" onclick="like_add(this, '.$userid.');">Like</a>';
?>
You can disable it in the javascript function for a set time period:
function like_add(a, userid) {
a.disabled = true;
setTimeout(function(){
a.disabled = false;
), 5000});//Code will execute in 5 seconds to enable the a tag
$.post('like_add.php', {userid:userid}, function(data) {
if (data == 'success'){
add_like($userid);
}else{
alert(data);
}
});
}
Is this something alogn the lines of what you were looking for?
In a completly not recommended way, you could define
var isLikeable = true;
function likeStatus(secs) {
isLikeable = false;
window.setTimeout("isLikeable = true;", (secs*60));
}
then, when clicking the "like" you would check
if (isLikeable) { // do like and call likeStatus(300); }
Do you need this to be enforced on the back-end, or is disabling it through the UI sufficient? You could theoretically get people hacking it using Developer tools or Firebug, but this seems very unlikely from casual users.
On the front end, I would user jQuery to add code on the click event that disables the "Like" button with a timeout, like this:
// First, move your click handler to your script file
$('.like').click( function(event) {
// Make sure clicking the button doesn't submit any form context that might be present
event.preventDefault();
var DURATION_IN_MINUTES = 5;
// Grab the user id that will be added as an attribute of your element: data-user-id="$userid"
var user_id = $(this).data('userID');
// Run your function
like_add(user_id);
// Disable clicking like (it's easiest to do this with a button, by far
$(this).prop({'disabled':true,'title':'Disabled for ' + DURATION_IN_MINUTES + ' minutes');
// Set a timer to re-enable the like button in 5 minutes
setTimeout( function() { $(this).prop({'disabled':false,'title':''}), DURATION_IN_MINUTES * 60 * 1000}
});
and then in your HTML:
echo '<a class="like" href="#" onclick="like_add(', $userid, ');">Like</a>';
becomes
echo '<button class="like" data-user-id="' + $userid + '">Like</button>';
I don't have a PHP environment to test this (and I haven't tested the JavaScript itself, to be honest), but this should be enough to get you started.
If you want to block multiple submissions on the back-end, you'll want to timestamp your likes, and do a look-up to see the last time a given user "liked" that link.

Categories

Resources