I have a form with multiple fields, one of them is register_id. I also have an upload button where I can upload multiple images through a modal. Once the user presses submit I have an ajax call sending both the register_id as well as the form data. However, I am having problems accessing the form data.
This is my javascript that is executed when the user presses submit from the modal window where they upload the images:
$("form").on("submit", function(e) {
e.preventDefault();
var regId = (document.getElementById('register_id').value);
var formdata = new FormData(this);
var postData = { formdata: formdata, regId: regId };
var dataString = JSON.stringify(postData);
$.ajax({
url: 'uploadImages.php',
type: 'POST',
data: {myData:dataString},
dataType: "json",
success: function(response) {
document.getElementById("body").innerHTML = "<p>"+response+"</p>";
},
});
});
In my PHP I would like to create a custom folder depending on the register Id passed and get all the images. I am managing to echo the register id but I am having trouble getting the formdata. As soon as I echo $obj->formdata;
I get:
jquery.min.js:2 POST http://localhost/CanvasCreator/uploadImages.php 500 (Internal Server Error)
send @ jquery.min.js:2
ajax @ jquery.min.js:2
(anonymous) @ uploadImages.js:7 dispatch @ jquery.min.js:2 v.handle @ jquery.min.js:2
This is my php code:
<?php
$obj = json_decode($_POST["myData"]);
$regNo = $obj->regId;
$formData = $obj->formdata;
$all_files = $formData;
echo($formData);
echo($regNo);
$path = 'SourceImages/'.$regNo.'/';
mkdir($path, 0777, true);
$extensions = ['tif'];
$all_files = count($_FILES['file']['name']);
for ($i = 0; $i < $all_files; $i++) {
$uploadOk = "";
$file_name = $_FILES['file']['name'][$i];
$file_tmp = $_FILES['file']['tmp_name'][$i];
$file_type = $_FILES['file']['type'][$i];
$file_size = $_FILES['file']['size'][$i];
$file_ext = strtolower(end(explode('.', $_FILES['file']['name'][$i])));
$file = $path . $file_name;
if (!in_array($file_ext, $extensions)) {
$uploadOk = $uploadOk . 'Extension not allowed: ' . $file_name. '</br>';
}
if ($file_size > 2097152) {
$uploadOk = $uploadOk . 'File size exceeds limit: ' . $file_name. '</br>';
}
if (file_exists($file)) {
$uploadOk = $uploadOk . 'File already exists: ' . $file_name. '</br>';
}
if ($file_size <1) {
$uploadOk ='Choose at least one image file' . $file_name. '</br>';
}
if($uploadOk != ""){
echo $uploadOk;
}else{
if(move_uploaded_file($file_tmp,$file)){
echo "File saved: ".$file_name."</br>";
}else{
echo "File not saved: ".$file_name."</br>";
}
}
}