Solved

fade new row in after record insert with jQuery/ajax/php

Posted on 2016-11-20
18
37 Views
Last Modified: 2016-11-22
When adding a record to the database the record is inserted into the database and I am able to get a new row to show up but at the moment I don't know how to display the latest record inserted if that is the best way to do it. I am just using plain text at the moment. Also, I want the row to fade in if possible to make it look a bit smoother.

	$(document).ready(function() {
			$("#catform").submit(function (e) {
	        e.preventDefault();

				$('#status').html("processing...");
				$("#submit").hide();
				$.ajax({
					url: "addcat.php",
					data: $(this).serialize(),
					type: "POST",
					success: function(data){
						$('#status').hide();
						$("#submit").show();
						$output = "<tr>";
						$output += "<td>Latest record to display here</td>";
						$output += "<td></td>";
						$output += "<td></td>";
						$output += "<td></td>";
						$output += "<td></td>";
						$output += "<td><a> <i class='pe-7s-trash' id='$pid'></i> </a></td>";
						$output += "</tr>";
						$("#addToTable").append($output);
						
						}
				});	
			});		
		});

Open in new window


The #addToTable is here:

<tbody id="addToTable">
<?php display_categories($link); ?>
</tbody>

Open in new window


the display_categories function is the same as my previous question:

$showcat = <<<EOD
		
<tr>
<td id="status"><input id="{$pid}" class="data" type="category" name="category" value="{$categoryName}"></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td><a> <i class="pe-7s-trash" id='$pid'></i> </a></td>
</tr>
		
EOD;
echo $showcat;

Open in new window

0
Comment
Question by:Black Sulfur
  • 11
  • 4
  • 2
  • +1
18 Comments
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 41894984
jQuery show() and hide() methods have a duration parameter that tells the speed of the animation.
http://api.jquery.com/show/
0
 

Author Comment

by:Black Sulfur
ID: 41894989
Ah, that is helpful, thanks. It works for my submit button:

$("#submit").show( "slow" );

Open in new window


But I need to just figure out how to get it to work with the added row:

$("#addToTable").append($output);

Open in new window

0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 41895011
Maybe append() the output, followed immediately by hide(), then show("slow") ?  Easy enough to try.
0
 

Author Comment

by:Black Sulfur
ID: 41895013
Thanks Ray, will give that a go. Any ideas on how to get the last inserted record to display? That is actually my main priority of the question.
0
 

Author Comment

by:Black Sulfur
ID: 41895016
Hmm.

This does the fade nicely, but because of my positioning of the id the whole table fades in when I just want the newly inserted row to fade in.

$("#addToTable").append($output).hide().show("slow");

Open in new window


I tried this but it doesn't seem to work:

$output = "<tr id='addToTable'>";
$output += "<td>Here goes</td>";
$output += "<td></td>";
$output += "<td></td>";
$output += "<td></td>";
$output += "<td></td>";
$output += "<td><a> <i class='pe-7s-trash' id='$pid'></i> </a></td>";
$output += "</tr>";
$("#addToTable").append($output).hide().show("slow");

Open in new window

0
 
LVL 9

Expert Comment

by:Moussa Mokhtari
ID: 41895036
@Black Sulfur
Try to use appendTo() like

$($output).appendTo("#addToTable").hide().show("slow");

Open in new window

0
 

Author Comment

by:Black Sulfur
ID: 41895056
Thank you. I will try that when I'm in front of my PC again(I'm sending this message from mobile app)

I've been thinking about how to retrieve the ID. First I thought it had to be done by jquery but now I'm thinking I need to alter my sql insert query and add the code to retrieve the last inserted record. I then need to pass that on to the jquery and display it. Is that the right idea or am I way off?
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 41895071
I think you're headed in the right direction.  You can get the last_insert_id (or similar) from your database insert process.  You can return this from your server-side AJAX script to your client-side jQuery script in the form of a return value.  Or if you need to return other values, you can make this an element of a JSON string.
0
 
LVL 82

Assisted Solution

by:leakim971
leakim971 earned 250 total points
ID: 41895080
*** DON'T AWARD ME POINTFOR THIS ***

from your original question replace :
                                    $output = "<tr>";
by :
                                    $output = "<tr style='display:none;'>";

and also replace :
                                    $("#addToTable").append($output);
by :
                                    $($output).appendTo("#addToTable").fadeIn("slow");

	$(document).ready(function() {
		$("#catform").submit(function (e) {
			e.preventDefault();

			$('#status').html("processing...");
			$("#submit").hide();
			$.ajax({
				url: "addcat.php",
				data: $(this).serialize(),
				type: "POST",
				success: function(data){
					$('#status').hide();
					$("#submit").show();
					$output = "<tr style='display:none;'>";
					$output += "<td>Latest record to display here</td>";
					$output += "<td></td>";
					$output += "<td></td>";
					$output += "<td></td>";
					$output += "<td></td>";
					$output += "<td><a> <i class='pe-7s-trash' id='$pid'></i> </a></td>";
					$output += "</tr>";
					$($output).appendTo("#addToTable").fadeIn(1500);					
				}
			});	
		});		
	});

Open in new window

0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 

Author Comment

by:Black Sulfur
ID: 41896139
Argh, I am struggling. How can I combine 2 prepared statements or do they have to be separate like I have them now?

$stmt = $link->prepare("INSERT INTO `voucher_categories`(`category_name`) VALUES (?)");
$stmt->bind_param("s", $_POST['cat_name']);
$stmt->execute();
$stmt->close();
	
$stmt = $link->prepare("SELECT LAST_INSERT_ID(cat_id) FROM `voucher_categories` ORDER BY `cat_id` DESC");
$stmt->execute();
$result = $stmt->get_result();
if($result) {
	$row = $result->fetch_assoc();
	$myoutput = htmlentities($row['cat_id']);
	echo $myoutput;
	$stmt->close();
	}
}

Open in new window


I have changed the jQuery as well:

                                             
  success: function(data){
						$myoutput = data;
						$("#cat_name").val("");
						$("#submit").show( "slow" );
						$output = "<tr'>";
						$output += "<td>" + $myoutput + "</td>";
						$output += "<td></td>";
						$output += "<td></td>";
						$output += "<td></td>";
						$output += "<td></td>";
						$output += "<td><a> <i class='pe-7s-trash' id='$pid'></i> </a></td>";
						$output += "</tr>";
						$($output).appendTo("#addToTable").hide().show("slow");

Open in new window


I am getting an error when I perform the insert:

Undefined index: cat_id

The particular line is :
$myoutput = htmlentities($row['cat_id']);

Open in new window

0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 250 total points
ID: 41896176
You're trying to do a lot of things at once.  Maybe separate these multi-layer questions out into parts, so you can get more focused help.

Please have a look at this article.  Search the code snippets for // LOADING OUR DATA INTO THE TABLE where it shows how to get the last insert id value.
https://www.experts-exchange.com/articles/11177/PHP-MySQL-Deprecated-as-of-PHP-5-5-0.html
1
 

Author Comment

by:Black Sulfur
ID: 41896245
Good point Ray,

I think I will ask a related question regarding the SQL query. I got some useful info from that link you posted and I can now retrieve the ID. But I have another headache now...
0
 

Author Comment

by:Black Sulfur
ID: 41896264
Thanks to Ray, I now how the prepared statement sorted. I seem to have one last problem. When the new row fades in with the newly added record, I cannot seem to click on the trash can icon to delete it. Nor can I click into it like the other records to edit it. It just seems to be read only.

Here is the code that displays the newly inserted record:

                                             $output = "<tr'>";
						$output += "<td>" + $myoutput + "</td>";
						$output += "<td></td>";
						$output += "<td></td>";
						$output += "<td></td>";
						$output += "<td></td>";
						$output += "<td><a> <i class='pe-7s-trash' data-id='$pid'></i> </a></td>";
						$output += "</tr>";
						$($output).appendTo("#addToTable").hide().show("slow");

Open in new window


If more code is required please let me know.
0
 

Author Comment

by:Black Sulfur
ID: 41896333
I am a bit closer now. I decided to use php to display the new record instead of jQuery. it adds the new row and I can edit it now where as I couldn't before. But when I click on the trash can to trigger the delete, nothing happens.

Updated php:

$stmt = $link->prepare("INSERT INTO `voucher_categories`(`category_name`) VALUES (?)");
$stmt->bind_param("s", $_POST['cat_name']);
$stmt->execute();
$catName = htmlentities($_POST['cat_name'], ENT_QUOTES, "UTF-8");
$pid = $stmt->insert_id; // Retrieves last inserted ID
	
	$output = <<<EOD
		
		<tr>
		<td id="status"><input id="{$pid}" class="data" type="category" name="category" value="{$catName}"></td>
		<td></td>
		<td></td>
		<td></td>
		<td></td>
		<td><a> <i class="pe-7s-trash" data-id='$pid'></i> </a></td>
		</tr>
		
EOD;
echo $output;
	
$stmt->close();	

Open in new window


updated jQuery:

                                     $.ajax({
					url: "addcat.php",
					data: $(this).serialize(),
					type: "POST",
					success: function(data){
						$output = data;
						$("#cat_name").val("");
						$($output).appendTo("#addToTable").hide().show("slow");

Open in new window

0
 

Author Comment

by:Black Sulfur
ID: 41896463
I thought about this and realized that I need to put the add and delete together. Now I can click on the trash icon straight after adding a record and it will let me delete it. is it okay to do this? The issue with this though is I have to have the delete functionality twice. Once with the insert code to work for newly inserted records and a separate delete function for existing records that weren't just added. If I don't do that then nothing happens when I click on the trash can(delete button) for older existing records. I can't win!

$(document).ready(function() {
	    $("#catform").submit(function(e) {
	        e.preventDefault();
	        $.ajax({
	            url: "addcat.php",
	            data: $(this).serialize(),
	            type: "POST",
	            success: function(data) {;
	                $output = data;
	                $("#cat_name").val("");
	                $($output).appendTo("#addToTable").fadeIn("slow");
	                $(".pe-7s-trash").click(function(e) {
	                    e.preventDefault();

	                    var id = $(this).data('id');
	                    var tr = $(this).closest('tr');

	                    swal({
	                            title: "Are you sure?",
	                            text: "You will not be able to undo this action.",
	                            type: "warning",
	                            showCancelButton: true,
	                            confirmButtonColor: "#FB404B",
	                            confirmButtonText: "Yes, delete it!",
	                            cancelButtonText: "Cancel!",
	                            closeOnConfirm: false,
	                            closeOnCancel: false
	                        },
	                        function(isConfirm) {
	                            if (isConfirm) {
	                                $.ajax({
	                                    url: "deletecat.php",
	                                    type: "POST",
	                                    data: {
	                                        delete: id
	                                    },

	                                    success: function(result) {
	                                        tr.fadeOut('slow', function() {
	                                            swal("Deleted!", "Category successfully deleted.", "success");
	                                        })
	                                    }

	                                })

	                            } else {
	                                swal("Cancelled", "Maybe later then..", "error");
	                            }
	                        });
	                })
	            }
	        })
	    })
	});

Open in new window

0
 
LVL 9

Expert Comment

by:Moussa Mokhtari
ID: 41896511
Nothing Happen
remove your delete action from your ajax success callback and
write it "delete action" like this (not inside success callback)  so it work with the newly created and the old ones
$(".pe-7s-trash").on("click",function(e) {
	                    e.preventDefault();

	                    var id = $(this).data('id');
	                    var tr = $(this).closest('tr');

	                    swal({
	                            title: "Are you sure?",
	                            text: "You will not be able to undo this action.",
	                            type: "warning",
	                            showCancelButton: true,
	                            confirmButtonColor: "#FB404B",
	                            confirmButtonText: "Yes, delete it!",
	                            cancelButtonText: "Cancel!",
	                            closeOnConfirm: false,
	                            closeOnCancel: false
	                        },
	                        function(isConfirm) {
	                            if (isConfirm) {
	                                $.ajax({
	                                    url: "deletecat.php",
	                                    type: "POST",
	                                    data: {
	                                        delete: id
	                                    },

	                                    success: function(result) {
	                                        tr.fadeOut('slow', function() {
	                                            swal("Deleted!", "Category successfully deleted.", "success");
	                                        })
	                                    }

	                                })

	                            } else {
	                                swal("Cancelled", "Maybe later then..", "error");
	                            }
	                        });
	                });

Open in new window

0
 

Author Comment

by:Black Sulfur
ID: 41897524
Not sure if this is what you mean but I tried this and I still can't delete a new record after insert it:

$(document).ready(function() {
		    $("#catform").submit(function(e) {
		        e.preventDefault();
              
		        $.ajax({
		            url: "addcat.php",
		            data: $(this).serialize(),
		            type: "POST",
		            success: function(data) {
		                $output = data;
		                $("#cat_name").val("");
		                $($output).appendTo("#addToTable").fadeIn("slow");

		            }
		        })

		    })


		    $(".pe-7s-trash").on("click", function(e) {
		        e.preventDefault();

		        var id = $(this).data('id');
		        var tr = $(this).closest('tr');

		        swal({
		                title: "Are you sure?",
		                text: "You will not be able to undo this action.",
		                type: "warning",
		                showCancelButton: true,
		                confirmButtonColor: "#FB404B",
		                confirmButtonText: "Yes, delete it!",
		                cancelButtonText: "Cancel!",
		                closeOnConfirm: false,
		                closeOnCancel: false
		            },
		            function(isConfirm) {
		                if (isConfirm) {
		                    $.ajax({
		                        url: "deletecat.php",
		                        type: "POST",
		                        data: {
		                            delete: id
		                        },

		                        success: function(result) {
		                            tr.fadeOut('slow', function() {
		                                swal("Deleted!", "Category successfully deleted.", "success");
		                            })
		                        }

		                    })

		                } else {
		                    swal("Cancelled", "Maybe later then..", "error");
		                }
		            });
		    });

		});

Open in new window

0
 

Author Comment

by:Black Sulfur
ID: 41897533
I think this thread is getting too long now so I will ask a new question for this and close this question out.
0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Suggested Solutions

This article discusses how to create an extensible mechanism for linked drop downs.
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.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to count occurrences of each item in an array.

706 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

18 Experts available now in Live!

Get 1:1 Help Now