Alec
Alec

Reputation: 9078

Process form data using jQuery

I'm currently using Prototype, but I'd like to rewrite this function to jQuery:

function post(div,url,formId) {
  new Ajax.Updater(div, url, {
    asynchronous:true, 
    parameters:Form.serialize(formId)
  });
}

HTML example that goes with it:

<form method="post" action="" id="foo" 
  onsubmit="post('result','getdata.php','foo');return false;">
  <input type="text" name="data" />
</form>
<div id="result"></div>

I've been looking at jQuery.load() and jQuery.post(), but I'm not sure which one to use and how exactly.

Thanks in advance for your help.

Upvotes: 1

Views: 13429

Answers (3)

Caner
Caner

Reputation: 1

You can't send "multipart/form-data" forms with jquery because of security problems. You must do it with flash or iframe...

Upvotes: -3

Paolo Bergantino
Paolo Bergantino

Reputation: 488434

With this HTML:

<form method="post" action="getdata.php" id="foo">
  <input type="text" name="data" />
</form>
<div id="result"></div>

You can do this with jQuery:

$(function() { // wait for the DOM to be ready
    $('#foo').submit(function() { // bind function to submit event of form
        $.ajax({
            type: $(this).attr('method'), // get type of request from 'method'
            url: $(this).attr('action'), // get url of request from 'action'
            data: $(this).serialize(), // serialize the form's data
            success: function(responseText) {
                // if everything goes well, update the div with the response
                $('#result').html(responseText);
            }
        });
        return false; // important: prevent the form from submitting
    });
});

The reason I got rid of the onsubmit code is because it is considered bad practice to have inline JavaScript like that. You should strive to make your forms free of JavaScript and then bind all the JavaScript away from it. This is known as unobtrusive JavaScript and it is a Good Thing.

EDIT:

Since you have that code in many pages, this is a function that will do what you want using the same signature you currently have on the post function. I recommend you take a few hours to update all your forms over keeping this, but here it is anyways:

function post(div,url,formId) {
    $.post(url, $('#' + formId).serialize(), function(d) {
        $('#' + div).html(d);
    });
}

As far as your problem, the livequery plugin could help you there. Alternatively, it is as simple as encapsulating the binding code in a function and calling it whenever a form is added.

Upvotes: 8

John Sheehan
John Sheehan

Reputation: 78124

Use this and get rid of the onsubmit attribute in your HTML:

$(document).ready(function() {
    $("#foo").submit(function() {
        $.post($(this).attr("action"), $(this).serialize());
        return false; // prevent actual browser submit
    });
});

jQuery serialize method docs

Upvotes: 0

Related Questions