Note that there are some explanatory texts on larger screens.

plurals
  1. POAjax form submission in symfony2 with graceful degradation for users without javascript
    text
    copied!<p>I am building a web application that involves forms. The framework being used is symfony2. I would like to have everything working for users without javascript, and then progressively enhance the experience for people with javascript enabled. I am planning to use JQuery as my javascript library.</p> <p>I would like to have forms where it submits and displays a message using the FlashMessage component if the user does not have javascript and the request is not an ajax request.</p> <p>For users with javascript support, I would like to return the message to them if submission is successful. The javascript should then display that message in a div immediately.</p> <p>At the same time, I need to deal with error messages. For users without javascript, the whole form will be rerendered with the error messages in place.</p> <p>For users with javascript, the ajax response should be an array containing the id of the input component and the error message. Javascript should then insert these into the form without a refresh.</p> <p>Looking at the symfony2 book, I can see the following for submissions, I then modified it to check if the request is an ajax request:</p> <pre><code>public function newAction(Request $request) { // just setup a fresh $task object (remove the dummy data) $task = new Task(); $form = $this-&gt;createFormBuilder($task) -&gt;add('task', 'text') -&gt;add('dueDate', 'date') -&gt;getForm(); if ($request-&gt;getMethod() == 'POST') { $form-&gt;bindRequest($request); if ($form-&gt;isValid()) { // perform some action, such as saving the task to the database if ($this-&gt;request-&gt;isXmlHttpRequest(){ //return data ajax requires. } return $this-&gt;redirect($this-&gt;generateUrl('task_success')); } } // ... } </code></pre> <p>The problem I find with this approach is that is isn't very elegant. I need add that extra check every single form. Further more, this method would not work if say the request comes in via Zend_AMF.</p> <p>Are there any better ways to do this? </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload