skip to Main Content

I’m working on a multi-step form using JavaScript, where I need to submit the second step of the form via Ajax. I’ve created a separate JavaScript file called ajaxRequest.js to handle the Ajax request, which I’m calling from the second step of the form. However, when I submit the form, nothing happens.

Here’s what I’ve tried so far:

I’ve checked the console for any errors, but I don’t see any.
I’ve made sure that the Ajax request is being sent to the correct URL.
I’ve tried to debug the ajaxRequest.js file by placing console.log statements, but I still can’t figure out what’s going wrong.
Here’s the code for the relevant parts of my project:

The HTML for the second step of the form is as follows:

<section class ="form-section">
<h4>family geographic</h4>
<div class = "familycontainer">
<div id="adultFormcontainer"></div>
<div id="children-form-container"></div>
</div>
</section>

I also have a javascript file called increment.js which creates dynamically creates the amount of fields based on what the user needs

here is my increment.js code

    function addAdultFields() {
   // Get the number of adults specified in the input element
    var numAdults = document.getElementById("numberofAdults").value;

    // Get the parent element to which we'll add the new form fields
    var parent = document.getElementById("adultFormcontainer");

     // Remove any existing form fields (in case the number of adults was changed)
      while (parent.lastChild) {
      parent.removeChild(parent.lastChild);
      }

     // testing this object will hold the value of the input field
       var adultfirstnameformdata ={};

     // Generate a new set of form fields for each adult
     for (var i = 1; i <= numAdults; i++) {

     // create a fieldset to hold the adult info
       var fieldset = document.createElement("fieldset");

    //styling the field set 

    //fieldset.style.border = "1px outset gray";

     fieldset.style.display= "flex";
     fieldset.style.flexDirection = "row";

     fieldset.style.marginBottom = '100px'; // add margin to the bottom
      fieldset.style.paddingTop = '5px'; // add padding to the bottom

    /*fieldset.style.backgroundColor ="blue";*/
  
   // we want the adult information to be on the left of the container while the child info is 
     on the right 
    fieldset.classList.add("float-left");

    // a legend should be create for the adult info
    var legend = document.createElement("legend");
   legend.textContent = "Adult" + i;


    // Create a new label element for the adult's name
     var nameLabel = document.createElement("label");
     nameLabel.classList.add("inline-block");
    //nameLabel.setAttribute("for", "adult" + i + "First Name");
      nameLabel.textContent = "First Name" ;  // "Adult " + i + " First Name:"

    // Create a new input element for the adult's name


 var nameInput = document.createElement("input");
    nameInput.setAttribute("type", "type");
    nameInput.setAttribute("id", "adult" + i + "FirstName");
    nameInput.setAttribute("name", "adult" + i + "FirstName");
    nameInput.classList.add("form-control");
    nameInput.classList.add("mb-3");
     fieldset.appendChild(nameLabel); //
     fieldset.appendChild(nameInput);

The JavaScript code for calling the Ajax request in increment.js is as follows:

document.getElementById('step2-form').addEventListener('submit', function(event) {
  event.preventDefault();

  // collect form data using FormData
  const formData = new FormData(event.target);

  // call the AJAX request function from ajaxRequest.js
  sendFormData(formData);
});

The code in ajaxRequest.js is as follows:

function sendFormData(formData) {
  const xhr = new XMLHttpRequest();
  xhr.open('POST', '/submitStep2FormData');
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  xhr.onload = function() {
    console.log(xhr.responseText);
  };
  xhr.send(formData);
}

here is the php code

    public function postdata(Request $req){ 
     $first_name = $req->input('adult'.$i.'FirstName');
     dd($first_name);
     }

the first step does work because the form is not dynamically created and I have a route to handle it.

Any help or suggestions on how to resolve this issue would be greatly appreciated. Thank you in advance!

2

Answers


  1. Chosen as BEST ANSWER

    I solved the problem first I Loop over $_POST array to find all keys starting with "adult" then extract the adult number from the key and extract the first name from the value then add output text to the $output array
    pass $output array to dd()

    here is the code

    $output = [];
    
    // Loop over $_POST array to find all keys starting with "adult"
    foreach ($_POST as $key => $value) {
      if (strpos($key, "adult") === 0) {
        // extract the adult number from the key
        $parts = explode("adult", $key);
        $adult_number = intval($parts[1]);
        
        // extract the first name from the value
        $first_name = $value;
        
        // add output text to the $output array
        $output[] = "Adult " . $adult_number . " first name is " . $first_name;
      }
    }
    
    // pass $output array to dd()
    dd($output);
    

  2. You are sending a FormData object in the request. Therefore you do not set the content type header in the request. It is set correctly and automatically.
    If your end point expects data in application/x-www-form-urlencoded then you can’t use form data you can try using URLSearchParams

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search