Incomplete Execution of Callbacks on JQuery POST

In JQuery, you can use the $.post() function to make a client-side AJAX request (more info here).

If you want to POST JSON objects to your server, you basically want to do something like this:

$.post( URL, [data], [CALLBACK FUNCTION], "json")

In the project that I’m working on, I’m rendering a table using JQuery + DataTables plugin. I wanted to embed a button in each row so that the user can selectively delete rows. My onclick function looks something like this:

var row = the tr node of the row where the delete button was clicked
$.post("myURL/",
		{key : value},
		function (jr) {
			if(jr['success'] == true) {
				oTable.fnDeleteRow(oTable.fnGetPosition(row));
			} else {
				alert("Error!!");
			}
		},
		"json");

Basically, I’m making a POST request to the server, sending it the dictionary {key : value}. Upon successful completion of the POST, the inner function will execute.

Unfortunately, when I tried to run this in Firefox, the callback function never executes the delete row line. When I debugged it with Firebug, it would always enter the callback function, but it would never execute oTable.fnDeleteRow(oTable.fnGetPosition(row));

The problem lies in fact that we’re working with asynchronous method invocations. The execution looks something like this:

Execute the onclick function -> make the POST request -> onclick function completes, so trash it -> POST response comes in from server -> execute the callback function.

We’re telling JQuery to delete row X from the table when we get a successful POST response, but the variable row will be out of the scope of the current context by this time. The onclick function would have finished executing and row would be long gone by now.

The ugly fix to this problem would be to pass the variable through to a separate function, like this:

var row = the tr node of the row where the delete button was clicked
$.post("myURL/",
		{key : value},
		function (jr) {
			if(jr['success'] == true) {
				deleteRow(row);
			} else {
				alert("Error!!");
			}
		},
		"json");

function deleteRow(row) {
	oTable.fnDeleteRow(oTable.fnGetPosition(row));
}
This entry was posted in Javascript, Tech and tagged , , , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>