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

39,946

Solution 1

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
});

Solution 2

You need to return the value false from the ajax function, which blocks the standard form submit.

<form id="myForm" onsubmit="return myfunc()" action="/getResults">


function myfunc(){
   ... do prototype ajax stuff...
  return false;

}

Using onsubmit on the form also captures users who submit with the enter key.

Solution 3

You first need to serialize your form, then call an Ajax Updater, using POST options and pass it the serialized form data. The result will then appear in the element you sepcified.

Share:
39,946
Vinze
Author by

Vinze

Updated on December 29, 2020

Comments

  • Vinze
    Vinze over 3 years

    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).

  • Vinze
    Vinze over 15 years
    I did the "return false" in the function but I was missing the return above the function in onsubmit...
  • AntonioCS
    AntonioCS about 15 years
    I thinks this answer is better than the selected answer because this way you do everything in the javascript side. There is no adding onsubmit="return myfunc()" to the form
  • Reed Richards
    Reed Richards about 15 years
    Couldn't agree more separation is vital!
  • gatoatigrado
    gatoatigrado over 14 years
    N.B. -- prototype is not compatible with file uploads submission through Ajax. See ruby-forum.com/topic/136931 .
  • gatoatigrado
    gatoatigrado over 14 years
    another note -- you might want to call Event.stop() first, in case you encounter an exception.
  • texmex5
    texmex5 almost 14 years
    This worked for me. Although since I am a total Javascript newbie, it took me some time to realize that in order for this to work. The javascript has to appear after the form in my source or after the items have been created dynamically.
  • Ricardo Martins
    Ricardo Martins about 11 years
    The way that @Paolo said it already serializes our form and send it.