2

I am using jquery validate with a form. I want to submit the form using ajax. When I put the ajax call in validate's submitHandler() The browser hangs. What's going on?

The error message I get when I enable the validate method's debug is:

uncaught exception: [Exception... "Illegal operation on WrappedNative prototype object" nsresult: "0x8057000c (NS_ERROR_XPC_BAD_OP_ON_WN_PROTO)" location: "JS frame :: http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js :: f :: line 132" data: no]

Which is too arcane for me to make sense of.

Some code:

$(document).ready(function() {
$("#loginForm").validate({
        debug: true,
        errorLabelContainer: $('div.error'),
        wrapper: 'li',
        rules:  {
            last_name: {
                required: true
            }
        },
        messages: {
            last_name: {
                required: "Please enter your last name."
            }
        },
        submitHandler: function(form){
            $.ajax({
                type: "POST",
                url: "test.php",
                data: form,
                success: function(msg){
                    console.log( "Data Saved: " + msg );
                },
                error: function(msg){
                    console.log( "Error: " + msg);
                }
            });
        }
    });

});

The form is a very vanilla form. Submitting via a standard POST works fine. Also, the validation works fine... it's just the submitting with ajax part that fails me.

1
  • You say the browser hangs, I'm wondering what's happening during that time. Is your server side code running? Or are we still client side? Have you put a debugger of some sort in your server side code where this request is processed? Commented Oct 28, 2010 at 3:51

3 Answers 3

3

You'll probably want to serialise that form before sending it - you probably don't want to send a DOM object

edit RE:comment - to select only some inputs and serialize -

$(form).find(":input[name=inp1] :input[name=inp2]").serialize()
Sign up to request clarification or add additional context in comments.

3 Comments

How would I do this (and why)?
because you don't want to send the dom object any more than you want to send the first link on the page - it just doesn't make sense. You want to send the key-value pairs of what the user has entered, which is just a very small part of the information in the DOM (which includes the CSS properties, position on the page, child nodes, parent nodes and anything else you can access through javascript to do with the DOM). The easiest way to serialize a form is to use $(form).serialize()
This seems to be working! Do you know how to access only certain elements of the serialized data?
3

call ajax method with php function

<script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script>

class Ajax{
public function submitForm($data=array()){
    //form - name attribute
    //do   - ajax page do_
    // get - ajax result
    return '<script language="javascript" type="text/javascript">
                $(document).ready(function (data){
                    $(\'form[name='.$data['form'].']\').validate({
                            submitHandler: function(form) {
                                $.ajax({
                                    method : \'post\',
                                    url    : \'' . AJAX_PATH . ''. $data['do'].'\',
                                    data   : $(this).serialize(),
                                    dataType : \'html\',
                                    success : function(data){
                                        $(\'form[name='.$data['form'].']\').slideUp(1000);
                                        $(\''. $data['get'] .'\').html(data).fadeIn(1000);
                                        //$(\''. $data['get'] .'\').html(data).fadeIn(1000);
                                    },
                                    error : function(data) {alert(\'missing file\'); }
                                });
                                return false;
                             }
                    });
                });
            </script>';
}

}

$ajax = new Ajax();

<?php echo $ajax->submitForm(array('do'=>'do_register.php','form'=>'register','get'=>'#message'));?>

Comments

2

Just to elaborate of tobyodavies answer. You might want to change your submission to

        $.ajax({
            type: "POST",
            url: "test.php",
            data: $(form).serialize(),
            success: function(msg){
                console.log( "Data Saved: " + msg );
            },
            error: function(msg){
                console.log( "Error: " + msg);
            }
        });

The ajax function expects the data option to be a string (not entirely true but for this case it's fine) while your passing in the forms dom object.

5 Comments

Thanks for the answer. Do you know how to access only certain elements of the serialized data?
I'm not exactly sure what you mean. If you only want to serialize a subset of the form elements then you can select those a serialise that instead i.e $('#name,#email,#phonenumber').serialize() will serialize the name, email and phonenumber form elements
I'm not able to receive files if data : $(form).serialize() is use. How can i upload files using ajax.
@KetavChotaliya you basically can't. You'll need to handle these specially. It's possible to handle file upload using XHR2 if your browser support requirements allow it, otherwise you'll commonly create an iframe and submit the form using the iframe as the target (i.e target="iframe-name"). There's a decent number of libraries which should obfuscate these details for you though.
@Toby it is done with these two lines. contentType: false, processData: false,

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.