skip to Main Content

I have a jQuery function that does the insert of an image with other fields to the database. Currently my function only inserts the image but does not insert the other form fields. I am using formData object and I don’t understand how to append my fields together with the image file so I can pass it to the ajax request body.
Here is what I have tried so far:

// submit function

function Submit_highschool() {
  jQuery(document).ready(function($) {
    $("#highschool").submit(function(event) {
      event.preventDefault();
      $("#progress").html(
        'Inserting <i class="fa fa-spinner fa-spin" aria-hidden="true"></i></span>');

      var formData = new FormData($(this)[0]);
      var firstname_h = $("#firstname_h").val();
      var middlename_h = $("#middlename_h").val();
      formData.append(firstname_h, middlename_h);

      $.ajax({
        url: 'insertFunctions/insertHighSchool.php',
        type: 'POST',
        data: formData,
        async: true,
        cache: false,
        contentType: false,
        processData: false,
        success: function(returndata) {
          alert(returndata);
        },
        error: function(xhr, status, error) {
          console.error(xhr);
        }
      });
      return false;
    });
  });
}

// html form

<form method="post" enctype="multipart/form-data" id="highschool">
  <div class="card" id="highschool">
    <div class="col-3">
      <label for="firstname">First name *</label>
      <input type="text" class="form-control" id="firstname_h" placeholder="First name" />
    </div>

    <div class="col-3">
      <label for="middlename">Middle name *</label>
      <input type="text" class="form-control" id="middlename_h" placeholder="Middle name" />
    </div>

    <div class="col-6">
      <label for="grade11_h">Grade 11 Transcript (image) *</label>
      <input type="file" class="form-control" name="grade11_h" id="grade11_h" accept=".png, .jpg, .jpeg">
    </div>
    <button type="submit" name="submit" class="btn btn-primary float-right" onclick="Submit_highschool();">Submit</button>
  </div>
</form>

The image name is succesfully inserted in the db and the image is uploaded to the required target location,However, the fields – firstname and middlename are not inserted and I don’t understand how to append these properties to the formData.

How can I pass these fields to the formData please?

2

Answers


  1. Chosen as BEST ANSWER

    Like @Professor Abronsius suggested in the comments section I only needed to add the "name" tag to the form elements and remove the append from my function thus, I have edited the function and the form as follows:

    // since I have added the name tag to the form elements, there is now 
    // no need to use the append() thus, I have commented out the append 
    // lines.
    
    function Submit_highschool() {
      jQuery(document).ready(function($) {
        $("#highschool").submit(function(event) {
          event.preventDefault();
          $("#progress").html(
            'Inserting <i class="fa fa-spinner fa-spin" aria-hidden="true"></i></span>');
    
          var formData = new FormData($(this)[0]);
          // var firstname_h = $("#firstname_h").val(); // removed this
          // var middlename_h = $("#middlename_h").val(); // removed this
          //formData.append(firstname_h, middlename_h); // removed this
    
          $.ajax({
            url: 'insertFunctions/insertHighSchool.php',
            type: 'POST',
            data: formData,
            async: true,
            cache: false,
            contentType: false,
            processData: false,
            success: function(returndata) {
              alert(returndata);
            },
            error: function(xhr, status, error) {
              console.error(xhr);
            }
          });
          return false;
        });
      });
    }

    // added the "name" tag to the form elements

    <form method="post" enctype="multipart/form-data" id="highschool">
      <div class="card" id="highschool">
        <div class="col-3">
          <label for="firstname">First name *</label>
          <input type="text" class="form-control" name="firstname_h" id="firstname_h" placeholder="First name" /> // added name="firstname_h"
        </div>
    
        <div class="col-3">
          <label for="middlename">Middle name *</label>
          <input type="text" class="form-control" name="middlename_h" id="middlename_h" placeholder="Middle name" /> // added name="middlename_h"
        </div>
    
        <div class="col-6">
          <label for="grade11_h">Grade 11 Transcript (image) *</label>
          <input type="file" class="form-control" name="grade11_h" id="grade11_h" accept=".png, .jpg, .jpeg">
        </div>
        <button type="submit" name="submit" class="btn btn-primary float-right" onclick="Submit_highschool();">Submit</button>
      </div>
    </form>
    

  2. You can use the following approach for storing the data with image.

    1.In PHP API write logic for Upload image to server using move_uploaded_file() & Insert image file name with server path in the MySQL database using PHP.

    2.In JS/JQuery, Read all HTML element & create an object & POST it to the API using AJAX Call.

    your JS code should be like this. Hope this will help you to fix the issue.

      var RegObj = {
              'Field1': $("#Field1").val(),
              'Field2': $("#Field2").val(),
              'logo': $("#company_logo").attr('src'),
             }
      
            console.log(RegObj);
            
            $.ajax({
              url: "API_PATH_HERE",
              type: "POST",
              data: JSON.stringify(RegObj),
              headers: {
                "Content-Type": "application/json"
              },
              dataType: 'text',
              success: function (result) {         
                     
                //
              },
              error: function (xhr, textStatus, errorThrown) {
                
              }
            });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search