Trevor Arjeski
Trevor Arjeski

Reputation: 2168

Why isn't this function ever being reached?

Why isn't the function with fadeOut ever being reached? Every time the function runs it refreshes the page instead of using AJAX.

<script type="text/javascript">


function deleterow(id){
if (confirm('Are you sure want to delete?')) {
$.post('delete.php', {id: +id, ajax: 'true' },
function(){
$("#row_"+id).fadeOut("slow");
});
}
}

</script>

Here is the html output by php:

<button onclick="deleterow('.$entry['rowid'].')" class="fg-button fg-button-icon-left ui-state-default ui-corner-all"><span class="ui-icon ui-icon-trash"></span></button>

Upvotes: 0

Views: 112

Answers (1)

prodigitalson
prodigitalson

Reputation: 60413

Its hard to say for certain without seeing the code/html that invokes the function but I assume this is attached to an onclick handler somehow. Therefore if you do not prevent the default action (following the href of the a tag) its going to refresh the page. You need to return false from the handler function or callevent.preventDefault() from it.

I would use this markup instead:

<button 
  value="$entry['rowid']"
  class="fg-delete fg-button fg-button-icon-left ui-state-default ui-corner-all">
  <span class="ui-icon ui-icon-trash"></span>
</button>

By encoding the rowid in the dom (in this case as value) we can access it in our functions without having to hard code it into the function call and keep the handler unobtrusive.

// pulling this into a full definition for clarity
// you could of course just use an anon function inside you $.click call
function handleDelete(event){
   event.preventDefault();
   var $this = $(this);
   var rowId = $this.val();
   deleterow(rowId);
   return false;
}


$('button.fg-delete').click(handleDelete);

Demo: http://jsfiddle.net/eBa7v/1/

Upvotes: 3

Related Questions