JQuery AJAX Delete form database

petewinter
petewinter used Ask the Experts™
on
Can you please look at my code and let me know when the delete is not working? Thanks
<script type="text/javascript">

//Delete post
$(document).ready(function() {
  $('a.delete').click(function(e) {
    e.preventDefault();
    var parent = $(this).parent();
    $.ajax({
      type: 'POST',
      url: 'add_script.php',
	  data: "id="+parent.attr('id')+"&del=true",
      success: function(r){
			$("#success").html("Post entitled <strong>"+post.find('h2').text()+"</strong> removed").fadeIn(300).delay(900).fadeOut(300);post.hide(300, function(){post.remove()})},
	  error: function(){$("#error").text("Could not delete post").fadeIn(300).delay(900).fadeOut(300)}
    });
  });
});

</script>

// add_script.php code below...

<?php
	
if(isset($_POST["del"])){
	
  	mysql_select_db($database_conn_cwes, $conn_cwes);
  	$query_rs_products = "DELETE FROM products2 WHERE id = " . $_POST['id'];
  	$rs_products = mysql_query($query_rs_products, $conn_cwes) or die(mysql_error());

	mysql_select_db($database_conn_cwes, $conn_cwes);
	$query_rs_products = "SELECT * FROM products2 WHERE active IS NULL ORDER BY product_name ASC";
	$rs_products = mysql_query($query_rs_products, $conn_cwes) or die(mysql_error());
	$row_rs_products = mysql_fetch_assoc($rs_products);
	$totalRows_rs_products = mysql_num_rows($rs_products);

}

?>

<?php do {
?>

<div id="<?php echo $row_rs_products['id']; ?>"><?php echo $row_rs_products['product_name']; ?> - <a href="#" class="delete">Delete</a></div>

<?php

} while ($row_rs_products = mysql_fetch_assoc($rs_products)); 

?>

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
are you getting id  $_POST['id']  in <?php section?

Commented:
Is "$conn_cwes" the database connection resource? Does the database open successfully?

You can dump what the "add_script.php" returns by

success: function(r){
    alert(r);
}

Open in new window

Author

Commented:
Thanks for the reply. Add the moment it is not doing anything and it trying to go the this page: add.php#

I thought the e.preventDefault(); should stop the link working?

yes the $conn_cwes does connect to the database okay.
Ensure you’re charging the right price for your IT

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

I thought the e.preventDefault(); should stop the link working?

yes

Commented:
Ok... Straightforward asking, did you include jquery.js in the page?

Author

Commented:
See the whole code to the php page too if that helps?
<?php require_once('../Connections/conn_cwes.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}

if (isset($_POST["add"])) {
	
	$insertSQL = sprintf("INSERT INTO products2 (product_name) VALUES (%s)",
                       GetSQLValueString($_POST["product_name"], "text"));  
	mysql_select_db($database_conn_cwes, $conn_cwes);
	$Result1 = mysql_query($insertSQL, $conn_cwes) or die(mysql_error());

	mysql_select_db($database_conn_cwes, $conn_cwes);
	$query_rs_products = "SELECT * FROM products2 WHERE active IS NULL ORDER BY product_name ASC";
	$rs_products = mysql_query($query_rs_products, $conn_cwes) or die(mysql_error());
	$row_rs_products = mysql_fetch_assoc($rs_products);
	$totalRows_rs_products = mysql_num_rows($rs_products);
	
} elseif(isset($_POST["product_category"])){

	mysql_select_db($database_conn_cwes, $conn_cwes);
	$query_rs_products = "SELECT * FROM products2 WHERE product_category_id = '". $_POST["product_category"] . "' AND active IS NULL ORDER BY product_name ASC";
	$rs_products = mysql_query($query_rs_products, $conn_cwes) or die(mysql_error());
	$row_rs_products = mysql_fetch_assoc($rs_products);
	$totalRows_rs_products = mysql_num_rows($rs_products);
	
} elseif(isset($_POST["product_brand"])){
	
	mysql_select_db($database_conn_cwes, $conn_cwes);
	$query_rs_products = "SELECT * FROM products2 WHERE product_brand_id = '". $_POST["product_brand"] . "' AND active IS NULL ORDER BY product_name ASC";
	$rs_products = mysql_query($query_rs_products, $conn_cwes) or die(mysql_error());
	$row_rs_products = mysql_fetch_assoc($rs_products);
	$totalRows_rs_products = mysql_num_rows($rs_products);
	
} elseif (isset($_POST["getall"])){
	
	mysql_select_db($database_conn_cwes, $conn_cwes);
	$query_rs_products = "SELECT * FROM products2 WHERE active IS NULL ORDER BY product_name ASC";
	$rs_products = mysql_query($query_rs_products, $conn_cwes) or die(mysql_error());
	$row_rs_products = mysql_fetch_assoc($rs_products);
	$totalRows_rs_products = mysql_num_rows($rs_products);
	
} elseif(isset($_POST["del"])){
	
  	mysql_select_db($database_conn_cwes, $conn_cwes);
  	$query_rs_products = "DELETE FROM products2 WHERE id = " . $_POST['id'];
  	$rs_products = mysql_query($query_rs_products, $conn_cwes) or die(mysql_error());

	mysql_select_db($database_conn_cwes, $conn_cwes);
	$query_rs_products = "SELECT * FROM products2 WHERE active IS NULL ORDER BY product_name ASC";
	$rs_products = mysql_query($query_rs_products, $conn_cwes) or die(mysql_error());
	$row_rs_products = mysql_fetch_assoc($rs_products);
	$totalRows_rs_products = mysql_num_rows($rs_products);

}

?>

<?php do {
?>

<div id="<?php echo $row_rs_products['id']; ?>"><?php echo $row_rs_products['product_name']; ?> - <a href="#" class="delete">Delete</a></div>

<?php

} while ($row_rs_products = mysql_fetch_assoc($rs_products)); 

?>

<?php

mysql_free_result($rs_products);

?>

Open in new window

AlexSoftware Engineer

Commented:
Fitrst of all your syntax into data is wrong.Please try the following.

data: { id:parent.attr('id'),del:1}

Author

Commented:
alex_code - I have changed as requested, but still the same?
AlexSoftware Engineer

Commented:
It's js modification, so, you have to clear your cache from the browser to ensure the change take effect.

Author

Commented:
I have cleared the cache. You can try via this link: http://www.cwesolutions.co.uk/printers/add.php
am not PHP guy but have doubt with this syntax.

"DELETE FROM products2 WHERE id = " . $_POST['id'];

Commented:
The DELETE syntax is correct. You can put $_POST['id'] inbetween 2 single quotes to prevent error.

"DELETE FROM products2 WHERE id = '" . $_POST['id'] . "'";
AlexSoftware Engineer

Commented:
So,ensure that the field id into your table it's an integer.
2nd) use this .....WHERE id=$_POST['id'];

Commented:
Try this:

//Delete post
$(document).ready(function() {
  $('a.delete').live('click', function(e) {
    e.preventDefault();
    var parent = $(this).parent();
    $.ajax({
      type: 'POST',
      url: 'add_script.php',
          data: "id="+parent.attr('id')+"&del=true",
      success: function(r){
                        $("#success").html("Post entitled <strong>"+post.find('h2').text()+"</strong> removed").fadeIn(300).delay(900).fadeOut(300);post.hide(300, function(){post.remove()})},
          error: function(){$("#error").text("Could not delete post").fadeIn(300).delay(900).fadeOut(300)}
    });
  });
});

Open in new window

AlexSoftware Engineer

Commented:
Also check the url parameter. You set it as add_script.php. That means that this file must be in the root directory otherwise if you have it i.e. into another folder let's say includes, you have to set an absolute path like this: url: './includes/add_script.php'
AlexSoftware Engineer

Commented:
and as i see you have it into printers folder so you have to correct the path of the url parameter :-)

Author

Commented:
StingRaY - Thanks that does remove the row from the database, but I not seeing the change unless I refresh the page?
Commented:
Try this:

//Delete post
$(document).ready(function() {
  $('a.delete').live('click', function(e) {
    e.preventDefault();
    var parent = $(this).parent();
    $.ajax({
      type: 'POST',
      url: 'add_script.php',
          data: "id="+parent.attr('id')+"&del=true",
      success: function(r){
          $("#postwrap").html(r)
                        $("#success").html("Post entitled <strong>"+post.find('h2').text()+"</strong> removed").fadeIn(300).delay(900).fadeOut(300);post.hide(300, function(){post.remove()})},
          error: function(){$("#error").text("Could not delete post").fadeIn(300).delay(900).fadeOut(300)}
    });
  });
});

Open in new window

Author

Commented:
Many thanks for your help

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial