views:

489

answers:

1

Hi all,

PLATFORM:

PHP, mySQL & jQuery

WHAT I HAVE:

I have a Database table. Within my application, I am able to fetch all the rows. When I am querying the database, I have set the records fetch limit as 30, but that can be changed via a dropdown list. So consider that I am fetching upto 30 rows of data in a single query and displaying them. I am populating this data in table (rows). I have checkbox next to every record and a Delete button. When the Delete button is clicked, all the rows that are checked, will get deleted.

WHAT I AM TRYING TO DO:

For every row that I delete, I am trying to update the current view with the next set of rows, till the fetch row limit is met. Confusing? Here's an example:

EXAMPLE:

Consider that I 1000 rows in my table & I have set the records fetch limit as 30, which means that upto 30 records will be shown at one time. I can use pagination to navigate to the other records. Now in my view, I have 30 rows of data in the table. I selected 5 rows and deleted them via jQuery. Upon deletion, I am able to remove the deleted rows from view. So in this case, since I deleted 5 rows, I am able to remove them and now my view shows me only 25 rows (which is correct). Since there are 995 rows remaining still in my table and as I have a record fetch limit of 30, now I want this to work in such a way that I show the next 5 records automatically. I want the existing entries to move up and the new entries to populate at the bottom.

In other words, as long as sufficient rows exist, I want to populate my view with the same number of records, as many were deleted. So if I delete 10 records, I want the next 10 records to be fetched and displayed automatically again making it a total count of 30 rows of data, that are displayed. If 20 records are deleted, then I want next 20 records to be fetched and displayed automatically( again making it a total count of 30 rows of data, that are displayed). I want to do this with an effect attached to it, so that i can visually note that new rows has appeared. Maybe a slideup or fadein+slideup effect can be applied? Hope I make sense.

WHAT I NEED:

I need the PHP & jQuery code to be able to achieve the above effect/functionality. Thanks in advance.

Here's a bit of my jQuery code (if that helps):

$('#button_delete').click(function() {  

  $.ajax({
   type: 'POST',  
   cache: false,
   url: 'test.php',
   data: $('#form1').serialize(), 
   dataType: 'json',
   success: function(data) {            

      if(data.success === 1)
      {
       $.each(data.id, function (index, value) {       

         $('#'+value).remove();
       });   

             jQuery.each(data.new_rows_data, function(i, val) 
            {

                jQuery.each(val, function(i, new_val) 
                {                  
                    $('#table').append('<tr id='+new_val+'>'+

                  '<td></td>'+
                  '<td></td>'+
                  '<td>'+new_val+'</td>'+           
                  '</tr>');   
                });
            });


      }
     }       
   }) 

  return false;
});

PHP code:

<?php
 $from = 0;
 $limit = 30;

$result = mysql_query( "SELECT * FROM mytable ORDER BY m_id ASC LIMIT  $from, $limit" );  
?>

<table>
 <tr>
     <td>ID</td>
     <td>Content</td>
    </tr>   

 <?php
 while( $rows = mysql_fetch_array($result) )
 {
 ?>
 <tr id=<?php echo $rows['m_id']; ?>>
     <td><?php echo $rows['m_id']; ?></td>
     <td><?php echo $rows['content']; ?></td>
    </tr>   
 <?php    
 }
 ?>

</table>

test.php

//test.php

<?php 

$id = $_POST['id'];

if( is_array( $id ) )
{
    $arr_size = sizeof( $id );

    foreach ( $id as $value )
    {
        $sql = "DELETE FROM mytable WHERE id = ".(int)$value." LIMIT 1";
        $result = mysql_query($sql);
    }

    if( $result )
            {
                $success = 1;
                $message = 'Deleted';   
            }
        else
            {
                $success = 0;
                $message = 'Unable to DELETE FROM DB.';             
            }
}

$last_id = 500; 


for($i=1; $i <= $arr_size;  $i++)
{
    $new_value = ($last_id + $i);

    $new_rows[] .= $new_value;

    $res = mysql_query("SELECT id,  message, date 
                       FROM mytable WHERE id = ".(int)$new_value." "); //LIMIT 1

    $row = mysql_fetch_array($res);



    $new_rows_data['row']['id'] .= $row['id'];

    $new_rows_data['row']['message'] .= $row['message'];

    $new_rows_data['row']['date'] .= $row['date'];
}



print json_encode(array('success' => $success, 'message' => $message, 'id' => $id,  'new_rows' => $new_rows,
                        'new_rows_data' => $new_rows_data)); 
?>
+1  A: 

Since you're using AJAX (or ajaj, i guess) to delete the rows, you could also pass in the last id that's currently being displayed to the deletion post page.

Then, instead of just passing back success, you could also pass a json encoded set of rows of the same length as the number deleted and use jquery to append those to your table, setting the last id to the last id of the appended rows.

$('#button_delete').click(function() {  

  $.ajax({
   type: 'POST',  
   cache: false,
   url: 'test.php',
   data: $.extend($('#form1').serialize(), { 'last_id':$('#table tr:last').attr('id') }), 
   dataType: 'json',
   success: function(data) {            

      if(data.success === 1)
      {
       $.each(data.id, function (index, value) {       

         $('#'+value).remove();
       });   
       jQuery.each(data.new_rows_data, function(i, val) 
            {
                 $('#table').append('<tr id='+val.id+'>'+

                  '<td></td>'+
                  '<td></td>'+
                  '<td>'+val.message+'</td>'+           
                  '</tr>');   

            });

      }
     }       
   }) 

  return false;
});

Or something to that effect.

Now you should be able to access the last id in your deletion code via $_POST['last_id']. By changing the post-delete select to:

$res = mysql_query("SELECT id,  message, date 
                   FROM mytable WHERE id > ".(int)$last_id." limit ".$arr_size);

You should get the results after your last one.

Adam Benzan
Hi Adam, Thank you for your response. Since I am already passing the selected row id by means of form serialization, how do I pass the ID of the last visible row?
Devner
Come to think of it, you don't actually need to track that last_id explicitly. $("table tr:last").attr('id') would probably get you the last visible one reliably. (Tho I'd add some classes to data rows and an ID to the table so the selector isn't quite so general.)
Adam Benzan
Hi Adam, I have edited my original post to include the test.php page (the page to which the form is submitted). I modified my code so that I can send $new_rows_data['row']['id'], $new_rows_data['row']['message'] and $new_rows_data['row']['date'] values in the success event and then, in the main the table, populate the new rows with the respective data for each of the rows, but it's not working incorrectly. Instead of filling the data of a single record in a single row, it is creating multiple rows for each of the data received.
Devner
..continued from above... So if I delete 1 record, I was trying to get it to populate 1 new row with the id, message and data values in their respective columns (well my original PHP code shows only 2 columns, sorry about that), but instead, it populates 3 new rows, which is one for id, the second one for message and the third row for the date. So simply put, it's treating each column as a new row and updating my table in an incorrect fashion. I hope I make sense. Hope we can arrive at a solution for this. Thank you so much.
Devner
Then it's probably iterating through the fields of an object instead of objects in a list. Are you using data.new_rows or data.new_rows_data in your success method? It looks like new_rows_data should work alright with that each statement, I'm assuming that ['row'] will eventually be the row id or somesuch.I'd recommend you use firebug or somesuch and use console.log(data) to see what that return object parses into.
Adam Benzan
I have edited my original post and added the code which I use to receive the data back. That shows how I am populating the data. Please let me know what change I need to do, to the existing code. Thank you.
Devner
I've updated the code in my response. See how that goes.
Adam Benzan
Tried out your updated code. It does not let me even submit and get back a response if I use $.extend($('#form1').serialize(), { 'last_id':$('#table tr:last').attr('id') }), The statement seems to be correct but it does not submit the form when used in conjunction with the above code. However, if I use data: $('#form1').serialize(), and hard code a value for last_id (for testing) and delete a single record, then it does get me the next record successfully. But this method has a bug,in that if I delete 2 or more records, then instead of outputting respective number of new records.continued..
Devner
..continued) all the new records data is shown in the same row, when in fact 2 (or as many as deleted) rows should have been appended. Please note that the last_id value has been hard-coded still. I have been Googling around and trying to search docs.jquery.com, but I think my naivety is beating me to this. Hope you will be able to help me out. Appreciate much.
Devner
Hi Adam, figured out the most part of it. I had to call the results in a while loop while in the current code, I don't. So that's fixed. The only part that needs fixing is the one of the non-repeating rows i.e. if I delete 2 or more records, then instead of outputting respective number of new records, all the new records data is shown in the same row. So if I delete 10 rows, then instead of creating 10 rows and populating them with the respective data, it creates 1 row and populates it with the data of 10 rows. Hope I make sense. I think if we can fix this, we will be good to go. Thank you.
Devner