jQuery onclick delete row from mysql table - javascript

I wrote a function to delete an item from cart; the success message flash, but the item is not getting deleted. There's no error message being flagged in the console. However I think my query is wrong.
cart.php
<form id='updateCartForm' action="update_cart.php" method="get">
<input name="cart_item_id" type = "hidden" id ="cart_item_id" value='<?=$product['id'];?>'>
</form>
<button class="btn btn-warning" onclick='update_cart(); return false;'>&times</button>
footer.php
function update_cart(){
jQuery('#updateCartErrors').html("");
var cart_item_id = jQuery('#cart_item_id').val();
var error = ' ';
var data = jQuery('#updateCartForm').serialize();
jQuery.ajax({
url : '/ecommerce/customer/parsers/update_cart.php ',
method: 'get',
data : data,
success : function (){
location.reload();
},
error : function(){alert("Something went wrong");}
});
}
update_cart.php
<?php
ob_start();
require_once $_SERVER['DOCUMENT_ROOT'].'/ecommerce/core/init.php';
$cart_item_id = $_GET['cart_item_id'];
$sql = "DELETE FROM cart WHERE id = $cart_item_id" ;
//flash success message
$domain =($_SERVER['HTTP_HOST'] != 'localhost')?'.'.$_SERVER['HTTP_HOST']:false;
$_SESSION['success_flash'] = $product['prod_name']. ' was deleted from your cart.';

Please update code as given below and try :
$sql = "DELETE FROM cart WHERE id =" . $cart_item_id; // update this
$db->query($sql); //add this new line in code.
If any confusion please let me ask.
Thanks...

Can you try this?
I think you need to append value instead.
$sql = "DELETE FROM cart WHERE id =".$cart_item_id;

Related

Ajax request : get text from database and display in div

My goal is to perform an AJAX request when clicking on a button to retrieve "name" and "story" stored in my database. Each button will get info of another hero.
I'm working on multiple files.
With my current code (which is the closer to what seems to be correct in my mind) the switchHeroInfo will always change the text to "TestName" and "StoryName" instead of "Gertrude" "An old lady"(stored in database).
Can you enlight me on what may be the cause of my struggles?
the php file for connecting to database : connect_database.php
<?php
try
{
$bdd = new PDO('mysql:host=localhost;dbname=biomass;charset=utf8', 'root', '', array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
}
catch(Exception $e)
{
die('Error : '.$e->getMessage());
}
?>
The Javascript part :
$(document).ready(function()
{
$(".hero_portrait").click(function()
{
var index = $(this).data("id");
$.ajax(
{
type: "POST",
url: "../php/get_data.php",
data: {newIndex:index},
success: function(data)
{
// Display {"nick":"Gertrude","0":"Gertrude","story":"Vieille folle senile","1":"Vieille folle senile"}
alert(data);
//Display : undefined
alert(data.story);
$("#hero_name").html(data.nick);
$("#hero_story").html(data.story);
},
error: function()
{
alert("Request failure");
}
});
});
});
The php file : get_data.php
<?php
$tempValue = $_POST['newIndex'];
$sql = $bdd->prepare('SELECT * FROM heroes WHERE ID = :indexValue');
$sql->bindParam(":indexValue", $tempValue, PDO::PARAM_STR);
$sql->execute();
while($data = $sql->fetch())
{
?>
<script>
$heroNameTemp = <?php echo json_encode($data["name"]); ?>;
$heroStoryTemp = <?php echo json_encode($data["story"]); ?>;
</script>
<?php
}
$sql->closeCursor();
?>
Finally the HTML relative to the current problem:
<div id="squad_portraits">
<div class="hero_portrait" id="1"></div>
<div class="hero_portrait" id="2"></div>
<div class="hero_portrait" id="3"></div>
<div class="hero_portrait" id="4"></div>
</div>
<div id="hero_info">
<h2 id="hero_name">Hero_Name</h2>
<p id="hero_story"> Hero_Description</p>
</div>
If i switch my sql request :
$tempValue = $_POST['newIndex'];
$sql = $bdd->prepare('SELECT * FROM heroes WHERE ID = :indexValue');
to this
$tempValue = 4;
$sql = $bdd->prepare('SELECT * FROM heroes WHERE ID = 4');
AND add the following to my HTML file
<?php include("../php/get_data.php"); ?>
everything works but my index will always be "4".
There are several issues and missunderstandings in your code.
first, in ajax change data to this:
data: {newIndex:index}, // remove the (), simple syntax misstake
This should solve the sql problem.
Now the get_data.php:
<?php
// including db connection is missing here for $bdd
// You should add a test here, wether you've received any and correct data in 'newIndex'
if(empty($_POST['newIndex']) {
// throw an error, send that back to ajax (with a fitting http response code) and exit script
http_response_code(400);
$error = new stdClass();
$error->msg = "Parameter newIndex was missing";
header('Content-Type: application/json'); // tell the browser that there is some json coming!
echo json_encode($error);
exit;
}
$tempValue = $_POST['newIndex'];
// only select the values you need (name, story)
$sql = $bdd->prepare('SELECT name, story FROM heroes WHERE ID = :indexValue');
$sql->bindParam(":indexValue", $tempValue, PDO::PARAM_STR);
$sql->execute();
$data = $sql->fetch(); // if you only expect/need one row, no while is needed
// echo ONE json string as plain string:
header('Content-Type: application/json'); // tell the browser that there is some json coming!
echo json_encode($data);
Now you receive content of $data as a json as param (data) in the success-callback of your ajax, which you can use like this:
success: function(data){
$("#hero_name").html(data.name);
$("#hero_story").html(data.story);
}
Finally let's change storing the item's id from the id attribute to the data-attribute:
In html:
<div class="hero_portrait" data-id="1"></div>
<div class="hero_portrait" data-id="2"></div>
and in javascript change
var index = $(this).attr("id");
to
var index = $(this).data("id"); // $(this).attr("data-id"); will also work

jQuery send empty data

I have jQuery script to send data from one php to another one.
<script>
jQuery(function(){
jQuery(".button").click(function(){
$.ajax({
url : "content_articles.php",
type : 'POST',
data : {'mark': ButtonValue}
}).done(function(response){
alert(response);
}).fail(function(jqXHR, textStatus, errorThrown){
alert('FAILED! ERROR: ' + errorThrown);
});
});
});
It should take button's value and send it. The value is right, checked with "some debug" alert. But all I have in the end is alert 'FAILED! ERROR: ' with no error message.
On the other side i use
$rowid=$_POST['mark'];
It is empty of course...
The rest of content_articles
<?php
$rowid=$_POST['mark'];
/*echo $_POST['mark'];
exit;*/
mysql_set_charset('utf8');
$mysqli = mysql_connect("localhost", "root", "");
$MySQLSelectedDB = mysql_select_db('content', $mysqli);
$res = mysql_query("SELECT id FROM news ORDER BY id DESC LIMIT 1");
$last =mysql_fetch_assoc($res);
if($rowid==""){
$sql="SELECT * FROM news WHERE id = ".$last['id'];
}
else
{
$sql = "SELECT * FROM news WHERE id='".$rowid."'";
}
$result = mysql_query($sql) or die(mysql_error());
?>
In you ajax replace alert('succesful'); by alert(response);.
Let's check if MARK is arriving ok, put next 3 lines at the top of your code :
$rowid=$_POST['mark'];
echo $_POST['mark'];
exit;
Let's shorten your code :
$rowid=$_POST['mark'];
mysql_set_charset('utf8');
$mysqli = mysql_connect("localhost", "root", "");
$MySQLSelectedDB = mysql_select_db('content', $mysqli);
$sql = "SELECT * FROM news WHERE id='".$rowid."'";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($result);
echo $row['SOME_COLUMN'];
You replace "SOME_COLUMN" by a column in table "news".
let's check if there are results from your query, replace the last line by this one:
echo mysql_num_rows( $result );
You can try to use next
var ButtonValue = $(this).attr('value');
// check here that your ButtonValue is not empty, you can call alert(Buttonvalue); to sure that this var is not empty and receive value from clicked element
$.post('content_articles.php', { mark:ButtonValue }, function(data){
alert(data); // to show what the resposne from script
});
Make sure in console of browser that your PHP script is available and server not return any error (like 404 or 500 and etc)

How can I make the delete buttons fully functional with right ID using php, AJAX or MySQL?

I am having a little problem with this, every delete button is supposed to delete the record of its own id. If we click 164 it must delete the record of 164. It works fine if I remove the ajax and ask the form to validate directly, but if I use AJAX it only deletes the record of 1st record regardless of what button I press e.g. in current scenario it will always delete the record of 159 even if I press 164 button. My code gives the following output: Remember it works fine if I ask the form to validate directly from other PHP file.
This is my output please have a look at it. Its quite simple!
if(is_numeric($lumens) && $lumens < 5000 && $lumens >250){
if(is_numeric($THD) && $THD <= 20 && $THD >=0){
if(is_numeric($scaled_power_factor) && $scaled_power_factor >=0.9){
if(is_numeric($scaled_cct) && $scaled_cct <=5700){
if(is_numeric($scaled_cri) && $scaled_cri >=65){
if(is_numeric($scaled_input_power)){
$con = new mysqli(localhost, asd, myp, rec);
if(!$con){
echo "Couldn't connect to the database";
}
else{
$id = $_SESSION['user_id'];
$query = "INSERT INTO scaling_performance_data SET
MODEL_NUMBER = '$model_number',
LUMENS = '$lumens',
scaled_luminaire_efficacy = '$lm_w',
scaled_input_power = '$scaled_input_power',
THD = '$THD',
SCALED_POWER_FACTOR = '$scaled_power_factor',
SCALED_CCT = '$scaled_cct',
SCALED_CRI = '$scaled_cri',
HOUSING_VARIATION = '$housing_variation',
user_id = '$id'
";
if($con->query($query)){
$sql = "SELECT * FROM scaling_performance_data WHERE user_id='$id';";
$result = $con->query($sql);
if($result){
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
?>
<form>
<table>
<tr>
<th>adsf</th><th>adsf</th><th>adsf</th><th>adsf</th><th>adsf</th><th>adsf</th><th><input type="button" name ="delete_id" id="delete_id" value="<?php echo $row['ID'];?>" onclick="vlid();"/></th>
</tr>
</table>
<script type="text/javascript">
function vlid(){
var delete_id = $('#delete_id').val();
alert(delete_id);
$.post('validator.php',{
postdelete_id : delete_id
},
function(data){
$('#del').html(data);
}
)
}
</script>
</form>
<?php
}
}
validator.php is:
$id = $_POST['postdelete_id'];
$con = new mysqli(localhost, asd, myp, rec);
if(!$con){
echo "Couldn't connect to the database";
}
else{
$query="DELETE FROM scaling_performance_data WHERE ID='$id';";
if($con->query($query)){
echo "Your Result was deleted successful";
echo $id;
}else{
echo "There was a problem Please try again later";
}
}
The problem is that in your vlid() function, JQuery is only selecting the first element with id = delete_id. I would try passing the ID to the vlid() function like this:
<input type="button" ... onclick="vlid(<?php echo $row['ID'];?>)"/>
And then modify your vlid() function to accept the ID parameter.
Try var delete_id = $(event.target).val(); instead of: var delete_id = $('#delete_id').val();
1st ID must be unique so use
class="delete_id"
instead of
id="delete_id"
2nd remove onclick="vlid();" and use
$(document).ready(function(){
$('body').on('click','.delete_id',function(){
var getValue = parseInt($(this).val());
$.post('validator.php',{postdelete_id : getValue},function(data){
$('#del').html(data);
});
});
});
and to remove the tr which deleted use
$(document).ready(function(){
$('body').on('click','.delete_id',function(){
var thisBtn = $(this);
var getValue = parseInt(thisBtn .val());
$.post('validator.php',{postdelete_id : getValue},function(data){
$('#del').html(data);
thisBtn.closest('tr').remove();
});
});
});

Delete PHP (mysqli) row - with HTML/Javascript button

Using google maps, I have events saving to a database using mysqli. These events are then displayed as markers on the map and when clicked the relevant data is displayed in an info box (Name, date, etc). I want the option to delete an event event by deleting a row from the DB when the Remove (remove-event) button is clicked. The button is contained in the data displayed with the javascript:
var eventContent = $('<div class="event-info">' + '<h4 class="event-name">' + point.name + '</h4><hr>' +
'<span><h5>Date: </h5>' +
'<p class="event-date">' + point.edate + '</p></span>' +
'<p class="event-description">'+point.description+'</p>' +
'</span><button id="remove-event" name="remove-event" class="remove-event btn btn-danger btn-sm" onclick="tidy_maps.delete()" title="Remove Event">Remove Event</button>'+
'</div>');
// Display Event details on marker click
google.maps.event.addListener(event_markers[i], "click", function () {
infowindow.setContent(eventContent[0]);
infowindow.open(map, event_markers[i]);
The script that sends it to the php (removedata.php):
tidy_maps.delete = function() {
$.ajax({
type:'POST',
url:'removedata.php',
success:function(data) {
if(data) {
alert("Are you sure?");
}
else {
alert("ERROR!!!!");
}
}
});
}
The removedata.php is:
$con = mysqli_connect("localhost", "root", "password", "gmaps1");
if (!$con) {
die("Can not connect: " .mysql_error());
}
$sql = "DELETE FROM events WHERE id = 'id' ";
$query = mysqli_query($con, $sql);
if(mysqli_affected_rows($con)) {
echo "Record deleted successfully";
}
mysqli_close($con);
As it is, it does not delete the row in the DB, but when i change the line:
$sql = "DELETE FROM events WHERE id = 'id' ";
to a specific ID No. Example:
$sql = "DELETE FROM events WHERE id = '5' ";
And i run the removedata.php in the browser, it deletes the row with ID=5 from the DB. There seems to be no errors when the console when clicking the remove button so it must be sending to PHP script ok.
I would like when the Remove button is clicked that it asks are you sure and then it deletes that specific Row form the DB.
As far as I can tell you don't pass the ID of the row to be deleted.
You can send data two ways, either as a url parameter, or post it using the
data tag:
$.ajax({
type:'POST',
url:'removedata.php',
data: {id : 5}
});
Access the ID in removedata.php:
$id = intval($_POST["id"]);
$sql = "DELETE FROM events WHERE id = " . $id;
WHERE id = 'id' you need to remove the '' and add the $ symbol if you want id to be a variable.
Ok I've played around a little and amended the JS slightly:
tidy_maps.delete = function() {
var confirm_remove = confirm("Do You Want to Remove This Event?")
if(confirm_remove) {
$.ajax({
type:'POST',
url:'removedata.php',
});
window.location = "http://www.google.com/";
}
else {
alert("ERROR!!!!");
}
}
So when Confirm is YES, i threw in a redirect to Google just to see what happens. When YES is clicked in the confirm box, it redirects the page to Google but does not delete the row from the DB
Try this
var id = 5;
var request = $.ajax({
url:'removedata.php',
type: "POST",
data: "id="+id,
success: function(data){
console.log(data);
}
});
get post value in removedata.php
//get post value
$id = intval($_POST["id"]);
$sql = "DELETE FROM events WHERE id = " . $id;

Ajax Form Submit - When click change html element text

So I'm trying to create a message system. When I click on the Message to open my template opens in the same page the message content. I'm trying to make like: "See" Button->ajax->replace with jquery .text("Blah Blah"). the problem is that when I try tod
HTML Code:
<form method="POST">
<button type="button" class="btn btn-small btn-success" name="msg_preview_id" value="'.$inbox_row['id'].'">New</button>
</form>
Jquery Ajax Form:
$(document).ready(function(){
$('button[name=msg_preview_id]').click(function(event) {
var formData = {'msg_preview_id' : $('button[name=msg_preview_id]').val()};
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : '../../class/messages/inbox_preview.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json' // what type of data do we expect back from the server
})
.done(function(data) {
console.log(data);
//Email Stuff
$('h1[id=emailheading]').text(""+data.info.subject+"");
$('a[id=emailfrom]').text(""+data.info.from+"");
$('span[id=emaildate]').text(""+data.info.rcvdat+"");
$('p[id=emailtext]').text(""+data.info.text+"");
//Ceninhas
$('#inbox-wrapper').addClass('animated fadeOut');
$('#inbox-wrapper').hide();
$('#preview-email-wrapper').addClass('animated fadeIn ');
$('#preview-email-wrapper').show();
//$('.page-title').show();
//Load email details
$('#inbox-wrapper').removeClass('animated fadeOut');
$('#inbox-wrapper').removeClass('animated fadeIn');
});
event.preventDefault();
});
});
PHP:
<?php
include ('../../inc/config.inc.php');
$data = array();
$info = array();
$Msg_Preview_ID = $_POST['msg_preview_id'];
$MsgSQL = mysqli_query($Connection, "SELECT * FROM messages_inbox WHERE id='$Msg_Preview_ID'");
$Msg = mysqli_fetch_assoc($MsgSQL);
$bzQuery = mysqli_query($Connection, "SELECT * FROM members_profile WHERE id='".$Msg['from']."'");
$bzFetch = mysqli_fetch_assoc($bzQuery);
$info['from'] = $bzFetch['fname']." ".$bzFetch['lname'];
$info['subject'] = $Msg['subject'];
$info['text'] = $Msg['text'];
$info['rcvdat'] = $Msg['rcvdat'];
$data['info'] = $info;
echo json_encode($data);
I use $_GET[] in other pge it was easier!

Categories

Resources