Home > front end >  How to add dynamic fields in ajax post call
How to add dynamic fields in ajax post call

Time:09-13

function submitData(productSubtypeId, orderNumber) {
  // Get all dynamic input fields belonging to a class so that we can check if a value for those were provided or not
  var cells = document.getElementsByClassName(
    orderNumber   "-"   productSubtypeId   "-"   "supplData"
  );
  for (var i = 0; i < cells.length; i  ) {
    if (
      document.getElementById(
        orderNumber   "-"   productSubtypeId   "-"   cells[i].name
      ).value == ""
    )
      alert(cells[i].name   " is required");
    return false;
  }
  if (
    confirm(
      "Confirm submitted data for order "  
        orderNumber  
        "?\nDon't forget to close the order after submitting supplemental data."
    )
  ) {
    $.ajax({
      url: "FillSupplData.cfm",
      type: "post",
      data: {
        productSubtypeId: productSubtypeId,
        orderNumber: orderNumber,
        DEPLOY_DATE: document.getElementById(
          orderNumber   "-"   productSubtypeId   "-"   "DEPLOY_DATE"
        ).value,
      },
      success: function (response) {
        // Remove data submit (supplemental) button once data is successfully submitted
        $(
          "#"   orderNumber   "-"   productSubtypeId   "-"   "fillSupplData"
        ).remove();
        // Disable all supplemental data input fields for this order
        //var cells = document.getElementsByClassName(orderNumber   '-'   productSubtypeId   '-'   'supplData');
        for (var i = 0; i < cells.length; i  ) {
          cells[i].disabled = true;
        }
        // Make order close button visible
        document.getElementById(
          orderNumber   "-"   productSubtypeId   "-"   methodInvoked
        ).style.display = "block";
      },
      error: function (jqXHR, exception) {
        var msg = "An error occurred";
        alert(msg);
      },
    });
  }
}

This is part of the HTML code I have :

<table  id="3202643984">
  <tbody>
    <tr>
      <td style="width: 50%; vertical-align: top">
        <div>
          <table >
            <tbody>
              <tr>
                <th style="width: 15%">Order Number</th>
                <th style="width: 20%">Scheduled Ship Date</th>
                <th style="width: 30%">Customer Name</th>
                <th style="width: 20%">Customer Number</th>
                <th style="width: 20%">Customer PO</th>
              </tr>
              <tr>
                <td>
                  <a
                    id="3202643984-104"
                    
                    style="display: block"
                    >3202643984</a
                  >
                </td>
                <td />
                <td>LOGAN COUNTY SHERIFF</td>
                <td>1000269359</td>
                <td>RG212738</td>
              </tr>
            </tbody>
          </table>
        </div>
      </td>

      <td style="width: 30%; vertical-align: top">
        <div id="3202643984-line-items">
          <table>
            <tbody>
              <tr>
                <th style="width: 15%">Line Num</th>
                <th style="width: 20%">Part Number</th>
                <th style="width: 15%">Qty</th>
                <th style="width: 50%">Description</th>
              </tr>
              <tr>
                <td>1.1</td>
                <td>AAS00100</td>
                <td>1</td>
                <td>EVIDENCE BWC AS A SERVICE</td>
              </tr>
              <tr>
                <td>2.1</td>
                <td>AAS00101</td>
                <td>1</td>
                <td>VIDEO-AS-A-SERVICE</td>
              </tr>
            </tbody>
          </table>
        </div>
      </td>
      <form id="SupplDataForm" action="FillSupplData1.cfm" method="post" />

      <input type="hidden" name="orderNumber" value="3202643984" />
      <input type="hidden" name="productSubtypeId" value="104" />
      <input type="hidden" name="toolSectionId" value="Watchguard" />
      <td style="vertical-align: top">
        <div style="padding-bottom: 10px">
          <strong>Additional Order Data</strong>
        </div>
        <div style="width: 150px">
          <div>
            Deploy Date:
            <input
              type="date"
              id="3202643984-104-DEPLOY_DATE"
              name="DEPLOY_DATE"
              placeholder="Deploy Date"
              value=""
              
              style="border: 2px solid lightgray; width: 90%"
              size="200"
              required
            />
            <strong style="color: red; font-size: 24px">*</strong>
          </div>
        </div>
      </td>
      <td style="width: 10%; vertical-align: top; padding-top: 40px">
        <input
          id="3202643984-104-fillSupplData"
          style="float: right; width: 125px; margin: 0px 5px"
          type="button"
          
          value="Submit Data"
          onclick="submitData(productSubtypeId = 104, orderNumber = '3202643984');"
        />
        <button
          type="button"
          id="3202643984-104-close"
          onclick="manualMethod(productSubtypeId = 104, methodInvoked = 'close', orderNumber = '3202643984');"
          style="margin-bottom: 10px; display: none"
        >
          Close
        </button>
      </td>
    </tr>
  </tbody>
</table>

Now the issue I need help with is that the input fields for the orders are dynamic depending on the product sub type they belong to and I need to grab those fields and create variables so that I can submit the values in ajax call.

data: {
  productSubtypeId: productSubtypeId,
  orderNumber: orderNumber,
  DEPLOY_DATE : document.getElementById(orderNumber   '-'   productSubtypeId   '-'   'DEPLOY_DATE').value
}

Here, I have DEPLOY_DATE but how can I do it so that I don't have to hardcode field name and value. I can have 2-3 different fields here depending on what fields are required for this product sub type.

Thanks for your help in this regard

CodePudding user response:

Looks like you've got everything you need in the <form> itself.

Use the .serialize() function to capture all the <form> element data. I would also recommend listening to the submit event rather than a button click so you have a direct reference to the form

$("table.order form").on("submit", (e) => {
  e.preventDefault(); // prevent normal submit

  const form = $(e.target); // <form> ref

  const cells = form.find("[class$='-supplData']");

  // get the names of any empty inputs
  const emptyData = cells
    .filter((_, { value }) => value === "")
    .map((_, { name }) => name)
    .get();

  if (emptyData.length) {
    alert(`${emptyData.join(", ")} required`);
    return false;
  }

  const orderNumber = form.find("[name='orderNumber']").val();

  if (
    !confirm(
      "Confirm submitted data for order "  
        orderNumber  
        "?\nDon't forget to close the order after submitting supplemental data."
    )
  ) {
    return false;
  }

  $.post("FillSupplData.cfm", form.serialize())
    .done((response) => {
      form.find("button[type=submit]").remove();
      form.find("button[type=button]").show();
      cells.prop("disabled", true);
    })
    .fail((_, ...errors) => {
      console.warn(...errors);
      alert("An error occurred");
    });
});

The only change to the HTML would be for your buttons

<button
  id="3202643984-104-fillSupplData"
  style="float: right; width: 125px; margin: 0px 5px"
  type="submit"
  
  value="Submit Data"
/>
<button
  type="button"
  id="3202643984-104-close"
  onclick="manualMethod(104, 'close', '3202643984');"
  style="margin-bottom: 10px; display: none"
>
  Close
</button>

CodePudding user response:

var formData = {
            productSubtypeId: 108,
            orderNumber: 5673856
};

What I wanted was to add a property to an object that I am passing in ajax. That can be achieved like this :

formData['newPropertyName'] = document.getElementById(orderNumber   '-'   productSubtypeId   '-'   'newPropertyName').value; 
  • Related