Modifying form values with beforeSubmit with jQuery ajaxSubmit?
Asked Answered
G

4

7

I have a form I am submitting using jQuery's ajaxSubmit function from the Forms plugin. I'm trying to add a form name/value pair to the form data just before submission occurs. My plan is to modify the form data in the beforeSubmit event handler.

Given a function that looks like:

function handleActionFormBeforeSubmit(formData, form, options) {
    // Add a name/value pair here somehow to formData
}

How do I add a simple pair to formData? It is an array in the form of:

[ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]

Thanks, Brian

Gorton answered 29/10, 2008 at 15:38 Comment(0)
G
16

After an hour of experimentation, I figured out a solution. To append a value to the form data, the following code will work.

function handleActionFormBeforeSubmit(formData, form, options) {

    // Add a name/value pair indicating this is an asynchronous call.
    // This works with the ASP.NET MVC framework's Request.IsMvcAjaxRequest() method.
    formData[formData.length] = { "name": "__MVCASYNCPOST", "value": "true" };
}

You can also modify the data if you know the index of the value you want to change such as:

formData[0].value = 'new value';

I hope this helps someone else.

Gorton answered 29/10, 2008 at 17:55 Comment(0)
W
7

This is fine:

formData.push({ "name": "__MVCASYNCPOST", "value": "true" });
Woodpile answered 2/11, 2009 at 3:43 Comment(0)
F
1

formData[0].value = 'new value'; is working fine in AjaxSubmit(). I had implemented same while upload file content dynamically. Earlier after so many time, form send blank data into server, so this code helpful to change before submit your form.

Fletcher answered 24/2, 2014 at 11:14 Comment(0)
F
0

For some reason changing the data in the beforeSubmit callback didn't work for me when I encountered this problem.

However assigning an object to "data" in the form options caused this object to be appended to the serialised data. This is not documented explicitly on the jquery form website but is part of the underlying $.ajax method.

Fantasy answered 8/2, 2010 at 12:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.