Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

submit a form via Ajax using prototype and update a result div

I'm wondering how can I submit a form via Ajax (using prototype framework) and display the server response in a "result" div. The html looks like this :

<form id="myForm" action="/getResults">
    [...]
    <input type="submit" value="submit" />
</form>
<div id="result"></div>

I tried to attach a javascript function (which uses Ajax.Updater) to "onsubmit" (on the form) and "onclick" (on the input) but the form is still "non-Ajax" submitted after the function ends (so the whole page is replaced by the results).

like image 924
Vinze Avatar asked Jan 14 '09 15:01

Vinze


1 Answers

Check out Prototype API's pages on Form.Request and Event handling.

Basically, if you have this:

<form id='myForm'>
.... fields ....
<input type='submit' value='Go'>
</form>
<div id='result'></div>

Your js would be, more or less:

Event.observe('myForm', 'submit', function(event) {
    $('myForm').request({
        onFailure: function() { .... },
        onSuccess: function(t) {
            $('result').update(t.responseText);
        }
    });
    Event.stop(event); // stop the form from submitting
});
like image 66
Paolo Bergantino Avatar answered Sep 23 '22 12:09

Paolo Bergantino