jQuery - Call an ashx web service and delete the current row if it succeeds


Scenario:

You are using a generic handler (ashx IHttpHandler) to execute some operation. You want to call this from jQuery and then remove or alter an element in the page if this is successful.

Solution:

In this example I'll use the onclick event on an HTML element to call a function that executes some jQuery to call the handler and then remove the current row from the table if it is successful. The handler will return "error" if there is an error an "ok" if it completes it's operation successfully. This example assumes you have jQuery included on your page already.

jQuery/JavaScript:

<script type="text/javascript">
    function removeEntry(o, id) {
        $.get("/WebServices/Core.ashx?query=dl&id=" + id, function (html) {
            if (html != 'ok') {
                alert('An error occured deleting that log entry.');
                return false;
            } 
            $(o).closest('tr').remove();
        });
    }
</script>

HTML/ASP.Net:

<td>
    <a href="#" onclick="removeEntry(this, <%#Eval("log_id")%>);">Delete</a>
</td>

The above will call the "removeEntry" function when the link is clicked and pass it a log id that was bound to the link and pass in the current object. The jQuery finds the closest row to that element and removes it if an ok is returned to the server.

Note:

This was a bare bones example. You'll want to make sure your service is secured properly and you'll also want to make sure you parameterize/sanitize any input you might be using in tandem with a database operation to avoid SQL injection exploits.