Solved

Single record delete with php/ajax

Posted on 2016-10-13
20
43 Views
Last Modified: 2016-10-15
When I click the delete button I want the record information to disappear and the record is removed from the database. At the moment, the record information fades out but the record isn't actually deleted from the database for some reason.

The button:

<input type="submit" id="contact_delete" class="btn btn-danger btn-fill" name="delete_comment" value="Delete message" data-id="<?php echo $contact_id; ?>">

Open in new window


jQuery/ajax:

	$(document).ready(function() {
			$('#contact_delete').click(function(e){
				e.preventDefault();
				var id = $(this).attr('data-id');
				$.ajax({
					type: 'POST',
					url: 'delete_message.php',
					data: 'contact_id='+id,
					success: function(data){
						$('#detail-area').fadeOut();
						
					}

				});
				
			});
			
		});

Open in new window


The php:

if(isset($_POST['delete_comment'])){
	
	$contact_id = $_POST['contact_id'];
	
	$stmt = $link->prepare("DELETE FROM `contact_form` WHERE `contact_id` = ?");
	$stmt->bind_param("i", $contact_id);
	$stmt->execute();
	$stmt->close();
	echo "Record deleted";
}

Open in new window

0
Comment
Question by:Black Sulfur
  • 8
  • 6
  • 4
  • +1
20 Comments
 
LVL 9

Expert Comment

by:Moussa Mokhtari
ID: 41842683
@Black Sulfur
try to remove the Apostrophe from
$stmt = $link->prepare("DELETE FROM `contact_form` WHERE `contact_id` = ?");

Open in new window

like
$stmt = $link->prepare("DELETE FROM contact_form WHERE contact_id = ?");

Open in new window

0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41842724
@Moussa Mokhtari
try to remove the Apostrophe from
That is not an apostrophe it is a backtick used to enclose database objects so they don't get confused with reserved words.

@Black Sulphur
This is how you should retrieve a custom data attribute
var id = $(this).data('id');

Open in new window


Check your console - see what you are posting to the form - make sure it is what you expect.
Check the console in the POST response to see if there are any errors reported there.

Debugging AJAX.
1. Change your PHP script from POST to GET
2. Call the script directly with the parameters (contact_id) in the url

delete_message.php?contact_id=3&delete_comment=abc

Open in new window


Get that working first - if it works then change back to POST and test with script again.
0
 
LVL 9

Expert Comment

by:Moussa Mokhtari
ID: 41842784
@Julian Hansen
Thanks for you're clarification I really appreciate that .
and both
$(this).attr("data-id") 

Open in new window

and
$(this).data('id'); 

Open in new window

will output the contact_id variable.
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41843066
Correct - you can use either - however in terms of good coding practice the correct way is
$(this).data('id');

Open in new window

0
 

Author Comment

by:Black Sulfur
ID: 41843086
Thanks for the responses, I am going to try this all out when I get home from work.

Just a quick question @Julian regarding :

$(this).data('id');

Open in new window


I used data-id because I am already using "id" for my button:

id="contact_delete"

Open in new window


So, just wondering if using id as you suggested will not cause a conflict?
1
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41843116
No, the two are completely separate
id="abc"
data-id="def"

Open in new window

Two different attributes.
The first you access like this
$(this).attr('id');

Open in new window

The second
$(this).data('id');

Open in new window

Note the different method used. .data() is jQuery's function for accessing custom attributes.
1
 
LVL 9

Expert Comment

by:Moussa Mokhtari
ID: 41843127
@Black Sulfur
No it won't
.data(key) is jQuery method that when applied on given element will search for attribute in that element that has the name data-key with prefix data-
if you have data-someId and you use .data("someId") you will get the value of that someId attribute
not necessarily data-id

Cheers
0
 
LVL 9

Assisted Solution

by:Brian Tao
Brian Tao earned 150 total points
ID: 41843595
There's no bug in you code, but there's a problem in the "submit" logic you have.
Your jQuery instructs the button to POST only with the contact_id, but not submitting the form, hence the delete_comment is never sent back to the server.  Consequently your PHP doesn't see $_POST['delete_comment'] and just skip the if part.

I guess you're trying to "migrate" from a normal HTTP page POST to jQuery's ajax POST.  You may want to bind the form submit event rather than the button click event, or simply add delete_comment to the data option in your ajax POST.
1
 
LVL 9

Expert Comment

by:Moussa Mokhtari
ID: 41843716
@Brian Tao you're truly right  
The only variable that has been sent to the server side is contact_id so when you perform
if(isset($_POST['delete_comment'])) it returns False
you can either change it to if(isset($_POST['contact_id'])) or  add delete_comment to your ajax data option like
data: 'contact_id='+id'&delete_comment='+$("input[name=delete_comment]").val(),

Open in new window

0
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 

Author Comment

by:Black Sulfur
ID: 41843780
Thanks again to everyone. I am truly sorry but I am getting even more confused now.

This is where I am now:

My form looks like this:

 <form class="form-inline" method="post" id="message_delete">
 <input type="submit" id="contact_delete" class="btn btn-danger btn-fill" name="delete_comment" value="Delete message" data-id="<?php echo $contact_id; ?>">
<a href="contact-form"><input type="button" class="btn btn-warning btn-fill" value="Back to messages"></a> </form>

Open in new window


So,

Form id = "message_delete"

Submit button id = "contact_delete"

Submit button name ="delete_comment"

data-id = php code that holds the record ID. I am still not really clear on the whole id and data-id thing. The id of the button is how I identify it in the jQuery and the data-id is the php variable I am assigning to the button. Would it not be better to put the variable in a hidden field and then not give the button data-id at all?

I did as suggested and changed the jQuery to be on form submit and not button click.


      
	$(document).ready(function() {
			$('#message_delete').submit(function(e){
				e.preventDefault();
				var id = $(this).data('id');
				$.ajax({
					type: 'POST',
					url: 'delete_message.php',
					data: 'contact_id='+id,
					success: function(data){
						$('#detail-area').fadeOut();
					
					}

				});
				
			});
			
		});

Open in new window


For normal php when not using ajax, I would normally have what I have now, which is to check if the button was pressed, and if so then do something.

So, if the button which has name "delete_comment" is pressed, delete the record where the id is = to the id being posted from the form. But that is with just using PHP. Are you saying that it doesn't work like that with ajax?


if(isset($_POST['delete_comment'])){
	
	$contact_id = $_POST['contact_id'];
	
	$stmt = $link->prepare("DELETE FROM `contact_form` WHERE `contact_id` = ?");
	$stmt->bind_param("i", $contact_id);
	$stmt->execute();
	$stmt->close();
	echo "Record deleted";
}

Open in new window

0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41843841
Look at your AJAX routine line 8
data: 'contact_id='+id,

Open in new window

contact_id is the only data you are sending to the server.
F12 to open your console after you click the button.
Expand the post and look at the request - you will see all you are sending is the contact_id.

In your PHP code you are looking for a POST variable delete_comment - which is not going to exist ever because you are not sending it.

Rather try this in your AJAX
$(document).ready(function() {
	$('#message_delete').submit(function(e){
		e.preventDefault();
		var id = $(this).data('id');
		var data = $(this).serialize() + '&contact_id=' + id;
		$.ajax({
			type: 'POST',
			url: 'delete_message.php',
			data: data,
			success: function(data){
				$('#detail-area').fadeOut();
			}
		});
	});
});

Open in new window

Working sample to follow
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41843847
However you are not actually using the "delete_comment" value so you can also just change your PHP to
$contact_id = isset($_POST['contact_id']) ? $_POST['contact_id'] : false;
if($contact_id){
	$stmt = $link->prepare("DELETE FROM `contact_form` WHERE `contact_id` = ?");
	$stmt->bind_param("i", $contact_id);
	$stmt->execute();
	$stmt->close();
	echo "Record deleted";
}

Open in new window

0
 
LVL 51

Accepted Solution

by:
Julian Hansen earned 350 total points
ID: 41843869
Just saw another issue.

You are binding to the submit and using $(this) to get the id attached to the button - not going to work. Rather do this
HTML - give your submit button a class of delete_comment
<form class="form-inline" method="post" id="message_delete">
  <input type="submit" id="contact_delete" class="btn btn-danger btn-fill delete_comment" name="delete_comment" value="Delete message" data-id="123">
  <a href="contact-form"><input type="button" class="btn btn-warning btn-fill" value="Back to messages"></a>
</form>

Open in new window

Then use this jQuery
$(document).ready(function() {
  $('.delete_comment').click(function(e){
    e.preventDefault();
    var id = $(this).data('id');

    $.ajax({
      type: 'POST',
      url: 'delete_message.php',
      data: {contact_id: id},
      success: function(data){
        // You are assuming success - probably best to check the return and update UI accordingly
        $('#detail-area').fadeOut();
      }
    });
  });
});

Open in new window

And in your PHP
$contact_id = isset($_POST['contact_id']) ? $_POST['contact_id'] : false;
if($contact_id){
  $stmt = $link->prepare("DELETE FROM `contact_form` WHERE `contact_id` = ?");
  $stmt->bind_param("i", $contact_id);
  $stmt->execute();
  $stmt->close();
  echo "Record deleted";
}

Open in new window

Working sample here
0
 

Author Comment

by:Black Sulfur
ID: 41843880
Thanks so much, I will try it now. Just a quick question before I do that. Is the whole point of using ajax just to make the user interface look cool by fading stuff out and in and more convenient by not having to redirect users etc. as they can just delete records all on one page and do a "live search" etc?

Because it seems like a real mission to do if that is all it is for. I suppose the more I do it the easier it will become but it really does seem like a lot of effort to make things "look cool" for lack of a better term. But perhaps I am missing the point completely.

Just wondering...
0
 

Author Comment

by:Black Sulfur
ID: 41843892
Finally, it is deleting records! Thank you!

Last thing though, how do I get it to actually echo the message in the php?

echo "Record deleted";

Open in new window

0
 

Author Comment

by:Black Sulfur
ID: 41843897
Oh, sorry. Forgot to ask one last thing.

When should you use:

success: function(data){

Open in new window


vs:

success: function(response){

Open in new window

0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41843915
function(data) vs function(response) vs function(bighappyelephantsdancingonaball)
All the same - you chose the parameter name.

The php script is sending back a response - you are just not doing anything with it.

in your success function the data (or response - whichever you prefer) parameter will hold whatever was output from the PHP script.
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41844305
Thank you for the points but Brian deserves some of the credit as well. He pointed out the key issue which was that you were checking a POST value that was not being sent.

Can I re-open the question for you to regrade?
0
 

Author Comment

by:Black Sulfur
ID: 41844664
Sorry, you are right. Yes, please let me change it.
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

OverviewThis article demonstrates a simple search form using AJAX. The purpose of the article is to demonstrate how to use the same code to render a page and javascript (JQuery) and AJAX to make subsequent calls to refine the results. The princip…
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now