I’m trying to send a file using AJAX with the form but the PHP file seems to receive nothing, not only the files but also the form elements. In PHP if i try to get a value from the $_POST
i get an Undefined Index
.
I’ve tried:
$("#animal-insert").click((e) => { e.preventDefault(); var fd = $("#animal-form-input"); var files = $("#file")[0].files[0]; fd.append("file", files); $.ajax({ url: "php_utility/ajax/admin-animal.php", type: "post", data: fd, cache: false, contentType: false, processData: false, success: function (response) { console.log(response); if (response === "allok") { showModalError("Registrato Correttamente", "modalsuccess"); } else { showModalError("Non Registrato Correttamente", "modalerror"); } }, });
and the method you see in the code below. I’m restricted to do this without plugins.
I was also trying with the $.post()
but if i understood correctly i have to use $.ajax()
to add the processData: false
to send files.
HTML
<form method="POST" action="" id="animal-form-insert" enctype="multipart/form-data"> <div class="span-1-of-2"> <label for="specie" class="label">Specie Animale:</label> <input type="text" class="animal-input" id="specie" name="specie" required placeholder="Pavo cristatus"> <label for="an-name" class="label">Nome Comune:</label> <input type="text" class="animal-input" id="an-name" name="an-name" required placeholder="pavone comune"> </div> <div class="span-1-of-2"> <label for="biom" class="label">Bioma/Habitat:</label> <select class="animal-input" name="biom" id="biom" required> <option value="Savana">Savana</option> <option value="Tundra">Tundra</option> <option value="Pianura">Pianura</option> </select> <label for="zoo-zone" class="label">Zona Zoo:</label> <select class="animal-input" name="zoo-zone" id="zoo-zone"> <option value="A">A</option> <option value="B">B</option> <option value="C">C</option> <option value="F">F</option> <option value="PN">PN</option> </select> </div> <label for="animal-photo" class="label">Foto Animale:</label> <input type="file" id="animal-photo" name="animal-photo" accept=".jpg,.jpeg.png" required> <label for="aniaml-desc" class="label">Descrizione:</label> <textarea class="animal-input-desc" name="animal-desc" id="animal-desc" required></textarea> <button type="submit" name="animal-insert" id="animal-insert" class="btn btn-block">Aggiungi</button> </form>
JS
$("#animal-insert").click((e) => { e.preventDefault(); var formData = { specie: $("#specie").val(), anname: $("#an-name").val(), biom: $("#biom").val(), zoozone: $("#zoo-zone").val(), animaldesc: $("#animal-desc").val(), animalphoto: $("#animal-photo")[0].files[0], submit: "submit", }; console.log(formData); $.ajax({ url: "php_utility/ajax/admin-animal.php", type: "post", data: JSON.stringify(formData), cache: false, contentType: false, processData: false, success: function (response) { console.log(response); if (response === "allok") { showModalError("Registrato Correttamente", "modalsuccess"); } else { showModalError("Non Registrato Correttamente", "modalerror"); } }, }); });
PHP
<?php error_log($_POST['specie']); if (isset($_POST['specie'])) { $animalspecie = $_POST['specie']; $animalName = $_POST['anname']; $animalBiom = $_POST['biom']; $animalZone = $_POST['zoozone']; $animalDesc = $_POST['animaldesc']; $animalPhoto = $_FILES['animalphoto']; $animalPhotoName = $animalPhoto['name']; $photoTmp = $animalPhoto['tmp_name']; $photoErr = $animalPhoto['error']; $photoType = $animalPhoto['type']; error_log("not here"); $formats = ["image/jpg", "image/jpeg", "image/png"]; require_once '../sql/utility.php'; //file with functions for db require_once '../checks.php'; //file with some type checks if (empty($animalspecie) || empty($animalName) || empty($animalBiom) || empty($animalZone) || empty($animalDesc) || empty($animalPhoto)) { echo "emptyinput"; exit(); } if (!preg_match('/[A-Z]+[a-z]+s[a-z]+/', $animalspecie)) { echo "invalidspecie"; exit(); } if (!in_array($photoType, $formats)) { echo "invalidformat"; exit(); } if ($photoErr !== 0) { echo "fileerror"; exit(); } $tmpExtension = explode("/", $photoType); $photoExtension = end($tmpExtension); $photoNewName = preg_replace('/s+/', '', $animalName) . preg_replace('/s+/', '', $animalName) . "." . $photoExtension; $photoDestination = "//resurces/images/animals/" . $photoNewName; move_uploaded_file($photoTmp, $_SERVER['DOCUMENT_ROOT'] . $photoDestination); $result = insertAnimal($conn, $animalspecie, $animalName, $animalBiom, $animalZone, $animalDesc); echo $result; }
Advertisement
Answer
You should create a new FormData()
and append your form values and files to it, and then send it as ‘multipart/form-data’ in the data
(not body
) param.
$("#animal-insert").click((e) => { e.preventDefault(); var formData = new FormData(); formData.append("specie", $("#specie").val()) formData.append("anname", $("#an-name").val()) formData.append("biom", $("#biom").val()) formData.append("zoozone", $("#zoo-zone").val()) formData.append("animaldesc", $("#animal-desc").val()) formData.append("animalphoto", $("#animal-photo")[0].files[0]) formData.append("submit", "submit") $.ajax({ url: "php_utility/ajax/admin-animal.php", method: "post", data: formData, cache: false, mimeType: "multipart/form-data", contentType: false, processData: false, success: function (response) { console.log(response); if (response === "allok") { showModalError("Registrato Correttamente", "modalsuccess"); } else { showModalError("Non Registrato Correttamente", "modalerror"); } }, }); });
In PHP Your files will be avaiable in $_FILES
array, and the other data will be in $_POST
array.
More on FormData: https://developer.mozilla.org/en-US/docs/Web/API/FormData