I'm trying to implement some Ajax on a favourite/unfavourite button. The idea behind it is that when you click it a star changes to yellow and when you click it again, it changes back to grey and so on. It adds and deletes data from a DB.
before I had it like this
<?php
include("classes/event.class.php");
$m = new Event();
$arrayAllEvents = $m->getNonFavo();
$arrayFavorites = $m->getFavo();
$db = new db();
while ($row = mysqli_fetch_assoc($arrayFavorites))
{
$unfavoriteID = $row['f_id'];
$uid = $_SESSION['u_id'];
}
if(isset($_POST['favorite_row']))
{
$uid = $_SESSION['u_id'];
$Fid = $_POST['id_to_be_favo'];
if(!mysqli_query($db->conn, "INSERT INTO favorites (u_id, n_id, f_boolean) VALUES
('". $db->conn->real_escape_string($uid) ."' ,
'". $db->conn->real_escape_string($Fid) ."' ,
'". $db->conn->real_escape_string("1") ."')"))
{
echo mysqli_error($db->conn);
}
}
if(isset($_POST['Unfavorite_row']))
{
$unFid = $_POST['id_to_be_unfavo'];
if(!mysqli_query($db->conn, "DELETE FROM favorites WHERE f_id ='".$unFid."'"))
{
echo mysqli_error($db);
}
}
?>
And the field was a php echo form
<?php
echo "<form method='post'>
<input type ='hidden' name='id_to_be_favo'
value='".$a['n_id']."' />
<input type='submit' class='favoriteFalse' id='FavoBtn' name='favorite_row' value='favorite' />
</form>
<div class='clearfix'> </div>";
?>
I'm trying to change the form to a button and use jQuery/Ajax to switch it.
I've been trying some different solutions I've found online, but none of them seem to work.
What would be the best way to implement this?
Kind regards
<input type='button' class='favorite' id='<?php echo $a['n_id']; ?>' value='favorite' />
<div class='clearfix'> </div>";
using
$(function() {
$(".favorite").on("click".function() {
$.post("whatever.php", {"favorite_row":this.id}, function(data) {
$("#star").html('<img/>',{"src":data.fave==yes"?"true.png":"false.png"});
});
});
Now return {"fave":"yes"} if favorited
Related
I have a comments section in a website that uses a "setComments" function to enter data into a SQL DB. This works great, but I found that if I refresh the page, the comment is re-entered into the DB and displayed as multiple comments using a "getComments" function.
I know I need to drop the values of the comment variables but tried a few places in the code and no joy.
This is the form to enter the comment:
<?php
echo "<form method='POST' action='".setComments($conn)."'>
<input type='hidden' name='uid' value='Anonymous'>
<input type='hidden' name='pid' value='$post_id'>
<input type='hidden' name='date' value='".date('Y-m-d H:i:s')."'>
<label>Add Comment</label>
<textarea name='message'class='form-control' width='50' cols='40'
rows='3'></textarea><br>
<button type = 'submit' name ='commentSubmit' class='btn btn-
primary'>Submit<span class='glyphicon glyphicon-chevron-right'></span>
</button>
</form>";
getComments($conn)
?>
<?php
function setComments($conn){
if (isset($_POST ['commentSubmit'])) {
$uid=$_POST['uid'];
$pid=$_POST['pid'];
$date=$_POST['date'];
$message=$_POST['message'];
$sql = "INSERT INTO comments (uid, pid, date, message)
VALUES('$uid','$pid', '$date', '$message')";
$result = $conn->query($sql);
}
}
function getComments($conn) {
if (isset($_GET['post'])) {
$pid = $_GET['post'];
$sql = "SELECT * FROM comments WHERE pid=$pid";
$result = mysqli_query($conn, $sql) or die(mysqli_error($conn));
if (mysqli_num_rows($result) > 0) {
while($row = $result->fetch_assoc()){
echo "<div class='comment-box'>";
echo $row['uid']."<br>";
echo $row['date']."<br>";
echo $row['message'];
echo "</div>";
}
}
else {
echo "Be the first to comment";
}
}
}
Comments are entered into sql DB fine, but variables not discarded once complete so they are re-entered into DB and displayed again on page refresh (page containing the comment form also displays the comments.
I ended up using the following script in the page - it seems to work fine:
<script>
if ( window.history.replaceState ) {
window.history.replaceState( null, null, window.location.href );
}
</script>
Before I say anything I'll just post my index.php to allow you guys to get an idea of what it looks like first:
<script>
function submitLikeForm() {
var form = jQuery("#like_form");
$.ajax({ type: "GET", url: form.attr("action"), data: form.serialize(), success: function() });
}
</script>
<script>
function leaveYourComment() {
var form = jQuery("#comment_form");
$.ajax({ type: "GET", url: form.attr("action"), data: form.serialize(), success: function() });
}
</script>
<link type="text/css" rel="stylesheet" href="index.css">
</head>
<body>
<?php
$conn = mysqli_connect("localhost","root","") or die ("No SQLI");//run query to display all images uploaded by users
mysqli_select_db($conn, "sample") or die ("No DB");
$sqli = "SELECT * FROM `photos` ORDER BY `id` DESC";
$result = mysqli_query($conn, $sqli) or die ("No query");
while($row = mysqli_fetch_assoc($result)) {
$username = $_SESSION['id'];
$title = $row['title'];
$description = $row['description'];
$image_name = $row['image_name'];
$random_directory = $row['random_direc'];
$date = date('M/d/Y');
$image_info = "http://localhost/splindr_2.0/photos/$random_directory/$image_name";
$sqli = ("SELECT * FROM `likes` WHERE `hidden_name` = '$image_name' AND `hidden_folder` = '$random_directory'");//run query to get likes
$likes_result = mysqli_query($conn, $sqli) or die ("No query");
$liked_count = '0' ; $unliked_count = '0';
while($likes_row = mysqli_fetch_assoc($likes_result)) {
if($likes_row['liked_unliked'] == 0) {
$unliked_count++;
} else {
$liked_count++;
}
}
$comment_count = ("SELECT * FROM `comments` WHERE `hidden_folder` = '$random_directory' AND `hidden_name` = '$image_name'");//run query to get comments
$comment_query = mysqli_query($conn, $comment_count) or die ("No query");
$total_comments = mysqli_num_rows($comment_query);
while($comment_result = mysqli_fetch_assoc($comment_query)) {
$comment = $comment_result['comment'];
$commented_on_by = $comment_result['commenting_user'];
}
echo "<div id='contentWrapper'>
<div class='photo'>
<div class='actual_image'>
<img src='$image_info'>
</div>
<div class='like_system'>
<form name='like_form' id='like_form' action='liked_button.php'>
<input type='image' img src='https://i.imgur.com/pMmYaYM.jpg' class='like_button button' name='like_button' onClick='return submitLikeForm()'>
<input type='hidden' name='hidden_image' class='hidden_image' value='$image_info'>
<input type='hidden' name='hidden_folder' class='hidden_folder' value='$random_directory'>
<input type='hidden' name='hidden_name' class='hidden_name' value='$image_name'>
<input disabled type='text' name='total_likes' class='total_likes' value='$liked_count'>
</form>
<a style='color: #2e4987;text-decoration:none' href='http://www.twitter.com/share?url=$image_info&hashtags=Splindr, CheckThisOut'>
<img class='twitter_button button' name='twitter_button' src='http://i.imgur.com/hKFKJoj.jpg'></a>
<img src='http://i.imgur.com/8azoFjh.jpg' class='show_comments button' name='show_comments'>
<input disabled type='text' class='comment_count' name='comment_count' value='$total_comments'>
<img class='delete_button button' name='delete_button' src='http://i.imgur.com/wKZu2H1.jpg'>
</div>
<div class='info_wrapper'>
<div class='info_header'>Title: $title   By: $username   Date: $date</div>
<div class='description'>$description</div>
</div>
<div class='comment_wrapper'>
<div class='close_comment'>[close comments]</div>
<div class='comment_box_wrapper'>
<div class='comment_box'>
<div class='commenter'>$commented_on_by</div>
<div class='profile_pic'><img src='https://i.imgur.com/1MkFvhU.png'></div>
<div class='actual_comment custom_scrollbar'>$comment</div>
</div>
</div>
<div class='post_comment'>
    <a style='color:#9b6bb4 ; text-decoration:none ; position:relative ; top:-5px ; left:-5px'></a>
<form name='comment_form' id='comment_form' action='leave_comments.php' onSubmit='return validateForm()'>
<input type='text' name='user_comment' class='user_comment' placeholder='Leave a comment...'>
<input type='hidden' name='hidden_image' class='hidden_image' value='$image_info'>
<input type='hidden' name='hidden_folder' class='hidden_folder' value='$random_directory'>
<input type='hidden' name='hidden_name' class='hidden_name' value='$image_name'>
<input type='image' img src='http://i.imgur.com/8azoFjh.jpg' class='leave_comment button' name='leave_comment button' onClick='return leaveYourComment ()'>
</form>
</div>
</div>
</div>
</div>";
}
?>
Okay so basically, so this index.php page is where images go after users upload them. Users can comment and like posts/images.
The problem I'm having is with my comments system. The comments are uploaded to mysqli just fine, however, I'm having trouble echoing each individual comment out. Multiple comments are shown in my table, but when I post a new comment, the new comment just replaces the previously posted comment. I don't want this, I want every comment to display by id DESC.
I've tried a loop for the comments (as you can see in the code above), but like I said, it just makes the newest comment replace the older comment.
So how can I correct my code so that all comments show in a comment_box within the comment_box_wrapper, with the respective information of the user that posted the comment.
I've struggled with this all day so any help will be appreciated.
Let me know if you need me to post anything else. I only posted the index.php because everything else is working and the problem is located only on this page.
You are assigning the $comment and $commented_by variables in a loop, effectively overwriting them, without using them.
You'd need to split you one big echo, and replace the comment_box part with something like this:
while($comment_result = mysqli_fetch_assoc($comment_query)) {
echo "<div class='comment_box'>";
echo "<div class='commenter'>".$comment_result['commenting_user']."</div>";
echo "<div class='profile_pic'><img src='https://i.imgur.com/1MkFvhU.png'></div>";
echo "<div class='actual_comment custom_scrollbar'>".$comment_result['comment']."</div>";
echo "</div>";
}
As you see above, we print each comment data, on each iteration of the loop.
I am trying to edit data in my database but i cant get it to work.
i have tried breaking the script down to basics and troubleshoot each part.
The delete button works just fine but editting the data doesn't.
Where have i gone wrong?
my structure
database = domains table = domains_info row = domain
<?php include("header.php");
//include database connection
include 'db_connect.php';
$action = isset( $_POST['action'] ) ? $_POST['action'] : "";
if($action == "update"){
//write query
$query = "update domains_info
set
domain = '".$mysqli->real_escape_string($_POST['domain'])."',
where id='".$mysqli->real_escape_string($_REQUEST['id'])."'";
if( $mysqli->query($query) ) {
echo "User was updated.";
}else{
echo "Database Error: Unable to update record.";
}
}
if($action=='delete'){ //if the user clicked ok, run our delete query
$query = "DELETE FROM domains_info WHERE id='".$mysqli->real_escape_string($_GET['id'])."'";
if( $mysqli->query($query) ){
echo "User was deleted.";
}else{
echo "Database Error: Unable to delete record.";
}}
$query = "select id, domain
from domains_info
where id='".$mysqli->real_escape_string($_REQUEST['id'])."'
limit 0,1";
$result = $mysqli->query( $query );
$row = $result->fetch_assoc();
$id = $row['id'];
$domain = $row['domain'];?>
<form action='#' method='post' border='0' class="well form-horizontal">
<fieldset>
<label class="control-label" for="name">Domain</label>
<div class="controls">
<input id="name" type="text" name="name" value="<?php echo$domain; ?>">
<input type='hidden' name='id' value='<?php echo $id ?>' />
<!-- we will set the action to edit -->
<input type='hidden' name='action' value='update' />
<input type='submit' value='Edit' />
</fieldset>
</form>
<?php echo "<a href='#' onclick='delete_user( {$id} );'>Delete</a>"; ?>
<script type='text/javascript'>
function delete_user( id ){
//prompt the user
var answer = confirm('Are you sure you want to delete <?php echo$name; ?>?');
if ( answer ){ //if user clicked ok
//redirect to url with action as delete and id of the record to be deleted
window.location = 'deletecontact.php?id=' + id;
}
}
</script>
the error im getting is this
Database Error: Unable to update record.
There is a extra ',' in your update query
$query = "update domains_info
set
domain = '".$mysqli->real_escape_string($_POST['domain'])."',
where id='".$mysqli->real_escape_string($_REQUEST['id'])."'";
with
$query = "update domains_info
set
domain = '".$mysqli->real_escape_string($_POST['domain'])."'
where id='".$mysqli->real_escape_string($_REQUEST['id'])."'";
Ok, so I have an input function that allows me to add items to a database, and displays this as a table. As part of the table, I am trying to add delete and edit buttons.
I am trying to figure out the best way to add delete and edit functionality. I'm thinking for editing, I will have to use Javascript. However, for deletions, I am not sure if I should use PHP, Javascript, or some combination therein.
So far, here's my code:
<html>
<header><title>Generic Web App</title></header>
<body>
<form action="addculture.php" method="POST">
<span><input type="text" size="3" name="id" />
<input type="text" name="culture" />
<input type="submit" value="add" /></span>
</form>
<?php
/* VARIABLE NAMES
*
* $con = MySQL Connection
* $rescult = MySQL Culture Query
* $cultrow = MySQL Culture Query Rows
*/
$con = mysql_connect("localhost", "root", "");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("generic");
$rescult = mysql_query("SELECT * FROM culture order by cult_id");
if (!$rescult) {
die('Invalid query: ' . mysql());
}
echo "<table><tbody><tr><th>ID</th><th>Culture Name</th>";
while ($cultrow = mysql_fetch_array($rescult)) {
echo "<tr>" . "<td>" . $cultrow[0] . "</td>" . "<td>" . $cultrow[1] . "</td>" . '<td><button type="button">Del</button></td>' . '<td><button type="button">Edit</button></td>' . "</tr>";
}
echo "</tbody></table>";
?>
</body>
</html>
Currently I have del and edit set as buttons, just for visible reference. What's the best way to deal with a situation where you have multiple buttons like this?
I apologize if my answer is too broad but so is your question.
Both, Editing and Deleting should use a combination of JavaScript and PHP code; for example when the user clicks on the delete button you can send an Ajax request to the server, have the record deleted from the DB and upon successful return from the server-side call, use JavaScript to visually delete the record from the markup. The same would apply to the Edit functionality.
Here's a nice intro on how to perform ajax requests using JQuery:
http://www.devirtuoso.com/2009/07/beginners-guide-to-using-ajax-with-jquery/
The first think I would do is add a value and name to the buttons:
<button type="button" value="$cultrow[0]" name="Delete">Delete</button>
<button type="button" value="$cultrow[0]" name="Edit">Edit</button>
The value of the button is going to be the id of the row, and the name is going to be the action that button will do. The next thing I would do is bind those buttons to actions with jquery.
$('button').click(function(){
//determine whether is delete or edit
//Once you determine what action use the id to make the request
//if delete prompt to verify if yes, ajax the server with a delete request
//if edit redirect user to a page that will handle editing of the row edit.php?id=5
});
For deleting row
1 - Make new page name it del_culture.php
session_start();
$id = base64_decode($_GET['id']);
$con = mysql_connect("localhost", "root", "");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$q = mysql_query("DELETE FROM culture WHERE cult_id = '".$id."' ");
if($q):
echo "Done";
else:
echo "ERROR";
endif;
2 - in your page add the following code
while ($cultrow = mysql_fetch_array($rescult))
{
echo "<tr>" . "<td>" . $cultrow[0] . "</td>" . "<td>" . $cultrow[1] . "</td>" . '
<td>Delete' . '<td><button type="button">Edit</button></td>' . "</tr>";
}
For Editing a row add link for edit like i did to page name it edit_cult.php
and do the same as you input put the values from database and then update it
This is your javascript
function performAction(action) {
// ASSIGN THE ACTION
var action = action;
// UPDATE THE HIDDEN FIELD
document.getElementById("action").value = action;
switch(action) {
case "delete":
//we get an array with every input contained into the form, and the form have an id
var aryCheck=document.getElementById('adminform').getElementsByTagName('input');
//now we parse them
var elm=null;
var total=0;
for(cptCnt=0;cptCnt<aryCheck.length;cptCnt++) {
elm=aryCheck[cptCnt];
if(elm.type=='checkbox') {
//we have a checkbox here
if(elm.checked==true){
total++;
}
}
}
if(total > 0) {
if(confirm("Are you sure you want to delete the selected records?")) {
// SUBMIT THE FORM
document.adminform.submit();
}
}
else {
alert("You didn't select any records");
}
break;
case "edit":
//we get an array with every input contained into the form, and the form have an id
var aryCheck=document.getElementById('adminform').getElementsByTagName('input');
//now we parse them
var elm=null;
var total=0;
for(cptCnt=0;cptCnt<aryCheck.length;cptCnt++) {
elm=aryCheck[cptCnt];
if(elm.type=='checkbox') {
//we have a checkbox here
if(elm.checked==true){
total++;
}
}
}
if(total > 1) {
alert("You can only edit one record at a time");
}
else if(total == 0) {
alert("You didn't select a record");
}
else {
document.adminform.submit();
}
break;
default:
}
}
and in your form you need something like this
<form id="adminform" name="adminform" action="<?php $_SERVER['REQUEST_URI'] ?>" method="post">
<img src="/admin/images/news.png" alt="news" title="news" />
<input type="button" class="back" id="backbutton" title="go back" onclick="performAction('back');" />
<input type="button" class="delete" id="deletebutton" title="delete" onclick="performAction('delete');" />
<input type="button" class="archive" id="archivebutton" title="archive" onclick="performAction('archive');" />
<input type="button" class="edit" id="editbutton" title="edit" onclick="performAction('edit');" />
<input type="button" class="add" id="addbutton" title="add" onclick="performAction('add');" />
<table id="admintable">
<tr><th class='tdleft'>
<?php
if($err !=0) {
echo"<input type='checkbox' name='all' onclick='checkAll(adminform);' />";
}
echo "</th><th class='tdright'>Title</th></tr>";
$z = 0;
// Iterate through the results
while ($row = $result->fetch()) {
if($z % 2==0) {
//this means if there is a remainder
echo "<tr class='yellow'>\n";
$z++;
} else {
//if there isn't a remainder we will do the else
echo "<tr class='white'>\n";
$z++;
}
echo "<td class='tdleft'><input type='checkbox' name='id[]' value='{$row['id']}' /></td><td class='tdright'><a href='/admin/news/edit-news-".$row['id']."'>{$row['title']}</a></td></tr>";
}
?>
</table>
<input type="hidden" id="action" name="action" value="" />
and at the top of your page before the html put
if($_POST && array_key_exists("action", $_POST)){
// CARRY OUT RELAVANT ACTION
switch($_POST['action']) {
case "edit":
foreach($_POST['id'] as $value) {
$id = $value;
}
header('Location: /admin/blogs/edit-blog-'.$id);
break;
case "delete":
if(!empty($_POST['id'])) {
//do your delete here
}
break;
}
}
}
Any ideas why the following code is not adding anything into the database once the user fills out the form? I'd really appreciate it.
Thank you!
if($_SESSION['loginSuccess']==1) {
// ============================================================
// = Create the table of current tasks stored in the database =
// ============================================================
$userID = $_SESSION['userID'];
$result = mysql_query("SELECT * FROM Tasks WHERE userID = '$userID'");
echo "<div id=\"draggable\" class=\"ui-widget-content\"><table border='5'><tr class=\"ui-widget-header\"><td><u>Task Name:</u></td><td><u>Class:</u></td><td><u>Due Date:</u></td><td><u>Task Type:</u></td></tr>";
echo $_SESSION['userID'];
while($row = mysql_fetch_array($result)) {
$taskName = $row[1];
$class = $row[2];
$taskDueDate = $row[3];
$taskType = $row[4];
echo "<tr><td>'$taskName'</td><td>'$class'</td><td>'$taskDueDate'</td><td>'$taskType'</td></tr>";
}
echo "</table>";
function addNewTask ($name, $class, $dueDate, $type) {
mysql_query("INSERT INTO Tasks VALUES ('$userID','$name', '$class', '$dueDate', '$type')");
}
if($_POST['taskName'] != NULL) {
addNewTask($_POST['taskName'], $_POST['class'], $_POST['dueDate'], $_POST['dueDate']);
}
?>
<!-- <img border="1" alt="New" src="/newTask.png" id="newTask" onmouseClick="showTaskField"/> -->
<p><form name="newTask" method="post" action="index.php" id="newTask"><br>
Task Name: <input name="taskName" type="text"> (necessary)<br>
Class: <input name="class" type="text"><Br>
Due Date: <input name="dueDate" type="text" id="datepicker"><Br>
Type:
<input type="submit"></p></div>
Try getting rid of the ' around the variables in the insert statement. If that does nothing echoing mysql_error().