user1151
user1151

Reputation:

How do I inject a form value with jQuery?

I am working with jQuery Form and ASP.NET MVC. Preview 5 of ASP.NET MVC has an Extension Method on HttpRequest called IsAjaxMvcRequest that detects if the POST was an Ajax request. This Extension Method basically "sniffs" for a form value called __MVCASYNCPOST and (basically) returns true if it sees this element.

What I want to do is inject this value using script (I can't use a hidden field as it defeats the purpose) into the form post - and I don't know how to do that with jQuery.

Here's my code:

<script type="text/javascript">
    $(document).ready(function() {

        $('#jform').submit(function() {
             //add a flag for asynch submit
             //" __MVCASYNCPOST
            $('#jform').ajaxSubmit({ target: '#results2' });

            return false;
        });
    });
</script>

I really should know how to do this :) but I don't! Also - an economy of code is required here so less LOC is appreciated.

Upvotes: 4

Views: 992

Answers (1)

John Millikin
John Millikin

Reputation: 200766

ajaxSubmit() accepts a data parameter with additional key-value pairs to send.


Additionally, there is a better way to test server-side if the request is an AJAX request. jQuery sets the HTTP header X-Requested-With to XMLHttpRequest. You can change your extension method to test for that instead of a custom field.

Upvotes: 8

Related Questions