Link to home
Start Free TrialLog in
Avatar of Crazy Horse
Crazy HorseFlag for South Africa

asked on

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

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

Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

jQuery show() and hide() methods have a duration parameter that tells the speed of the animation.
http://api.jquery.com/show/
Avatar of Crazy Horse

ASKER

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

Maybe append() the output, followed immediately by hide(), then show("slow") ?  Easy enough to try.
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.
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

Avatar of Moussa Mokhtari
Moussa Mokhtari

@Black Sulfur
Try to use appendTo() like

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

Open in new window

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?
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.
SOLUTION
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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

ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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...
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.
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

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

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

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

I think this thread is getting too long now so I will ask a new question for this and close this question out.