I want to insert a "remove" button in each of these divs, so that the database's row and the div can be deleted using the remove button.
Number of divs vary according to the number of rows in the database.
It should appear as follows,
Showing data works just fine. But, delete (remove button) doesn't work.
PHP
function deleteUser($connection, $userID){ // this function calls within the "currentUsers" Function
$sql2 = "DELETE FROM users_table WHERE user_id = '$userID' ";
if (mysqli_query($connection, $sql2)) {
header("Location: main.php");
} else {
echo "Error! ";
}
}
function currentUsers($connection){
$sql1 = "SELECT * FROM users_table ";
$result1 = mysqli_query($connection, $sql1);
if(mysqli_num_rows($result1) > 0){
while($row = mysqli_fetch_assoc($result1)) {
$userID = $row['user_id'];
$name = $row['name'];
$country = $row['country'];
echo '<div>
<h3>'. $userID. " ". $name. " ". $country. '</h3>
<input type = "button" name = "removeButton" value = "Remove" method = "GET">
</div>';
if (isset($_GET['removeButton'])) {
deleteUser($connection, $userID);
}
}
}else{
echo "Currently there are no users!";
}
mysqli_close($connection);
}
currentUsers($connection);
?>
As the discussion from the comment, The following codes given.
Updated HTML:
<input type="button" name="removeButton" value="Remove" class="removeBtn">
Javascript:
var userID = "<?php echo $userID;?>";
$(".removeBtn").on("click", function(){
$.post("page.php", { userID : userID}, function(result){
if(result == "Success") window.location.href = "main.php";
else alert(result);
});
});
page.php
//need the database connection
$userID = $_POST['userID'];
$sql2 = "DELETE FROM users_table WHERE user_id = '$userID' ";
if (mysqli_query($connection, $sql2)) {
echo 'Success';
} else {
echo "Error! ";
}
If you want to remove the total div as well with the database field then use:
Javascript:
var userID = "<?php echo $userID;?>";
$(".removeBtn").on("click", function(){
var __this = $(this);
$.post("page.php", { userID : userID}, function(result){
if(result == "Success"){
__this.closest("div").remove();
window.location.href = "main.php";
}
else alert(result);
});
});
If you want to pass your $userID in each input then use:
<input data-userid = <?php echo $userID;?> type="button" name="removeButton" value="Remove" class="removeBtn">
Javascript
$(".removeBtn").on("click", function(){
var __this = $(this);
var userID = __this.attr("data-userid");
$.post("page.php", { userID : userID}, function(result){
if(result == "Success"){
__this.closest("div").remove();
window.location.href = "main.php";
}
else alert(result);
});
});
This is just an answer of your question, but you have to use this as you want. This may help you, try and let me know what happens.
The remove button doesnt work because you never get into deleteUser() method.
You cant just write
<input type = "button" name = "removeButton" value = "Remove" method = "GET">
as it was inside a form. For it to trigger, write it like this:
<form method="GET">
<input type = "submit" name = "removeButton" value = "<?php echo $userID;?>">
</form>
Then, when calling
deleteUser($connection, $_GET['removeButton']);
Hope this helps.
<?php
$connection = mysqli_connect('localhost', 'root', '', 'users');
function deleteUser($connection, $userID){ // this function calls within the "currentUsers" Function
$sql2 = "DELETE FROM users_table WHERE id = '$userID' ";
if (mysqli_query($connection, $sql2)) {
header("Location: main.php");
} else {
echo "Error! ";
}
}
function currentUsers($connection){
$sql1 = "SELECT * FROM maps ";
$result1 = mysqli_query($connection, $sql1);
if(mysqli_num_rows($result1) > 0){
while($row = mysqli_fetch_assoc($result1)) {
$userID = $row['id'];
$name = $row['name'];
$country = $row['country'];
echo '<div>
<h3>'. $userID. " ". $name. " ". $country. '</h3>
</div>';
}
}else{
echo "Currently there are no users!";
}
mysqli_close($connection);
}
if (isset($_GET['removeButton']))
{
deleteUser($connection, $_GET['removeButton']);
}
currentUsers($connection);
?>
Related
I have 2 functions in 1 php file, one for upvote and 1 for downvote. How to tell ajax to post to the function with name upvoteImage()? I'm literally starting out with ajax so I'm having some troubles figuring things out.
Javascript file
$('.arrowUp').click(function(){
var id = $("input[name='id']").val();
var userId = $("input[name='userId']").val();
$.post('../includes/voting.inc.php', {id: id, userId: userId}, function(data){
alert(data);
});
});
PHP file
function upvoteImage($conn) {
if (isset($_POST['upvoteImage'])){
$imageId = $_POST['id'];
$userId = $_POST['userId'];
$sql3 = "SELECT * FROM votingconnection WHERE userId='".$userId."' and imageId='".$imageId."'";
$result3 = mysqli_query($conn, $sql3);
$getResult3 = mysqli_fetch_assoc($result3);
if ($getResult3['vote'] == 'downvote') {
$sql4 = "UPDATE votingconnection SET vote='upvote' WHERE userId='".$userId."' and imageId='".$imageId."'";
$result4 = mysqli_query($conn, $sql4);
$sql5 = "UPDATE image SET upvotes = upvotes + 1 WHERE id='$imageId'";
$result5 = mysqli_query($conn, $sql5);
$sql6 = "UPDATE image SET downvotes = downvotes - 1 WHERE id='$imageId'";
$result6 = mysqli_query($conn, $sql6);
header("Location: ../index.php");
} else {
$sql = "INSERT INTO votingconnection (userId, imageId, vote) VALUES ('".$userId."','".$imageId."', 'upvote')";
$result = mysqli_query($conn, $sql);
$sql2 = "UPDATE image SET upvotes = upvotes + 1 WHERE id='$imageId'";
$result2 = mysqli_query($conn, $sql2);
header("Location: ../index.php");
}
}
}
I just can't understand how to connect the index page, the page with the logic for upvote/downvote and the javascript page. This is part of my index page.
<?php
if (isset($_POST['action']) && in_array($_POST['action'], ['upvote', 'downvote'])) {
if ($_POST['action'] == 'upvote' ) {
upvoteImage($conn);
} else {
downvoteImage($conn);
}
}
$currentUser = $_SESSION['id'];
$sql = "SELECT * FROM image";
$result = mysqli_query($conn, $sql);
$getResult = mysqli_fetch_assoc($result);
$numberOfResults = mysqli_num_rows($result);
$resultsPerPage = 5;
$numberOfPages = ceil($numberOfResults/$resultsPerPage);
if (!isset($_GET['page'])) {
$page = 1;
} else {
$page = $_GET['page'];
}
$currentPageResults = ($page-1)*$resultsPerPage;
$sql2 = "SELECT * FROM image ORDER BY id DESC LIMIT ".$currentPageResults.','.$resultsPerPage;
$result2 = mysqli_query($conn, $sql2);
while($row = $result2->fetch_assoc()) {
$sql3 = "SELECT * FROM votingconnection WHERE userId='".$currentUser."' and imageId='".$row['id']."'";
$result3 = mysqli_query($conn, $sql3);
$getResult3 = mysqli_fetch_assoc($result3);
$hasVoted = mysqli_num_rows($result3);
$vote = $getResult3['vote'];
echo "<div class='imageContainer'>"
."<h1>".$row["name"].'</h1>'
.'<div class="stickyImageContainer"><img class="uploadedImg" src="uploads/'.$row["path"] .'" alt="Random image" /> ';
if (isset($_SESSION['id'])) {
if ($hasVoted < 1) {
echo "<div class='upvoteDownvoteRatingContainer'><form class='upvoteImage' method='POST' action=''>
<input type='hidden' name='action' value='upvote'>
<input type='hidden' name='id' value='".$row['id']."'>
<input type='hidden' name='userId' value='".$currentUser."'>
<button class='upvoteImageButton' type='submit' name='upvoteImage'><img class='arrowUp' src='../images/Social Media/arrowUp.png' alt='submit'></button>
</form>";
echo "<div class='ratingNumber'>";
if ($row['upvotes'] - $row['downvotes'] <= 0) {
echo "<p>0</p>";
} else {
echo $row['upvotes'] - $row['downvotes'];
}
echo "</div>";
echo "<form class='downvoteImage' method='POST' action=''>
<input type='hidden' name='action' value='downvote'>
<input type='hidden' name='id' value='".$row['id']."'>
<input type='hidden' name='userId' value='".$currentUser."'>
<button class='downvoteImageButton' type='submit' name='downvoteImage'><img class='arrowDown' src='../images/Social Media/arrowDown.png' alt='submit'></button>
</form></div>";
}
Ajax is not "posting to a function", it's only a way to request a page from the server.
The code in your page is the one that should decide what to do, so basically you can just call the function in your page:
function upvoteImage() {
....
}
upvoteImage()
Of check the data you got from the client, and based on that data - run the relevant function:
function upvoteImage() {
....
}
if ($_POST['do_upvote']) {
upvoteImage()
}
You could call functions by sending post data with some tag like "type:"upvote" or "type:"downvote" and in php, call the function upvoteImage or doenVoteImage according to the tag.
You don't tell ajax to post to a function specifically. Instead tell ajax to post to a file specifically.
$('.arrowUp').click(function(){
var id = $("input[name='id']").val();
var userId = $("input[name='userId']").val();
$.post('../includes/upvote.inc.php', {id: id, userId: userId}, function(data){
alert(data);
});
});
$('.arrowDown').click(function(){
var id = $("input[name='id']").val();
var userId = $("input[name='userId']").val();
$.post('../includes/downvote.inc.php', {id: id, userId: userId}, function(data){
alert(data);
});
});
One for handling the upvote, and the other the downvote.
Either send the preferred action(upvote or downvote) along with the query part of the URL, or send a separate action data(upvote or downvote) along with id and userId.
Method(1):
// for downvote, URL would be ../includes/voting.inc.php?action=downvote
$.post('../includes/voting.inc.php?action=upvote', {id: id, userId: userId}, function(data){
alert(data);
});
And process the request in voting.inc.php page the following way,
if($_GET['action'] == "upvote"){
// call upvoteImage function
}else if($_GET['action'] == "downvote"){
// call downvoteImage function
}
Method(2):
// for downvote, {id: id, userId: userId, action: 'downvote'}
$.post('../includes/voting.inc.php', {id: id, userId: userId, action: 'upvote'}, function(data){
alert(data);
});
And process the request in voting.inc.php page the following way,
if($_POST['action'] == "upvote"){
// call upvoteImage function
}else if($_POST['action'] == "downvote"){
// call downvoteImage function
}
You can simply do this via data-* attribute and make your voting buttons like this
<button class="vote" data-type="up" data-id="1" data-user-id="2">Up</button>
<button class="vote" data-type="down" data-id="1" data-user-id="2">Down</button>
then you can simply send the ajax request like this
$('.vote').click(function() {
var data = {
id: $(this).data('id'),
userId: $(this).data('user-id'),
type: $(this).data('type')
};
$.post('../includes/voting.inc.php', data, function(data){
alert(data);
});
});
Finally, in your server side you can check the type and call functions
if (isset($_POST['type']) && $_POST['type'] == "up"){
// Call upvote function here
}
else if (isset($_POST['type']) && $_POST['type'] == "down"){
// Call downvote function here
}
else {
// Abort if invalid
}
I am trying to work out why my alert in the 'function processResponse(data)' part of the code, is not being displayed. I have tried various return; options, but still, refuses to display.
I would be grateful if someone could point out my error. Many thanks.
PS. I am aware of security issues in the code posted such as mysql_escape_string, but all security issues will be inserted before the site goes live.
jQuery code
<script type="text/javascript">
$(function() {
$('#srcsubmit').click(function(e) {
e.preventDefault();
if ($('#srcBox').val() == '') {
notif({
type: "error",
msg: "<b>ERROR:<br /><br />You must enter a search term</b><p>Click anywhere to close</p>",
height: 99,
multiline: true,
position: "middle,center",
fade: true,
timeout: 3000
});
return false;
}
$("#submit").prop("disabled", true);
$("#submit2").prop("disabled", true);
$("#submit3").prop("disabled", true);
var value = $('#srcBox').val();
var dept = '<?php echo $_GET['dept ']; ?>';
var qString = 'sub=' + encodeURIComponent(value) + '&dept=' + encodeURIComponent(dept);
$.post('sub_db_handler.php', qString, processResponse);
});
function processResponse(data) {
if (data === 'true') {
alert('That box is not on the system'); <--- this is the problem
return;
}
$('#srcBoxRslt').val(data);
};
});
</script>
PHP backend
<?php session_start(); ?>
<?php
$con = mysql_connect("localhost","root","");
if(!$con) { die('Could not connect: ' . mysql_error()); }
mysql_select_db("sample", $con);
$dept = trim($_POST['dept']);
$custref = trim($_POST['sub']);
$result = mysql_query("SELECT * FROM boxes WHERE custref = '".$custref."'");
$found = mysql_num_rows($result);
if ($found == 0)
{
echo trim('true');
} else {
$query = "SELECT * FROM boxes WHERE department = '".$dept."' AND status = 1 AND custref = '".$custref."'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result) or die(mysql_error());
$r = $row['custref'];
$str = json_encode($r);
echo trim($str, '"');
}
?>
The data value is not equal to true because of extra space to get rid of extra use .trim()
This question already has answers here:
Make jQuery AJAX Call to Specific PHP Functions
(3 answers)
Closed 6 years ago.
I've read all the topics about my question but cannot solve my problem. I want to get php function result using jQuery AJAX.
function fetch_select(){
val_name = $('#name').val();
$.ajax({
type: 'POST',
url: 'include/get_db.inc.php',
data: {
name: val_name,
},
success: function (response) {
document.getElementById('higtchart_medie_gen').innerHTML=response;
columnChart( JSON.parse(response));
}
});
}
function columnChart(data_v){
if(data_v.length >0){
$(function () {
$('#higtchart_medie_gen').highcharts({
chart: {
type: 'column'
},
......
#name is id for select tag.
My code for get_db.inc.php is:
<?php
function test_name () {
$ret = [];
if(isset($_POST['name'])){
$name = $_POST['name'];
$sql = "SELECT
......
WHERE ID = $name ";
$result = $conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()) {
$ret [] = [$row['NAME'] . ' ' . $row['LASTN'], floatval($row['AVGG'])];
}
}
}
if(count($ret) >1) echo json_encode($ret);
else echo 'Not working';
}
?>
How can I call test_name function from Ajax code?
Thank you very much!
You do almost correct but only one mistake is you forget to invoke the function. What you do is just send the data to this file.
So, to fixed this. Just add test_name() to your get_db.inc.php
<?php
function test_name () {
$ret = [];
if(isset($_POST['name'])){
$name = $_POST['name'];
$sql = "SELECT
......
WHERE ID = $name ";
$result = $conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()) {
$ret [] = [$row['NAME'] . ' ' . $row['LASTN'],floatval($row['AVGG'])];
}
}
}
if(count($ret) >1) echo json_encode($ret);
else echo 'Not working';
}
test_name()
?>
Also it will be better to check isset outside the function.
function test_name ($name) {
$ret = [];
$sql = "SELECT
......
WHERE ID = $name ";
$result = $conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()) {
$ret [] = [$row['NAME'] . ' ' . $row['LASTN'],floatval($row['AVGG'])];
}
}
if(count($ret) >1) echo json_encode($ret);
else echo 'Not working';
}
if(isset($_POST['name'])){
test_name($_POST['name'])
}
This will make your function to be pure. It will easier to debug later and it will not invoke if you don't have $_POST['name'].
Please see the scripts below. Onclick of Add gives an error when a php variable ($var)is used, however it will work with a number - i.e. if the line in index.php:
echo '<button id="1" onclick="company_add(\''.$var.'\');">Add</button>';
Is changed to something like:
echo '<button id="1" onclick="company_add(',57776,');">Add</button>';
What am I missing please?
Index.php:
<html>
<head>
<script type ="text/javascript">
function company_add(company_name) {
$.post('company_add.php', {company_name:company_name}, function(data) {
if (data == 'success'){
alert("Cool");
} else{
alert(data);
}
});
}
</script>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<?php
include 'connect.php'; //Generic connect file
$var = 'Name';
echo '<button id="1" onclick="company_add(\''.$var.'\');">Add</button>
<br/>';
?>
</body>
</html>
company_add.php:
<?php
include 'connect.php';
function company_exists($company_name) {
return (mysql_result(mysql_query("SELECT COUNT(`company_name`) FROM
`company` WHERE `company_name` = $company_name"), 0) == 0 ) ? false :
true;
}
function add_company($company_name){
mysql_query("INSERT INTO `company` (`id`, `company_name`) values ('',
".$company_name.")");
}
$company_name = $_POST['company_name'];
if (company_exists($company_name) === true) {
echo 'Company already added';
} else {
add_company($company_name);
echo 'success';
}
?>
Use that line like this:
echo "<button id='1' onclick='company_add('" . $var . "');'>Add</button>";
In case if you already have commas after and before the value of the $var you should trim it.
So use it like this:
$var = ltrim(",", $var);
$var = rtrim(", ", $var);
echo "<button id='1' onclick='company_add('" . $var . "');'>Add</button>";
And for your information yes you can even use a String instead of a Number too.
And UPDATE the functions:
function company_exists($company_name) {
$company_name = mysql_real_escape_string($company_name);
$query = "SELECT * FROM company WHERE company_name = '{$company}'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0) {
return true;
}else{
return false;
}
}
function add_company($company_name){
$company_name = mysql_real_escape_string($company_name);
$query = "INSERT INTO company (id, company_name) VALUES ('', '{$company_name}')";
return mysql_query($query);
}
If you are using id field of that company table as AUTO_INCREMENT then you can leave the id field NAME & VALUE in the INSERT Statement.
Like This in the add_company Function:
$query = "INSERT INTO company (company_name) VALUES ('{$company_name}')"
I want to add comment on pressing enter and want to store it to my database with the specific t_id for it so that i can show it on the page after submission but when i enter text and press enter it does nothing.and i am also suspicious about my add_comment.php fule query because t_id is forgien key in comments table and primary in topics i am at very beginer level in jquery,php and ajax...Any Help will be appreciated.
Here is my Jquery From Send.php
$(document).ready(function(){
$('a').on('click',function(e){
$('#Comments').html('<textarea id="D_Comment" name="D_Comment"></textarea>');
$('a').on('input',function(ev){
$('#Enter_Comments').on('click',function(event){
var d_comnt = $('#D_Comment').val();
if (event.which == 13) {
alert("You Hit Enter");
e.preventDefault();
$.ajax({
url : "ajax/add_comment.php",
type : "POST",
data : {D_Comment : d_comnt},
success : function(data){
console.log(data);
},
error : function(data){
alert(data);
}
});
}
});
// ev.preventDefault();
// return false;
});
//e.preventDefault();
return false;
});
});
and my html from send.php on same page with php showing post from database
<section id="Main_Content">
<?php
mysql_connect("localhost","root","") or die("Could not coonnect");
mysql_select_db("forum") or die("could not select db");
$last_id = mysql_real_escape_string($_GET['t_id']);
$sql = "SELECT * FROM Topics WHERE t_id = '".$last_id."'";
$query = mysql_query($sql);
$row = mysql_fetch_assoc($query);
echo "<article>";
// echo $row['t_id'];
echo "<h2>".$row['name']."</h2>"."<br/>";
//echo "<a href='#'>".$row['date']."</a>";
// echo "<a href='#'>".$row['date']."</a>";
echo "<p> Posted on ".$row['date']."</p>"."<br/>" ;
echo "<p>".$row['detail']."</p>"."<br/>" ;
echo "<a href='t_id=".$row['t_id']."' id='Enter_Comments'>"."Enter Comment". "</a>";
echo "</article>";
?>
<div id="Comments"></div>
</section>
and my add_comment.php fiel is
<?php
mysql_connect("localhost","root","") or die("Could not coonnect");
mysql_select_db("forum") or die("could not select db");
$d_cmnt = mysql_real_escape_string($_POST['D_Comment']);
$t_id = mysql_real_escape_string($_GET['t_id']);
$sql = "INSERT INTO comments (comment,t_id,date) VALUES('$d_cmnt','$t_id',Now())";
$query = mysql_query($sql);
if ($query) {
echo "Success";
}
else{
echo "Error";
}
?>