When you submit a form, the next page displayed is normally the "success" or "thanks" page. This is the easiest approach, and usually it is a perfectly reasonable approach. This is what you will get by default when you set up a form as described in Creating Forms for User Submissions.
There are times, however, when you want to submit the form but stay on the same page. For example, you might have a small contact form in the sidebar of a page, and want to continue to display that page after the form is submitted.
There's a few steps to converting a form submission to use an Ajax submit:
Here's an example that illustrates the first three items above:
<div id="form_success"></div> <div id="form_errors"></div> <div id="form_wrapper"> <form ...> (normal form code goes here) <input type='hidden' name='contact[ajax]' value='json' /> </form> </div>
The only change we've made to the form itself is to add a hidden form element with the name
contact[ajax] whose value is set to
json. This tells the Webvanta system that you want to perform an Ajax submit, and that you'd like the results delivered in json format. Make sure to adjust the name attribute's prefix of
contact to be what-ever name prefix your form actually uses.
Here's a summary of what this code is doing:
postfunction performs the ajax submit. The parameters are:
Most of the complexity is in the function that processes the response—in particular, in dealing with any errors. Webvanta returns two objects:
dataobject, which contains:
data.status) that will contain the string "ok" if all went well.
data.errors) that explain any validation errors.
textStatus) that explains what went wrong, if there was some sort of communication or server error.
Now that we understand these two objects, the actions performed by the result-processing function are clear. If the status is "ok", meaning that the form was successfully submitted:
If the submit fails, things are a little more complicated. The code:
data.errorsarray), display them. In the example here, we've formatted them in an unordered list.
data.errorsis empty), then there must have been some sort of communication or server error, so display the textStatus string.
If you have only one form on the page, and you name your
form_id is the ID of the form you want to work with.