Entire database deletes instead of one row - javascript

I have been trying to delete a row in my mySQL database on the onclick of a delete button. But instead of the one mySQL row getting deleted, all rows in the database get deleted.
I am targeting just the specific ID, so I am unclear as to why all other ID's are getting deleted.
HTML:
<?php foreach ($movies as $movie) : ?>
<div class="col-4">
<div class="card card-cascade">
<div class="view gradient-card-header purple-gradient">
<h2><?php echo $movie['name']; ?></h2>
<p><?php echo $movie['genre']; ?></p>
</div>
<div class="card-body text-center">
<!-- Delete -->
<a type="button" class="btn-floating btn-small btn-dribbble delbutton" data-toggle="tooltip" data-placement="top" title="Delete" id="<?php echo $movie['id']; ?>"><i class="fa fa-trash-o" aria-hidden="true"></i></a>
</div>
</div>
</div>
<?php endforeach; ?>
JS:
$(function () {
// Tooltips Initialization
$('[data-toggle="tooltip"]').tooltip();
// Delete Movie
$(".delbutton").click(function() {
console.log('watch me')
var del_id = $(this).attr("id");
var info = 'id=' + del_id;
if (confirm("Sure you want to delete this post? This cannot be undone later.")) {
$.ajax({
type : "POST",
url : "../movieApp/delete.php", //URL to the delete php script
data : {id:info},
success : function() {
console.log("success");
},
error: function () {
console.log("failed");
},
});
$(this).parents(".record").animate("fast").animate({
opacity : "hide"
}, "slow");
}
return false;
});
});
PHP:
require 'config/config.php';
require 'config/db.php';
if($_POST['id']){
$id=$_POST['id'];
$delete = "DELETE FROM movies WHERE id=$id";
$result = $conn->query($delete);
}
if (mysqli_query($conn, $sql)) {
mysqli_free_result($result);
mysqli_close($conn);
echo "Worked!";
exit;
} else {
echo "Error deleting record";
}

You set ajax method POST, But Post data format is not correct as per your requirement.
Change your ajax Data like as
//var info = 'id=' + del_id;
var info = {
id : del_id
}
And
$.ajax({
/*...*/
data : info,
/*.../
});
And also check if your id field is string, If integer then change the Query string to -
#$delete = "DELETE FROM movies WHERE id='$id'";
$delete = "DELETE FROM movies WHERE id=$id";
Also change -
#$_POST['info']
$_POST['id']
Because, You didn't set $_POST['info'] anywhere in your code.
Note : And don't forget to console your correct Ajax URL

In your HTML use data-id="<?php echo $movie['id']; ?>" for the tag. Then in your JS you can pick up the value like so: var del_id = $(this).data("id");. I would also inspect element in your browser to see if you are in fact sending an "id" to your PHP script. If you are then possibly you may want to enable error debugging in your PHP script like so: error_reporting(E_ALL);
ini_set('display_errors', 1);. Also wouldn't hurt to change your SQL statement to something like this: $delete = "DELETE FROM movies WHERE id='" . $id . "'";. Good luck with this one doesn't sound too hard.

Related

parameter is missing in php jquery ajax

Sorry for disturbing again with my very basic question. First of all, sorry if my English is a little bit hard to understand. My current situation is I want to do a popup modal in my drag and drop boxes. In my popup modal, I can view and edit the details of the user based on what we click in the button in the box. The problem is, I cannot SELECT the data by id. But, when I SELECT all the data, the data appear in the modal boxes. But, it appears all the data. I just want the selected id. Back to my question for past few days, I've redo again to get more understanding on this popup modal part. I've done ajax and a little bit JavaScript, also, I tried to debug my code just what I've been told but I got an error saying "Parameter is missing" . What is causing by that ? I've done some reading about parameter but I still don't get the actual understanding about it. Can someone give an idea what is actually parameter is missing . And what I suppose to do by it?
Here what I've tried so far.
This is the button
<button data-id="<?php echo $row['userid'];?>" data-target="doubleClick-1" class='jobinfo' type='button' id='btnInfo' ondblclick="document.getElementById('doubleClick-1').style.display='block'">Info</button>
This is the modal popup
<div id="doubleClick-1" class="modal">
<label class="tabHeading">User Info</label>
<div class="contentTechJobInfo">
<div class="tech-details">
<div class="techClose" onclick="document.getElementById('doubleClick-1').style.display='none'" >&times</div>
</div>
</div>
</div>
</div>
<script type='text/javascript'>
$(document).ready(function() {
$('.jobinfo').click(function() {
var userid = $(this).data('userid');
// AJAX request
$.ajax({
url: 'ajaxhome.php',
type: 'post',
data: {userid: userid},
success: function(response) {
// Add response in Modal body
$('.tech-details').html(response);
// Display Modal
$('#doubleClick-1').modal('show');
}
});
});
});
</script>
This my ajaxhome.php
<?php
$connection = mysqli_connect("", "", "");
$db = mysqli_select_db($connection, '');
if (!isset($_GET['userid'])) {
die("Parameter is missing!");
}
$userid = intval($_GET['userid']);
$query = "SELECT * FROM user WHERE userid ='$userid'";
$query_run = mysqli_query($connection, $query);
if ($query_run) {
while ($row = mysqli_fetch_array($query_run)) {
?>
<div class="input-box">
<label for="">Name</label>
<input type="text" id="username" name="username" value="<?php echo $row['username']?>">
</div>
<div class="input-box">
<label for="">Number</label>
<input type="text" id="usernumber" name="usernumber" value="<?php echo $row['usernumber']?>">
</div>
<div class="input-box">
<label for="">Class</label>
<input type="text" id="userclass" name="userclass" value="<?php echo $row['userclass']?>">
</div>
<button type="submit" id="submit" name="update" class="btn btn-primary"> Update Data </button>
<?php
if (isset($_POST['update'])) {
$username = $_POST['username'];
$usernumber = $_POST['usernumber'];
$userclass = $_POST['userclass'];
$query = "UPDATE user SET username='$username', usernumber='$usernumber', userclass='$userclass' WHERE userid='$userid'";
$query_run = mysqli_query($connection, $query);
if ($query_run) {
echo '<script> alert("Data Updated"); </script>';
header("location:homepage.php");
} else {
echo '<script> alert("Data Not Updated"); </script>';
}
}
} ?>
<?php
}
?>
In short, I think the problem comes from these lines of code in your modal:
var userid = $(this).data('userid');
you should replace it with
var userid = $(this).data('id'); // you should pass 'id' to .data() function instead of 'userid'
With your current code userid variable in your modal will always be undefined. It means it wont exist in $_GET when you send ajax request to PHP. And it causes your ajaxhome.php moves to die("Parameter is missing!");.
To get data-xxx attribute with jQuery, you should use pass 'xxx' to .data() function.
var xxx = $(this).data('xxx');
In your button, you are storing userid in data-id attribute
<button data-id="<?php echo $row['userid'];?>"
so if you need to get that userid you should pass 'id' into .data() function
Update:
In your ajax, you are using type: 'post', so in your php code you should check $_POST instead of $_GET
I don't think the value of user has been obtained
var userid = $(this).data('userid');
you can try
var userid = $(this).data('id');

Button for Updating a Database single entry with PHP AJAX Call

For Future Readers, this was my first question and the answer has been found (read comments and replies below):
First of all, i've searched in Stackoverflow and i didn't found an answer for a similar problem.
i would like to link a html Button (among many buttons) with a JQuery function. The function shall execute AJAX method like so :
HTML Code in a separated file index.php:
<button id="submitbtn" type="button" class="btn btn-success">UPDATE</button>
JQuery Function :
$('#submitbtn').on('click', function(){
var id = $(this).data('id');
$.ajax({
url: 'includes/updatequery.php',
type: 'POST',
data: {id:id},
success: function(data){
if (data) {
console.log("updated");
} else {
$('#error').load("custom/static/error.html");
}
},
error: function(jqXHR, textStatus, errorThrown){
$('#error').html("oops" + errorThrown);
}
});
});
Here is the PHP file that should be called by AJAX Method :
<?php
include("src/db.php");
$query = "UPDATE mytable SET job='completed' WHERE id=id";
mysqli_query($conn, $query);
?>
The problem is that i CANNOT link the ID of the clicked button (because there are many buttons) to the ID of the Database Entry in order to update the Data in the Database according to this specific button.
Now i would like to have the results updated LIVE after updating the Database.
This is the PHP code that output menu items (items stored in the same Database table as before) and in front of every menu item, a badge should be displayed (with a value within it : "completed" or "not completed") :
<?php
foreach($data as $d) {
$id = $d['id'];
$mystatus = $d['status'];
?>
<li class="nav-item">
<a class="nav-link clickable blueMenuItem" id="nav-location" data-id="<?php echo $d['id']; ?>">
<i class="nav-icon fas <?php echo $d['icon']; ?>"></i>
<p><?php
echo $d["title"];
if ($d['type'] == "job") { ?>
<span id="updatedicon" class="right badge <?php if($mystatus == "completed"){echo "badge-success";} else {echo "badge-danger";}?>"><?php setJob($con, $id)?></span><?php
} ?>
</p>
</a>
</li><?php
}
?>
Here is the PHP file where the setJob method is defined :
<?php
function setJob($con, $idd) {
$sql = "SELECT status FROM mytable WHERE id=$id";
$result = mysqli_query($con, $sql);
while ($row = mysqli_fetch_assoc($result)) {
foreach ($row as $row => $value) {
echo $value;
}
}
}
?>
Any suggestions?
Thanks
Use the data-id attribute to add the id:
<button id="submitbtn" data-id="<id>" type="button" class="btn btn-success">UPDATE</button>
https://www.w3schools.com/tags/att_global_data.asp
By default, jQuery ajax uses a Content-Type of application/x-www-form-urlencoded; charset=UTF-8. This means in PHP the POST values can be accessed using $_POST. If using a Content-Type of application/json, you will need to do this.
include("src/db.php");
$id = $_POST['id']; // make sure to sanitize this value
$query = "UPDATE mytable SET job='completed' WHERE id=$id";
mysqli_query($conn, $query);
The above example only demonstrates how to reference the id value from the POST. However, this is not secure as-is. Make sure to sanitize the value as well as protect yourself from SQL Injection using prepared statements. Prepared Statements allow you to bind variables to SQL queries which are sent separately to the database server and can not interfere with the query itself.
Updated HTML - added data-id="" to button and replace with id
<button id="submitbtn" data-id="<id>" type="button" class="btn btn-success">UPDATE</button>
Updated jQuery - use attr to get the id of row/record by using data-id attribute
$('#submitbtn').on('click', function(){
var id = $(this).attr('data-id');
$.ajax({
url: 'includes/updatequery.php',
type: 'POST',
data: {id:id},
success: function(data){
if (data) {
console.log("updated");
} else {
$('#error').load("custom/static/error.html");
}
},
error: function(jqXHR, textStatus, errorThrown){
$('#error').html("oops" + errorThrown);
}
});
});

Delete a table row with dynamic id that comes from DB using ajax

I have a table that it's content is comes from database.When I click on the delete button I want to delete that row with Ajax. Actually right now it's working but with a bug and that is all of the rows get deleted when I click on the button and then if I refresh , the row that I was deleted is gone and other rows are shown.But as I said it needs a refresh.Any solution would be appreciated .
$('.dashboard-subscribe-form').submit(() => {
event.preventDefault();
const currentHiddBtn = $('.dash-subscribe-form-btn');
console.log(currentHiddBtn.closest('tr'));
const userCaution = confirm('Want to delete this quote?');
if (userCaution) { //If admin insists to delete the row
const deleteId = $('.dash-subscribe-form-btn').attr('value');
$.ajax({
type: "POST",
url: "delete-subscribe.php",
dataType: "json",
data: {
deleteId: deleteId
},
success: (data) => {
if (data.code === '200') {
console.log('It works!');
currentHiddBtn.closest('tr').css('background', 'tomato');
currentHiddBtn.closest('tr').fadeOut(1200, () => {
});
} else if (data.code === '404') {
alert('An error occurred!Please try again.');
}
}
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<tbody>
<?php
$count = 1;
$sqlCommand = "SELECT * FROM `kq0b3_subscribe`";
$sqlCommandPrepare = $pdoObject->prepare($sqlCommand);
$sqlCommandPrepare->execute();
while ($result = $sqlCommandPrepare->fetch()) {
?>
<tr id="row-<?php echo $result['id']; ?>">
<td class="dashboard-records">
<?php echo $count; ?>
</td>
<td class="dashboard-records">
<?php echo $result['email']; ?>
</td>
<td>
<form action="" method="post" class="dashboard-subscribe-form">
<input id="<?php echo $result['id']; ?>" type="hidden" class="dash-subscribe-form-btn" name="hidden-del" value='<?php echo $result[' id ']; ?>'/>
<button type="submit" name="sub-del-btn" class="btn btn-danger del" value='<?php echo $result[' id ']; ?>'> Delete
</button>
</form>
</td>
</tr>
<?php
$count++;
}
?>
</tbody>
delete-subscribe.php:
<?php
require_once('config.php');
$delete_row = $_POST['deleteId'];
if($delete_row){
$sqlCommand = "DELETE FROM `kq0b3_subscribe` WHERE `id` = ?";
$sqlCommandPrepare = $pdoObject->prepare($sqlCommand);
$result = $sqlCommandPrepare->execute([
$delete_row
]);
/*The json_encode() must be after all of our calculation codes and DB query codes and...(It must be the
last line of code) */
echo json_encode(['code' => '200'], JSON_THROW_ON_ERROR, 512);
}
else {
echo json_encode(['code' => '404'], JSON_THROW_ON_ERROR, 512);
}
UPDATE2: now I'm using :
$('#row-' + deleteId).css('background', 'tomato');
$('#row-' + deleteId).fadeOut(1200, () => {
});
but the new problem is : it doesn't matter which button I click, the forst row is deleted (when any button is clicked , in the console , the id of the first row-button is printed , not the actual id that I was clicked. ).How can I fix this one?
I think the main issue, in this case, is using CSS classes as a selector and it seems to be selecting the first instance no matter which item you are clicking.
The code causing this is:
const deleteId = $('.dash-subscribe-form-btn').attr('value');
You want to be getting the target input from the event object passed from your .submit().
I have created a jsfiddle with an example that could be adapted to your code but here is a quick preview of jQuery part.
$('.dashboard-subscribe-form').submit((event) => {
event.preventDefault()
console.log(event.target.elements[0]["value"])
$('#result-from-click').html("Input Value: " + event.target.elements[0]["value"])
})
It is selecting the first element within the elements array which is the input. If you want the button you can use event.target.elements[1]
You could then also use the value returned to remove the <tr> with the same id instead of finding the nearest. This could be done in the success part of your ajax call without doing a refresh.

Using Ajax to create session and echo results

I'm trying my best to get this to work. But AJAX is pretty new to me. So hang in there...
Ok, I've asked a couple of questions here about getting this issue that I'm having to work. I (We)'ve come a long way. But now the next issue is here.
I'm trying to echo a session in a div using AJAX.
The AJAX code is working, I can echo plain text to the div I want it to go. The only problem I have is it does not display the title of the item.
I have some items (lets say 3 for this example) and I would like to have the custom save the Items in a Session. So when the customer clicks on save. The ajax div displays the title. And if the custom clicks the 3rd item it show the 1st and 3rd item, etc...
My HTML:
<button type="submit" class="btn btn-primary text-right" data-toggle="modal" data-target=".post-<?php the_ID(); ?>" data-attribute="<?php the_title(); ?>" data-whatever="<?php the_title(); ?>">Sla deze boot op <span class="glyphicon glyphicon-heart" aria-hidden="true"></span></button>
My AJAX code:
$(".ajaxform").submit(function(event){
event.preventDefault();
$.ajax({
type: "POST",
url: "example.com/reload.php",
success: function(data) {
$(".txtHint").html(data);
},
error: function() {
alert('Not OKay');
}
});
return false;
});
My PHP reload.php:
<h4>Saved Items</h4>
<p>Blaat...</p>
<?php echo "Product Name = ". $_SESSION['item'];?>
I saw this code on here: I'm not using this code. Only wondering if I can use it for my code, and then how?
Change session.php to this:
<?php
session_start();
// store session data
$_SESSION['productName'] = $_POST['productName'];
//retrieve session data
echo "Product Name = ". $_SESSION['productName'];
?>
And in your HTML code:
function addCart(){
var brandName = $('iframe').contents().find('.section01a h2').text();
$.post("sessions.php", {"name": brandName}, function(results) {
$('#SOME-ELEMENT').html(results);
});
}
How I'm getting my title();:
<?php
// Set session variables
$_SESSION["item"][] = get_the_title();
?>
Is this some thing I can use? And could someone help me with the code?
Thanks in advance!
I'm not too sure on what exactly you're trying to accomplish, but here's a quick and dirty example of making an HTTP request (POST) with a name of a product, storing it in a PHP session, and outputting all product names in the session:
HTML
<p>Product A <button class="add-product" data-product="Product A">Add Product</button></p>
<p>Product B <button class="add-product" data-product="Product B">Add Product</button></p>
<p>Product C <button class="add-product" data-product="Product C">Add Product</button></p>
<div id="response">
</div>
JavaScript
$('.add-product').click(function() {
var productName = $(this).data('product');
$.post('addProduct.php', {productName: productName}, function(data) {
$('#response').html(data);
})
});
PHP (addProduct.php)
<?php
session_start();
if (!array_key_exists('products', $_SESSION) || !is_array($_SESSION['products'])) {
$_SESSION['products'] = [];
}
$productName = array_key_exists('productName', $_POST) ? (string) $_POST['productName'] : '';
if ($productName) {
$_SESSION['products'][] = $productName;
}
?>
<h4>Your added products:</h4>
<ul>
<?php foreach ($_SESSION['products'] as $product): ?>
<li><?php echo htmlspecialchars($product); ?></li>
<?php endforeach;?>
</ul>

inline update in mysql using jquery/php

I'm performing CRUD oprations using JQuery/Ajax and php/MySQL
i'm able to insert/select and delete data but i gotta stuck in edit/update. im pulling data into text box when i click on edit button but after editing when i click on save button unable to update in mysql db!!
Any help is Appreciated Thanks
html code
<span class="noedit name" idl='<?php echo $row->id;?>'>
<?php echo $row->url;?>
</span>
<input id="url1" name="url1" class="form-control edit name url1" value="<?php echo $row->id;?>"/>
<a ide='<?php echo $row->id;?>' id="edit" class='editOrder' href="#" style="display:block-inline;">EDIT</a>
<a idu='<?php echo $row->id;?>' id="update" class='update saveEdit' href='#' style='display:none;'>SAVE</a>
<a idc='<?php echo $row->id;?>' id="cancel" class='cancelEdit edit' href='#' style='display:none;'>CANCEL</a>
Jquery code
$('body').delegate('.edit','click',function(){
var IdEdit = $(this).attr('ide');
alert(IdEdit);
$.ajax({
url:"pages/feeds.php",
type:"post",
data:{
editvalue:1,
id:IdEdit
},
success:function(show)
{
$('#id').val(show.id);
$('#url1').val(show.url);
}
});
});
$('.update').click(function(){
var id = $('#id').val()-0;
var urls = $('#url1').val();
$.ajax({
url:"pages/feeds.php",
type:"post",
async:false,
data:{
update:1,
id:id,
upurls:urls
},
success:function(up)
{
$('input[type=text]').val('');
showdata();
},
error:function(){
alert('error in updating');
}
});
});
PHP Code
if(isset($_POST['editvalue']))
{
$sql = "select * from test where id='{$_POST['id']}'";
$row = mysql_query($sql);
$rows = mysql_fetch_object($row);
header("Content-type:text/x-json");
echo json_encode($rows);
exit();
}
if(isset($_POST['update']))
{
$sql = "
update test
set
url='{$_POST['upurls']}'
where id='{$_POST['id']}'
";
$result = mysql_query($sql);
if($result)
{
//alert('success');
echo 'updated successfully';
}
else
{
//alert('failed');
echo 'failed to update';
}
}
I don't see an #id input in your code. is it there? I think the problem is here.
If this input exists, use the following tips:
Check if all values (id, url) are sended to your PHP script.
You can use console.log in Javascript or print_r, var_dump functions in PHP.
Change
$('.update').click(function(){
to
$('.saveEdit').click(function(){

Categories

Resources