3

I am trying to submit a form thru javascript on the fly (using jquery-form)

Is it possible to create 'FORM' update bunch of values in that 'FORM' using javascript without having HTML-form ?

Niger
  • 3,916
  • 5
  • 30
  • 30

4 Answers4

5

I'm going to guess that what you're asking is 'Can I perform an HTTP POST without using an HTML form?' The answer is yes.

Check out jquery's $.post(). It would look something like this:

$.post(url, { value1: "foo", value2: "bar" } );

Where the variable names you're passing are value1/value2 with their corresponding values.

Here's the jquery reference: $.ajax

T. Stone
  • 19,209
  • 15
  • 69
  • 97
3

This code will create a form on the fly, populate it with the data passed in and submit it (as a regular HTTP POST). This should be what you need.

var postRequest = function (uri, data) {

    data = data || {};

    var form = $('<form method="post" class="js:hidden">').attr('action', uri);

    $.each(data, function(name, value) {
        var input = $('<input type="hidden">')
            .attr('name', name)
            .attr('value', value);
        form.append(input);
    });

    $('body').append(form);
    form.submit();
};
LukLed
  • 31,452
  • 17
  • 82
  • 107
sandstrom
  • 14,554
  • 7
  • 65
  • 62
2

I think you mean one of the following two things:

  1. Can I create a <form> element using javascript?
    A: Yes, you can.
    Use jQuery DOM manipulation functions to do that.

  2. Can I submit values to a server side script like a <form> would?
    A: Yes, you can.
    Use jQuery Ajax functions to do so. More specifically, jQuery.post() is your friend.
    jQuery form plugin can come in handy if you want to do something in between these two options.

Cheers!

jrharshath
  • 25,975
  • 33
  • 97
  • 127
  • 1
    That first point is extremely bad advise even if easily possible, because it completely destroys accessibility. If people cannot figure how to perform destructive actions on their own there is less harm to the world in lying to them by saying that it cannot be done until they learn otherwise by advancing their own abilities independently. –  Sep 12 '09 at 11:45
  • I'm not saying that using these function blindly will result in the perfect solution. These are the tools. In the hands of a master, they can create a perfect solution in terms of accessibility and graceful degradation. Consider: replacing links to `rename item` with renaming ajax forms, if the user agent is capable of interpreting the interface. – jrharshath Sep 12 '09 at 17:02
1

You can post all the values in the form through

$.ajax({url: XXX, data: { formField1: "value" }})
Jan Jongboom
  • 26,598
  • 9
  • 83
  • 120