Question

Note : I have titled it very poorly, please help me improve it, if you understand my question

I am using ajaxform submit for all of my forms. I am able to programatically add a feedback div to each form successfully. I want to select only current form in my page. I am using following code.

 $('form').append('<div class="feedback" />');
    $('form').ajaxForm
    ({      
        success: function(responseText)
        {
            if(responseText=="1")
            {           
                $(this).clearForm();
                $(this).children('INPUT,select').eq(0).focus();
            }
            else    
            {
                alert($(this).children().length); // This gives me 0
                $(this).children('.feedback').eq(0).html(responseText); 
            }
        }
    });

I can do the above successfully only if I have one form in whole page using $('form') instead of $(this) but it makes problem when i have multiple forms in a page

Was it helpful?

Solution

If you look closer at the docs, will see that the success callback is passed 4 arguments

1.) responseText or responseXML value (depending on the value of the dataType option).
2.) statusText
3.) xhr (or the jQuery-wrapped form element if using jQuery < 1.4)
4.) jQuery-wrapped form element (or undefined if using jQuery < 1.4)

Use the last argument instead of $(this) for current form instance

See options tab of docs

Update by asker : working code from above answer I got is following

Instead of $(this) I could do following

$('form').append('<div class="feedback" />');
var options = { success: showResponse  };
$('form').ajaxForm(options);
function showResponse(responseText, statusText, xhr, $form)
{
    if(statusText == 'success')     
        $form.children('.feedback').html(responseText);
}

Link of example followed

OTHER TIPS

$(this) will only work if the context of the invocation for the success callback is the form node itself.

If it's not working, you can always cache the reference and you will have access to it in the scope of your callback:

var $form = $('form');

$form.ajaxForm({
    success: function (responseText) {

        $form.clearForm();

    }
});

I did not include your logic with the response because response is an object with several unique properties. See the answer by @charlietfl for the properties

------ UPDATE ---------

If the problem you have is that you need access to that form after appending the div, remember that "append", along with all other jQuery methods affecting a node, are chainable:

$('form').append('<div>My Div</div>').ajaxForm(options....)

Hopefully the context of the invocation of the success handler is the form node itself, if not you can cache the reference as I did above.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top