Alan Buchanan Alan Buchanan - 1 month ago 27
Ajax Question

Ajax.BeginForm JavaScript callback with parameter causes $(this) to refer to window instead of form

I am using the following code to create a form with JS callbacks:

@using (Ajax.BeginForm("Example", "Example", null, new AjaxOptions
{
HttpMethod = "POST",
OnBegin = "ajaxFormBegin",
OnSuccess = "ajaxFormSuccess(data, status, xhr, 'exampleValue')"
}


I have found that if I don't pass a parameter to the callback, as is the case with the OnBegin callback, then the JQuery $(this) variable refers to the calling form.

If I do pass a parameter, as is the case with the OnSuccess callback, $(this) refers to the window. I want it to refer to the form as in the first scenario.

function ajaxFormBegin() {
$form = $(this); // Refers to calling form
}
function ajaxFormSuccess(data, status, xhr, callback_) {
$form = $(this); // Refers to window
}


Is this expected behavior or is my implementation wrong?

Answer

Your assignment to OnSuccess is a function call in global context.

@using (Ajax.BeginForm("Example", "Example", null, new AjaxOptions
{
    HttpMethod = "POST",
    OnBegin = "ajaxFormBegin",
    OnSuccess = "ajaxFormSuccessWrapper"
}

<script>
function ajaxFormSuccessWrapper(data, status, xhr) {
  var form = this; 
  ajaxFormSuccess(data, status, xhr, 'exampleValue'); 
}
</script>
Comments