Question

I am using ajaxform to handle my form submissions and have encountered a problem with the option variable. I am trying to have the success callback append some HTML to a relative element, as such I am using the $(this) approach as I would do normally. I can't get it to work, am I missing something simple here? Is there any reason why $(this) will not work? The plugin url is http://malsup.com/jquery/form/

Thanks in advance

A

The selector references the element so on submit the ajaxform plugin fires. It is as follows $('#formSEIncome').ajaxForm(options)

The options jQuery is as follows:

var options = {             
       success: function() { 
       $(this).parents('.trm_expense_cats').find('.itemlist').append('<li>Test</li>');
        alert('ok');
    }   // post-submit callback 
};
Was it helpful?

Solution 2

The answer to this is to use the provided success functionality in the jQuery plugin rather than what I did above. So

Event handler:

$('#formSEIncome').ajaxForm(options)

Options variable:

var options = { 
        target:        this  // target element to be updated with server response 
        ,success:       showResponse          
}; 

Success function:

function showResponse(responseText, statusText, xhr, $form)  { 
$form.parents('.trm_expense_cats').find('.itemlist').append('<li>Test</li>');
    alert('ok');
}

As such the use of this in the options.success object solved the problem.

OTHER TIPS

this is set by each function when it is invoked. Your code looks like this:

// OUTSIDE the callback

var options = {             
       success: function() { 
         // INSIDE the callback
         $(this).parents('.trm_expense_cats').find('.itemlist').append('<li>Test</li>');
         alert('ok');
    }
};

// OUTSIDE the callback
$('#formSEIncome').ajaxForm(options)

You probably expect that this is the same value both inside and outside the callback, but it is not. The callback sets its own value of this depending on how it is invoked. Here, the callback decides the value of this inside the callback when it runs.

If you want to save your "outer" this, see $(this) inside of AJAX success not working for how to use $.proxy. You can also save your outer this in a variable (often named that) outside your callback. Since JavaScript functions have access to the variables of their containing functions, the callback will have access to that:

// OUTSIDE the callback
// save outer this
var that = this;

var options = {             
       success: function() { 
         // INSIDE the callback
         // we use that, not this, to get the outer this
         $(that).parents('.trm_expense_cats').find('.itemlist').append('<li>Test</li>');
         alert('ok');
    }
};

// OUTSIDE the callback
$('#formSEIncome').ajaxForm(options)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top