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
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:
// added the "name" tag to the form elements
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.