Welcome Guest, Not a member yet? Register   Sign In
Ajax if no result return empty
#1

When I need to delete a file I delete it via ajax.

Lets say I have two files I can delete the second one OK. But then when I want to delete the last file it deletes it from the database table and uploads folder OK.

However it still shows the very last result on list even though there is no record of it any more.

How can I make sure that when I delete the last result that the ajax will remove the last result 

I did think about using $('#file-attachments tbody').html(""); But not sure where to place it if can not find any more results.


Code:
<script type="text/javascript">
$(document).ready(function() {

    $(document).on('click', '#delete_button', function () {
         $.ajax({
            url: "<?php echo base_url('extensions/attachments/delete');?>",
            type: 'post',        
            dataType: 'json',
            data: {
                attachment_id: $(this).attr("data-id"),
                posthash: $('#posthash').val()
            },
            success: function(json) {
                if (json['success'] == true) {
                    $.each(json['attachments'], function( key, value ) {
                        info = '<tr>';
                        info += '<td>';
                        info += value['orig_name'];
                        info += '</td>';
                        info += '<td>';
                        info += value['file_size'] + 'KB';
                        info += '</td>';
                        info += '<td class="text-center">';
                        info += '<button type="button" id="delete_button" class="btn btn-danger" data-id="' + value['attachment_id'] +'"><i class="fa fa-trash-o" aria-hidden="true"></i></button>';
                        info += '</td>';
                        info += '</tr>';
                    });    

                    $('#file-attachments tbody').html(info);
                }
            },
        });
    });


    $('#add_attachment').on('click', function() {
        
    $('#form-upload').remove();

    $('body').prepend('<form enctype="multipart/form-data" id="form-upload" style="display: none;"><input type="file" name="file" /></form>');

    $('#form-upload input[name=\'file\']').trigger('click');
        
    $('#form-upload input[name=\'file\']').on('change', function() {
            
        var formData = new FormData($(this).parent()[0]);
        formData.append('posthash', $("#newreply #posthash").val());

        $.ajax({
            url: "<?php echo base_url('extensions/attachments/upload');?>",
            type: 'post',        
            dataType: 'json',
            data: formData,
            cache: false,
            contentType: false,
            processData: false,        
            success: function(json) {
                if (json['error']) {
                    alert(json['error']);
                }
                            
                if (json['success']) {
                        
                    $.each(json['attachments'], function( key, value ) {
                        info = '<tr>';
                        info += '<td>';
                        info += value['orig_name'];
                        info += '</td>';
                        info += '<td>';
                        info += value['file_size'] + 'KB';
                        info += '</td>';
                        info += '<td class="text-center">';
                        info += '<button type="button" id="delete_button" class="btn btn-danger" data-id="' + value['attachment_id'] +'"><i class="fa fa-trash-o" aria-hidden="true"></i></button>';
                        info += '</td>';
                        info += '</tr>';
                    });    

                    $('#file-attachments tbody').append(info);
                }
            },            

            });
        
        });
    });    
});

</script>


Controller Function
PHP Code:
public function delete()
{

    
$data = array('success' => false'attachments' => '');

 
   if ($this->input->post('attachment_id'))
 
   {
 
       $data['success'] = true;

 
       $get $this->attachment_model->getattachment($this->input->post('attachment_id'));

 
       if (unlink(FCPATH 'uploads/' $get['path']))
 
       {
 
          $this->attachment_model->deleteattachment($this->input->post('attachment_id'));
 
       }

 
       $attachments_results $this->attachment_model->getattachmentsfornewreply($get['posthash']);

 
       foreach ($attachments_results as $attachment)
 
       {
 
           $data['attachments'][] = array(
                
'attachment_id' => $attachment['attachment_id'],
                
'post_id' => $attachment['post_id'],
                
'posthash' => $attachment['posthash'],
                
'file_name' => $attachment['file_name'],
                
'orig_name' => $attachment['orig_name'],
                
'file_size' => $attachment['file_size'],
 
               'path' => $attachment['path'
 
           );
 
       }
 
   }

 
   echo json_encode($data);

There's only one rule - please don't tell anyone to go and read the manual.  Sometimes the manual just SUCKS!
Reply
#2

Oh damn it. I just wrote a long answer and accidentally closed the browser :-(

Anyway, the long and short of it was that I think your each loop might fail depending on how your model returns attachments to your controller.

I would not have any html in my js, I think it is ugly and hard to maintain. Instead, in your controller get your attachments, then load a partial view into a variable called something like 'attachments_tbody' and return that. Then in your js code just output the tbody contents to the page.

In this way you can easily deal within the view of the case of there being no attachments. ie a message like '<tr><td>no attachments to display</td></td>'

In that way your js is clean of html, you can have much easier control over the behaviour and layout from within a view file, and it is much simpler to deal with the case of no attachments.

Alternatively, test to see if there are any attachments returned in your js and output relevant html message from there. But personally I feel that putting html into js becomes messy and unmanageable over time. I try to keep all my html in views or partial views, and not in the controllers or js.

Hope that helps,

Paul.

PS Hopefully I won't delete this before I manage to click the save button this time.
Reply
#3

I agree with PaulD.
When the AJAX action's goal is deleting an attachment, there is no need to rebuild the complete table with JS or JSON. Why don't you just remove the table row (<tr> element ) that contains the items that were deleted? JQuery can find the parent element and remove it. The actual removal of the database record and attachment(s) in the file system is done by your php script (server side).
Reply
#4

(06-28-2017, 11:20 AM)PaulD Wrote: Oh damn it. I just wrote a long answer and accidentally closed the browser :-(

Anyway, the long and short of it was that I think your each loop might fail depending on how your model returns attachments to your controller.

I would not have any html in my js, I think it is ugly and hard to maintain. Instead, in your controller get your attachments, then load a partial view into a variable called something like 'attachments_tbody' and return that. Then in your js code just output the tbody contents to the page.

In this way you can easily deal within the view of the case of there being no attachments. ie a message like '<tr><td>no attachments to display</td></td>'

In that way your js is clean of html, you can have much easier control over the behaviour and layout from within a view file, and it is much simpler to deal with the case of no attachments.

Alternatively, test to see if there are any attachments returned in your js and output relevant html message from there. But personally I feel that putting html into js becomes messy and unmanageable over time. I try to keep all my html in views or partial views, and not in the controllers or js.

Hope that helps,

Paul.

PS Hopefully I won't delete this before I manage to click the save button this time.

Hi, Just to let you know after working on it for half hour today I have it solved.

I create a get function on view for ajax that just gets the files / attachments

PHP Code:
function getattachments() {
    $.
ajax({
        
url"<?php echo base_url('extensions/attachments/getattachments');?>",
        
type'post',        
        
dataType'json',
        
data: {
            
posthash: $('#posthash').val()
        },
        
success: function(json) {

            
info '';
            
            $.
each(json['attachments'], function( keyvalue ) {
                
info += '<tr>';
                
info += '<td>';
                
info += value['orig_name'];
                
info += '</td>';
                
info += '<td>';
                
info += value['file_size'] + 'KB';
                
info += '</td>';
                
info += '<td class="text-center">';
                
info += '<button type="button" id="delete_button" class="btn btn-danger" data-id="' value['attachment_id'] +'"><i class="fa fa-trash-o" aria-hidden="true"></i></button>';
                
info += '</td>';
                
info += '</tr>';
            });    

            $(
'#file-attachments tbody').html(info);
            
        },
    });


Then I return the function in success part of this ajax

PHP Code:
$(document).on('click''#delete_button', function (e) {
    
e.preventDefault();

    $.
ajax({
        
url"<?php echo base_url('extensions/attachments/delete');?>",
        
type'post',        
        
dataType'json',
        
data: {
        
attachment_id: $(this).attr("data-id"),
        
posthash: $('#posthash').val()
        },
        
success: function(json) {
                return 
getattachments();
        },
    });
}); 

Of course I have had to make a getattachments function on controller that just gets the attachments for this post.
There's only one rule - please don't tell anyone to go and read the manual.  Sometimes the manual just SUCKS!
Reply




Theme © iAndrew 2016 - Forum software by © MyBB