Home > Blockchain >  How to send an image alongside other fields to PHP?
How to send an image alongside other fields to PHP?

Time:06-03

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  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  id="highschool">
    <div >
      <label for="firstname">First name *</label>
      <input type="text"  id="firstname_h" placeholder="First name" />
    </div>

    <div >
      <label for="middlename">Middle name *</label>
      <input type="text"  id="middlename_h" placeholder="Middle name" />
    </div>

    <div >
      <label for="grade11_h">Grade 11 Transcript (image) *</label>
      <input type="file"  name="grade11_h" id="grade11_h" accept=".png, .jpg, .jpeg">
    </div>
    <button type="submit" name="submit"  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?

CodePudding user response:

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) {
            
          }
        });

CodePudding user response:

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  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  id="highschool">
    <div >
      <label for="firstname">First name *</label>
      <input type="text"  name="firstname_h" id="firstname_h" placeholder="First name" /> // added name="firstname_h"
    </div>

    <div >
      <label for="middlename">Middle name *</label>
      <input type="text"  name="middlename_h" id="middlename_h" placeholder="Middle name" /> // added name="middlename_h"
    </div>

    <div >
      <label for="grade11_h">Grade 11 Transcript (image) *</label>
      <input type="file"  name="grade11_h" id="grade11_h" accept=".png, .jpg, .jpeg">
    </div>
    <button type="submit" name="submit"  onclick="Submit_highschool();">Submit</button>
  </div>
</form>
  • Related