How can I include the 'Submit' button in the 'POST' matrix generated by 'serialize'?

Asked

Viewed 427 times

6

On the forms, I have the button like submit that when clicked will be intercepted by jQuery in order to make validations to the content of the form before sending it to PHP process via Ajax.

Form

<?php

$html = '
<form action="'.CONF_FORM_ACTION_REGISTRATION.'" method="post" autocomplete="off" class="jForm">
  <p>
    <span class="icon-user"></span>
    <label for="formRegistration-usr">
      '.LANG_WORD_NAME.'
      <span class="msg"></span>
    </label>
    <input id="formRegistration-usr" class="roundCorners jValidate" name="formRegistration-usr" required="required" type="text" placeholder="'.LANG_PLACEHOLDER_NAME.'" data-validation="notEmpty">
  </p>
  <p>
    <span class="icon-envelope"></span>
      <label for="formRegistration-email">
        '.LANG_SENTENCE_YOUR_EMAIL_ADDRESS.'
        <span class="msg"></span>
      </label>
      <input id="formRegistration-email" class="roundCorners jValidate" name="formRegistration-email" required="required" type="text" placeholder="'.LANG_PLACEHOLDER_EMAIL.'" data-validation="email">
  </p>
  <p>
    <span class="icon-key"></span>
      <label for="formRegistration-pwd">
        '.LANG_SENTENCE_YOUR_PASSWORD.'
        <span class="msg"></span>
      </label>
      <input id="formRegistration-pwd" class="roundCorners" name="formRegistration-pwd" required="required" type="password" placeholder="'.LANG_PLACEHOLDER_PASSWORD.'">
  </p>
  <p>
    <span class="icon-key"></span>
    <label for="formRegistration-chkPwd">
      '.LANG_SENTENCE_CONFIRM_YOUR_PASSWORD.'
      <span class="msg"></span>
    </label>
    <input id="formRegistration-chkPwd" class="roundCorners jValidate" name="formRegistration-chkPwd" required="required" type="password" placeholder="'.LANG_PLACEHOLDER_PASSWORD.'" data-validation="chkPwd">
  </p>
  <p class="button">
    <span class="formMsg"></span>
    <input name="formRegistration-smt" id="formRegistration-smt" class="btn_blue roundCorners" type="submit" value="'.LANG_WORD_REGISTER.'">
  </p>
</form>';

?>

Code jQuery

/**
 * PROCESS FORMS
 * Actions associated with the submit of several similar forms.
 */
function processForms() {

  $(".jForm").on("submit", function(e) {
    e.preventDefault();

    var $this    = $(this),
        $formMsg = $this.find(".formMsg");

    if (mandatoryFieldsFilled($this)) {

      $.ajax({
        type    : "POST",
        url     : "/components/inc/ajax/users.ajax.php",
        async   : false,
        data    : $this.serialize(),
        dataType: "json",
        success : function(data) {

          var arr = data;

          if (arr[0]=="success") {
            $formMsg.removeClass("error").addClass("success");
          } else {
            $formMsg.removeClass("success").addClass("error");
          }

          $formMsg.html(arr[1]);

          autoHideModalForm($this, 4000);
        }
      });

    } else {
      $formMsg.removeClass("success").addClass("error").html(LANG_USR_MSG_MANDATORY_FIELD_EMPTY);
    }

  });
}

The problem is that all form fields are sent to POST Ajax with the exception of the submit, which I use to discern through the name of the same, which form to process on the PHP side.

Question

How can I include the submit in the POST matrix generated by serialize ?

3 answers

3

The first way that occurs to me is to add a hidden input after checking and before serialize is called.

if (mandatoryFieldsFilled($this)) {

      var inputEscondido = $('input[type=submit]').clone().attr('type', 'hidden');        
      $(this).append(inputEscondido);

      $.ajax({
        type    : "POST",
        url     : "/components/inc/ajax/users.ajax.php",
        async   : false,
        data    : $this.serialize(),
        dataType: "json",
        success : function(data) {

But it also seems possible using:

//antes do ajax
var inputEscondido = $('input[type=submit]')[0];

// dentro do ajax
data: $this.serialize() + '&' + encodeURIComponent(inputEscondido.name) + '=' + encodeURIComponent(inputEscondido.value), 

0

Add the attribute "name" to the button(Submit) and the serialized value will be the attribute "value" and the same should be the Item clicked in the form

0

#1 Using the plugin Jquery Forms

I know the question does not talk about any plugin, but an option would be to use this plugin that already comes with several ready functionalities related to submission via Ajax.

The plugin adds the automatically clicked button if it is applied to a form, but even if you want to call it programmatically, there is the parameter data which allows arbitrary additional values to be passed.

Example:

$('.jForm').submit(function() { 
    var $this = $(this);
    var options = { 
        data: { $this.attr('name'): $this.attr("value") }
    };
    $(this).ajaxSubmit(options); 
    return false; 
}); 

#2 Concatenate the value of the button to the result of form serialization

There is the option to concatenate the value manually (which Sergio added to his question as well), but here is a version more "chewed":

$.ajax({
    ...
    data    : $this.serialize() + '&' + encodeURIComponent($this.attr('name')) +
                  '=' + encodeURIComponent($this.attr("value")),
    ...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.