I have this form.js code. Please help me to redirect back to contact.html form after successful or error message.  $(function() {   function after_form_submitted(data) {     if (data.result == 'success') {       $('form#reused_form').hide();       $('#success_message').show();       $('#error_message').hide();     } else {       $('#error_message').append('&lt;ul&gt;&lt;/ul&gt;');       jQuery.each(data.errors, function(key, val) {         $('#error_message ul').append('&lt;li&gt;' + key + ':' + val + '&lt;/li&gt;');       });       $('#success_message').hide();       $('#error_message').show();        //reverse the response on the button       $('button[type="button"]', $form).each(function() {         $btn = $(this);         label = $btn.prop('orig_label');          if (label) {           $btn.prop('type', 'submit');           $btn.text(label);           $btn.prop('orig_label', '');         }       });     } //else   }    $('#reused_form').submit(function(e) {     e.preventDefault();     $form = $(this);      //show some response on the button     $('button[type="submit"]', $form).each(function() {       $btn = $(this);       $btn.prop('type', 'button');       $btn.prop('orig_label', $btn.text());       $btn.text('Please Wait Sending ...');     });      var formdata = new FormData(this);      $.ajax({       type: "POST",       url: 'handler.php',       data: formdata,       success: after_form_submitted,       dataType: 'json',       processData: false,       contentType: false,       cache: false     });   }); });
906
How can I redirect the user from one page to another using jQuery or pure JavaScript?
44846
I used the jQuery Form plugin for asynchronous form submission. For forms that contain files, it copies the form to a hidden iframe, submits it, and copies back the iframe's contents. The problem is that I can't figure out how to find what HTTP status code was returned by the server. For example, if the server returns 404, the data from the iframe will be copied as normal and treated as a regular response.  I've tried poking around in the iframe objects looking for some sort of status_code attribute, but haven't been able to find anything like that.    The $.ajax() function can't be used, because it does not support uploading files. The only way to asynchronously upload files that I know of is using the hidden iframe method.
53883
Drupal doesn't seem to prevent multiple form submits, even on node pages. This  suggests fixing it on the server side.  How could I disable the submit button after clicking?   Any other solutions?
75322
I'm developing some plugin where I would like to enable custom pages. In my case some custom page would contain a form like contact form (not literally). When user will fill out this form and send it, there should be the next step which will require more information. Lets say that the first page with form would be located at www.domain.tld/custom-page/ and after successful form submission, the user should be redirected to www.domain.tld/custom-page/second. Template with HTML elements and PHP code should be also custom.  I think that a part of the problem is possible to achieve with custom URL rewrites, but the other parts are currently unknown to me. I really don't know where should I start looking and what's the correct naming for that problem. Any help would be really appreciated.
91485
So this is my controller which create new event and save event.  in this i have hardcoded page redirect link  '/a3I/o'. i dnt want this to hardcoded. I want to do something like it will redirect to that tab without harcoded code or this will redirect to new record page which i am creating in this code(t1).   public class ERFormController {     public Event_Request__c t1{get;set;}      public ERFormController(ApexPages.StandardController controller)     {         t1 = new Event_Request__c();     }      public PageReference save()     {         insert t1;          ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.CONFIRM,'Record Created Successfully.Thank you!'));         PageReference pg = new PageReference('/a3I/o');         pg.setRedirect(true);         return pg;       }
108591
I have a form which allows the user to create extra "rows" using JQuery (using .clone) so that they can decide how many of the same information they need to submit. My issue is that I cannot work out how to access these form items within my controller.  the form that is being submitted may look like this  &lt;input type="text" name="Amount" id="Amount"&gt;    &lt;select name="Item"&gt;        &lt;option value="1"&gt;Item 1"&lt;/option&gt;        &lt;option value="2"&gt;Item 2"&lt;/option&gt;        &lt;option value="3"&gt;Item 3"&lt;/option&gt;    &lt;/select&gt; &lt;input type="text" name="Amount" id="Amount"&gt;    &lt;select name="Item"&gt;        &lt;option value="1"&gt;Item 1"&lt;/option&gt;        &lt;option value="2"&gt;Item 2"&lt;/option&gt;        &lt;option value="3"&gt;Item 3"&lt;/option&gt;    &lt;/select&gt; &lt;input type="text" name="Amount" id="Amount"&gt;    &lt;select name="Item"&gt;        &lt;option value="1"&gt;Item 1"&lt;/option&gt;        &lt;option value="2"&gt;Item 2"&lt;/option&gt;        &lt;option value="3"&gt;Item 3"&lt;/option&gt;    &lt;/select&gt;   Basically, the block between input and the select could be repeated an infinite number of times. When I submit to the controller I am then using FormCollection form to access the form elements. from there I am unsure how I can access the items that have been submitted. I thought of using a for loop and then accessing them via something like form["Amount"][i] but obviously that is not going to work.  Am I going about this the right way and if so, does anyone have any suggestions about how this might work?  Thanks in advance.
3260
As a user, when I submit a "Contact us" form with [valid] info, should the page response show in the form (clear the form and show some "We have received your message" type of success message, either at the top or bottom of the form, or should they simply be redirected to another page showing the success message?
50903
I'd think this would work just fine, but it seems to prevent the action function from firing regardless of the confirm response  &lt;apex:commandButton value="Remove All" action="{!removeAll}" rerender="form"      status="LoadingStatus" onclick="return confirm('Are you sure?');"/&gt;
18317
I'm running into a problem where a user can submit any form built by the Form API multiple times (fast clicking resulting in multiple requests).  I've put in the basic client side (javascript) solution of disabling the button, but I'm curious what the best approach to preventing this situation is on the server side.  Is there a recommended way to use Drupal's form token system to handle this?  Especially a global form solution (ie, adding a custom validator to every form using hook_form_alter()).  My approach so far has been something like this:  function mymodule_form_alter(&amp;$form, &amp;$form_state, $form_id) {   $form['#validate'][] = 'mymodule_form_validate'; }  function mymodule_form_validate(&amp;$form, &amp;$form_state){   //initialize form array   if (!isset($_SESSION['submitted_forms'])){     $_SESSION['submitted_forms'] = array();   }    $form_token = $form_state['values']['form_token'];   if ( isset($_SESSION['submitted_forms'][$form_token]) &amp;&amp; $_SESSION['submitted_forms'][$form_token] = TRUE ){     form_set_error('name]', 'This form has already been submitted');   }   else{     $_SESSION['submitted_forms'][$form_token] = TRUE;   } }   I'm running into trouble where the form_token isn't unique to the form - it seems to stay the same no matter what happens.  I'm probably misunderstanding what the token is in the grand scheme of the form api.  Any insight is appreciated!
120639
I'm trying to put search results into a div with ajax. The issue is I'm getting errors saying undefined function have_posts() when the the search template is accessed. It also took issue with get_header() which was in the search-results.php but I took it out. Here's how I have it setup.    &lt;div id="my_search"&gt;    &lt;form role="search" method="get" id="searchform" action="http://myurl.com/" &gt;     &lt;input type="text" value="" name="s" id="s" /&gt;     &lt;input type="submit" id="searchsubmit" value="Search" /&gt;    &lt;/form&gt;   &lt;/div&gt;   &lt;div id="results"&gt;&lt;/div&gt;   &lt;script type="text/javascript"&gt;     $(document).ready(function(){     $("#searchsubmit").click(function(e){      e.preventDefault();      var search_val=$("#s").val();       $.post('http://mysite.com/wp-content/themes/beta/search-results.php',{search_string:search_val},function(data){         if(data.length&gt;0){             $("#results").html(data);         }      });     });       });   &lt;/script&gt;   And here is the search-results.php template. I'm wondering if maybe I'm not passing the search results to the template.  &lt;ul&gt;  &lt;?php if (have_posts()) : while (have_posts()) : the_post();  ?&gt;   &lt;li&gt;&lt;a title="Permalink to this post" href="&lt;?php echo get_permalink(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/li&gt;   &lt;?php endwhile; endif; ?&gt;  &lt;?php if (!have_posts()) { echo('&lt;li&gt;No results to show.&lt;/li&gt;'); } ?&gt; &lt;/ul&gt;
22295
I'm using $.post() to call a servlet using Ajax and then using the resulting HTML fragment to replace a div element in the user's current page. However, if the session times out, the server sends a redirect directive to send the user to the login page. In this case, jQuery is replacing the div element with the contents of the login page, forcing the user's eyes to witness a rare scene indeed.   How can I manage a redirect directive from an Ajax call with jQuery 1.2.6?
22242
I'm in a bit of a verbiage bind. I have a form for a request cancellation. I cannot change the wording on that. The word cancel HAS to be used.  The button bellow sits in the footer of a card. Unfortunately, I cannot show you the rest of the card for context.      Clicking that button brings up the above form in the footer of the card.  The pattern shown here (form input on one line, followed by a cancel and submit button with the below styles and ordering) is used across the application. This is another non negotiable. Clicking that cancel button collapses the form back into the original button ("Cancel Request").  As you can probably tell as this point, I have a Cancel-Cancel-Conundrum. I need a better word than cancel for that form button, but I'm having trouble thinking of something. I was thinking something along the lines of "Exit" but that feels a little weird.
39468
I have a form on my front-page. It sends the entered address to Google API and returns the JSON to wp_options. That works fine. I am using update_option to do that, so it rewrites the meta_key each time. How would I go about having each address entered remain?    $address = esc_html( $_POST['address'] );    //assign JSON object to var using  geocodeing function('address') input    $address_results = gmap_geocode($address);    // transfer data to options array   $options['py_name'] = $py_username;   $options['address'] = $address;   $options['coords']  = $address_results;    // create and name the option_name and set fields with $options array   update_option( 'row_name', $options );
88313
Usually, we only have 2 buttons at the bottom of a form or a page that requires an action: Submit &amp; Cancel.  This one is quite easy to style. However, what if we are dealing with multiple buttons at the bottom of a page? For example:   ← Back | Send Email | Booking Paid | Check-in Guest   I'm thinking of making "Back" just a link (not a button) and making "Send Email" / "Booking Paid" secondary buttons (light gray). Then I'd make "Check-in Guest" as the primary button (green).  I still feel that there's a better way of doing it or dealing with multiple buttons / actions. What do you think?
42461
I am designing a site that has a variety of points in which I need to render "workflow" buttons that are used to send actions to an external application.   I used the form API to generate these buttons, and am using the #submit => option on my buttons to direct specific button types to custom functions. I am also using hidden fields to house data that I use to facilitate the action.   The problem I am having is that these buttons can and should show up multiple times per page, for different aspects of the application, and whenever I click one of the buttons Drupal attempts to submit all of the forms.   I guess what i am asking is, how can I have multiple instances of the exact same form on screen at any given time, and know with certainty that the submit buttons are only going to trigger actions for the specific instance of the form they belong to?  thanks in advance!!  Edit  So here is the crux of the problem - it appears that the getFormId needs to return a unique value, but I cannot figure out how to pass unique values into it.
50374
I have a form with only a select element and no submit button. Upon change, I issue an ajax call to retrieve the details of the selected Project. Everything works as expected, however after I leave the page, I see the error "An illegal choice has been detected. Please contact the site administrator."  I only get the error if I change the select input. Ex. if I navigate to:     Home->Projects->Home   I don't see the error on the last Home page. If i navigate to:     Home->Projects(change select input)->Home   I see the error on the last Home page.  Here is my module code:  class ExpeditionController extends ControllerBase {   public $client;    public function __construct() {     $this-&gt;client = \Drupal::service('http_client');   }     public function listProjects() {     $select_form = \Drupal::formBuilder()-&gt;getForm('Drupal\myModule\Form\ExpeditionSelectForm');     // Remove the submit button.     unset($select_form['actions']['submit']);      $result = $this-&gt;client-&gt;get('myRESTService', ['Accept' =&gt; 'application/json']);     $expeditions = json_decode($result-&gt;getBody());      foreach ($expeditions as $value) {       $select_form['expeditions']['#options'][$value-&gt;{'expedition'}-&gt;{'expeditionId'}] = $this-&gt;t($value-&gt;{'expedition'}-&gt;{'expeditionTitle'});     }      return array(       '#theme' =&gt; 'myModule_expeditions',       '#form' =&gt; $select_form,     );   }    public function expeditionDetail($form, $form_state) {     $expedition = [];     $response = new AjaxResponse();     if ($form['expeditions']['#value'] != "") {        $client = \Drupal::service('http_client');       $result = $client-&gt;get(         'myService' . $form['expeditions']['#value'],         ['Accept' =&gt; 'application/json']       );       $expedition = json_decode($result-&gt;getBody());     }      $response-&gt;addCommand(new HtmlCommand(       '#expeditionDetail',       array(         '#theme' =&gt; 'myModule_expeditions_detail',         '#expedition' =&gt; $expedition,       )     ));      return $response;   }    public function deploymentDetail($project_id, $deployment_id) {     $result = $this-&gt;client-&gt;get(       'myService' . $project_id . '/' . $deployment_id,       ['Accept' =&gt; 'application/json']     );      return array(       '#theme' =&gt; 'myModule_deployment_detail',       '#deployment' =&gt; json_decode($result-&gt;getBody()),     );    } }  class ExpeditionSelectForm extends ConfigFormBase {   /**    * {@inheritdoc}    */   public function getFormId() {     return 'myModule_expeditions';   }    /**    * {@inheritdoc}    */   public function buildForm(array $form, FormStateInterface $form_state) {     $form['expeditions'] = array(       '#type' =&gt; 'select',       '#title' =&gt; $this-&gt;t('Choose Project'),       '#empty_option' =&gt; $this-&gt;t('Select a project'),       '#default_value' =&gt; '',       '#ajax' =&gt; [         'callback' =&gt; 'Drupal\myModule\Controller\ExpeditionController::expeditionDetail',       ],     );      return parent::buildForm($form, $form_state);   }    /**    * Gets the configuration names that will be editable.    *    * @return array    *   An array of configuration object names that are editable if called in    *   conjunction with the trait's config() method.    */   protected function getEditableConfigNames() {     // TODO: Implement getEditableConfigNames() method.     return [];   } }
40150
I have a form with multiple fields that I'm validating (some with methods added for custom validation) with Jörn Zaeffere's excellent jQuery Validation plugin. How do you circumvent validation with specified submit controls (in other words, fire validation with some submit inputs, but do not fire validation with others)? This would be similar to ValidationGroups with standard ASP.NET validator controls.  My situation:  It's with ASP.NET WebForms, but you can ignore that if you wish. However, I am using the validation more as a "recommendation": in other words, when the form is submitted, validation fires but instead of a "required" message displaying, a "recommendation" shows that says something along the line of "you missed the following fields.... do you wish to proceed anyways?" At that point in the error container there's another submit button now visible that can be pressed which would ignore the validation and submit anyways. How to circumvent the forms .validate() for this button control and still post?  The Buy and Sell a House sample at  allows for this in order to hit the previous links, but it does so through creating custom methods and adding it to the validator. I would prefer to not have to create custom methods duplicating functionality already in the validation plugin.  The following is a shortened version of the immediately applicable script that I've got right now:  var container = $("#&lt;%= Form.ClientID %&gt; div.validationSuggestion");  $('#&lt;%= Form.ClientID %&gt;').validate({               errorContainer: container,     errorLabelContainer: $("ul",container),     rules: {         &lt;%= YesNo.UniqueID %&gt;: { required: true },         &lt;%= ShortText.UniqueID %&gt;: { required: true } // etc.      },     messages: {         &lt;%= YesNo.UniqueID %&gt;: 'A message.',         &lt;%= ShortText.UniqueID %&gt;: 'Another message.' // etc.     },     highlight: function(element, errorClass) {         $(element).addClass(errorClass);         $(element.form).find("label[for=" + element.id + "]").addClass(errorClass);         $(element.form).find("label[for=" + element.id + "]").removeClass("valid");     },     unhighlight: function(element, errorClass) {         $(element).removeClass(errorClass);         $(element.form).find("label[for=" + element.id + "]").removeClass(errorClass);         $(element.form).find("label[for=" + element.id + "]").addClass("valid");     },     wrapper: 'li' });