day_dreamer
day_dreamer

Reputation: 834

Form submission using jQuery ajax not working

I have a form generated dynamically using jQuery as below:

<form id="editorform" accept-charset="utf-8" method="post" name="editorform" action="menuupdate">
    <div>
        <input id="updateItem" type="submit" value="Update"></input>
    </div>
</form>

And I have jQuery Ajax code :

$("#editorform").submit(function(event)
        {

    var urls=$("#editorform").attr('action');
    event.preventDefault();
    var postData=$("#editorform").serializeArray();
    $.ajax({
        type:'POST',
        url:urls,
        data:postData,
        async:   false,
        contentType :'application/x-www-form-urlencoded; charset=UTF-8',
        success: function(results){
            alert(results);
        }
        });

    return false;

        });

The ajax call is not getting executed, instead a normal form submission is taking place.

Can anybody help figure out what's wrong with this piece of code?

Any help is greatly appreciated.

Upvotes: 0

Views: 64

Answers (1)

John S
John S

Reputation: 21482

You say the form is dynamically generated. It might be that you are registering the submit-event handler before the form element exists. If that is the case, then $("#editorform") does not represent any elements at that time.

You either have to bind the submit-event handler after the form element is added to the page, or use event delegation to bind the event.

Try changing this:

$("#editorform").submit(function(event)

To:

$(document).on('submit', '#editorform', function(event)

Also, I think you should call .serialize() instead of .serializeArray().

Upvotes: 1

Related Questions