black_belt
black_belt

Reputation: 6799

Deleting database records using jQuery AJAX is not working

I am trying to delete records from database without reloading the page. In the view file I have the following code. But when I click on the delete link nothing happens. Would you please kindly help me find out where I have done wrong?

Thanks in advance.

My view file:

<script  type="text/javascript">
    $(function(){ // added
        $('a.delete').click(function(){
            $.ajax({
                var a_href = $('selector').attr('href');
                type: "POST",
                url: "<?php echo base_url(); ?>student_fee_status/payment_info_delete",
                data: "id="+a_href,
                success: function(html){
                    $("#show").html(html);
                }
            });
         return false
        });
    }); // added
</script>


<?php if(count($records) > 0) { $i = 0; foreach ($records as $row){ $i++; ?>

<span> <?php echo $row['fee_type']; ?> : <?php echo $row['fee_amount']; ?> [<a id='<?php echo "$paymentid" ;?>'  
  class='delete' href='#'>Delete</a>]</span> <br>

<?php  }} ?>            

This is my Controller:

function payment_info_delete(){

    $id = mysql_real_escape_string($_POST['id']);//Some clean up :)

    $query= $this->db->delete('studentpayment2', array('pid' => $id)); 

    echo "$id";

}

Upvotes: 0

Views: 1364

Answers (3)

Anthony Grist
Anthony Grist

Reputation: 38345

As mgraph pointed out in his answer, the var a_href = $('selector').attr('href'); line is incorrect. You want to replace 'selector' with this so that you're getting the href attribute from the anchor that was clicked on.

That said, I think that's still probably wrong - surely you want to be passing back the id of the entry to delete, which seems to be stored in the id attribute of the anchor tag, rather than always passing back a # symbol?

To pass the id back instead, rather than the href, replace this: var a_href = $('selector').attr('href'); with this: var a_href = this.id;

Upvotes: 1

Mazatec
Mazatec

Reputation: 11649

  1. You need to put the 'var a_href...' line outside of the ajax function
  2. You need to replace the word selector with this which refers to the currently clicked element.

    var a_href = $(this).attr('href'); $.ajax({...

Upvotes: 1

mgraph
mgraph

Reputation: 15338

var a_href = $('selector').attr('href');
$.ajax({...

Upvotes: 1

Related Questions