Send file with jquery and recive in PHP (No plugIn) - javascript

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

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

Related

CodeIgniter file upload error “You did not select a file to upload” using Ajax

I've seen and tried a few answers that are similar to this question, but it still displays the same error.
The console is also giving the error: Uncaught TypeError: Cannot read property 'length' of undefined at Function.each (jquery-1.10.2.js:631)
My view:
<form action="https://dev.vmc.w3.uvm.edu/xana/sensors/deployments" class="basicForm aboutForm form-horizontal" id="deploymentForm" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<div class="form-group">
<label for="fldFileName" class="col-sm-4 control-label">Image</label>
<div class="col-sm-8">
<input type="file" name="fldFileName" value="" class="form-control" id="fldFileName" />
</div>
</div>
<button type="button" class="btn btn-primary" id="newSensorSubmit">Save</button>
</form>
javascript to submit form:
$(document).on("click", "#newSensorSubmit", function(event){
var posturl="<?php echo site_url("sensors/add_deployment");?>";
var formData = new FormData();
var fldFileName = $('#fldFileName').val();
formData.append('fldFileName', fldFileName);
jQuery.ajax({
url: posturl,
data: formData,
cache: false,
mimeType: "multipart/form-data",
dataType: 'json',
contentType: false,
processData: false,
type: 'POST',
success: function(data){
if(data.status === 'success') {
//handle success
}
else {
//handle fail
}
},
error: (error) => {
$('#articleErrorText').html(JSON.stringify(error));
}
});
});
controller:
public function add_deployment(){
$this->load->helper(array('form', 'url'));
$this->load->library('upload');
$config = array(
'upload_path' => site_url("attachments/project/999/metstations"),
'allowed_types' => "gif|jpg|png|jpeg",
'overwrite' => TRUE,
'max_size' => "16000000"
);
$this->load->library('upload', $config);
if($this->upload->do_upload('fldFileName'))
{
$data['image_metadata'] = array('image_metadata' => $this->upload->data());
}
else
{
$error = $this->upload->display_errors();
$data['errors']='<p class="error-message">'.$error.'</p>';
$data['status']='failure';
}
}
Try This.
To get all your form inputs, including the type="file" you need to use FormData object.
To append param just use append() method:
formData.append("param", "value");
And in the php-side I catch it:
echo $file_name = ($_FILES['file']['name']);
View Code:-
<body>
<p id="msg"></p>
<input type="file" id="file" name="file" />
<button id="upload">Upload</button>
</body>
jQuery / Ajax Code:-
<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(e){
$('#upload').on('click', function () {
var file_data = $('#file').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'ControllerName/upload_file', // point to server-side controller method
dataType: 'text', // what to expect back from the server
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
$('#msg').html(response); // display success response from the server
},
error: function (response) {
$('#msg').html(response); // display error response from the server
}
});
});
});
</script>
Controller Code:-
class ControllerName extends CI_Controller {
function __construct() {
parent::__construct();
}
function upload_file() {
//upload file
$config['upload_path'] = 'uploads/';
$config['allowed_types'] = '*';
$config['max_filename'] = '255';
$config['encrypt_name'] = TRUE; // remove it for actual file name.
$config['max_size'] = '1024'; //1 MB
if (isset($_FILES['file']['name'])) {
if (0 < $_FILES['file']['error']) {
echo 'Error during file upload' . $_FILES['file']['error'];
} else {
if (file_exists('uploads/' . $_FILES['file']['name'])) {
echo 'File already exists : uploads/' . $_FILES['file']['name'];
} else {
$this->load->library('upload', $config);
if (!$this->upload->do_upload('file')) {
echo $this->upload->display_errors();
} else {
echo 'File successfully uploaded : uploads/' . $_FILES['file']['name'];
}
}
}
} else {
echo 'Please choose a file';
}
}
}
Note:- For more reference regarding this check this
https://developer.mozilla.org/en-US/docs/Web/API/FormData/append

PHP 7.x can't get post data using Ajax

After submitting the form I can't get post data, no clue where is the problem but I think it's the js file. I'm not advanced in using Ajax so I guess this is the problem.
I'm getting error that can't get $name, $projectFile etc.
So should I rewrite the js or PHP? There are no syntax errors, I want this form to be dynamically submitted with Ajax.
html
<form enctype="multipart/form-data" id="upload-form" class="upload-container">
<label for="projectname">Project Name</label>
<input type="text" id="projectname" name="projectname">
<label for="projecturl">Project Link (Gitlab/Github)</label>
<input type="text" id="projecturl" name="projecturl">
<div class="fileuploader">
<label for="projectpreview">Project Upload</label>
<input type="file" id="projectpreview" name="projectpreview">
</div>
<label for="projectwebsite">Project Website</label>
<input type="text" id="projectwebsite" name="projectwebsite">
<button type="submit" id="upload">Add Project</button>
</form>
js
$('#upload-form').on('submit', (e) => {
e.preventDefault();
let $this = $(this);
let $name = $('#projectname');
let $url = $('#projecturl');
let $file = $('#projectpreview');
let $web = $('#projectwebsite');
$.ajax({
url: '../assets/upload.php',
type: 'POST',
data: new FormData($(this)),
contentType: false,
cache: false,
processData: false,
success: (response) => {
console.log(response);
}
});
// VALIDATION
$('#file').change(() => {
let file = this.files[0];
let imageFile = file.type;
let match = ['image/jpeg', 'image/png', 'image/jpg'];
if (!((imageFile == match[0]) || (imageFile == match[1]) || (imageFile == match[2]))) {
alert('Pleas select valid file: JPEG, PNG, JPG');
$('#file').val('');
return false;
}
});
});
php
<?php
include('db.php');
$name = $_POST['projectname'];
$projectUrl = $_POST['projecturl'];
$projectFile = $_FILES['projectpreview'];
$projectWebsite = $_POST['projectwebsite'];
$date = date('Y-m-d H:i:s');
if (!empty($name) || !empty($projectUrl) || !empty($projectFile['name']) || !empty($projectWebsite)) {
$upFile = '';
if (!empty($projectFile['type'])) {
$fileName = time().'_'.$projectFile['name'];
$valid_extensions = array('jpeg', 'jpg', 'png');
$temporary = explode('.', $projectFile['name']);
$file_extension = end($temporary);
if ((($_FILES['hard_file']['type'] == 'image/png') || ($projectFile['type'] == 'image/jpeg') || ($projectFile['type'] == 'image/jpg')) && in_array($file_extension, $valid_extensions)) {
$sourcePath = $projectFile['tmp_name'];
$targetPath = 'img/photos/'.$fileName;
if (move_uploaded_file($sourcePath, $targetPath)) {
$uploadedFile = $fileName;
}
}
}
if ($connection->query("INSERT INTO projects VALUES('', '$name', '$projectUrl', '$uploadedFile', '$projectWebsite', '$date')")) {
exit('success');
} else {
exit('fail');
}
}
i think you have to remove the contentType argument (and use serializeArrayfrom your Form jQuery Object):
$.ajax({
url: '../assets/upload.php',
type: 'POST',
data: $(this).serializeArray(),
processData: false,
success: (response) => {
console.log(response);
}
});
Convert form fields to key value page and then pass that as the data in AJAX.
$('#upload-form').on('submit', (e) => {
e.preventDefault();
let $this = $(this);
var formData = "";
$.each($('#upload-form').serializeArray(), function(i, field) {
formData += field.name + ": \""+ field.value + "\","
});
formData = formData.replace(/^,|,$/g,'');
console.log(formData);
$.ajax({
url: '../assets/upload.php',
type: 'POST',
data: formData,
contentType: false,
cache: false,
processData: false,
success: (response) => {
console.log(response);
}
});
// VALIDATION
$('#file').change(() => {
let file = this.files[0];
let imageFile = file.type;
let match = ['image/jpeg', 'image/png', 'image/jpg'];
if (!((imageFile == match[0]) || (imageFile == match[1]) || (imageFile == match[2]))) {
alert('Pleas select valid file: JPEG, PNG, JPG');
$('#file').val('');
return false;
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form enctype="multipart/form-data" id="upload-form" class="upload-container">
<label for="projectname">Project Name</label>
<input type="text" id="projectname" name="projectname">
<label for="projecturl">Project Link (Gitlab/Github)</label>
<input type="text" id="projecturl" name="projecturl">
<div class="fileuploader">
<label for="projectpreview">Project Upload</label>
<input type="file" id="projectpreview" name="projectpreview">
</div>
<label for="projectwebsite">Project Website</label>
<input type="text" id="projectwebsite" name="projectwebsite">
<button type="submit" id="upload">Add Project</button>
</form>

multiple option boxes same name jquery ajax

I've got multiple select boxes that have the same name. Right now when I select the value from the first select box its submitting that one and updating the database. When I select and item on an other select box its submitting the value from the first one. I feel like the javascript isn't right. Any idea what is wrong?
Heres my html:
<?php foreach ($result as $row): ?>
<select class="form-control" name="category[]" required>
<option value="" disabled selected>Select The Category </option>
<option value="station">Station</option>
<option value="equipment">Tools/Equipment</option>
<option value="supplies">Supplies</option>
</select>
<input id="taskID" value="<?php echo $row['id']; ?>" hidden></input>
<?php endforeach; ?>
jquery:
$(document).on('change', 'select[name="category[]"]', function(event){
$('select[name="category[]"]').each(function(){
var formData = {
'task': $('select[name="category[]"]').val(),
'name': $('input[name="taskID[]"]').val(),
};
$.ajax({
type: 'POST',
url: 'php/addressBook.php',
data: formData,
dataType: 'html',
encode: true
})
.done(function(msg) {
$(".alert").html(msg);
})
.fail(function(data) {
console.log(data);
})
event.preventDefault();
});
});
addressBook.php
if (isset($_POST['task'])) {
$task = $_POST['task'];
$id = $_POST['name'];
$stmt = $con->prepare("UPDATE members SET task = ? WHERE id = ?");
$stmt->bind_param('ss', $task, $id);
$stmt->execute();
}
Change the class attribute to: class="form-control categorySelect"
$('.categorySelect').change(function(event){
for(selectInstance of $('.categorySelect')){
var formData = {
'task': $(selectInstance).val(),
'name': $(selectInstance).next().val()
};
$.ajax({
type: 'POST',
url: 'php/addressBook.php',
data: formData,
dataType: 'html',
encode: true
})
.done(function(msg) {
$(".alert").html(msg);
})
.fail(function(data) {
console.log(data);
})
event.preventDefault();
}
});

Auto submit Form via ajax on selecting image

I have this form to change profile pic of user. I am trying to change the pic on clicking current pic and select from user filesystem
Form:
<form id="changeProfilePicForm" action="<?=base_url()?>user/change_profile_pic" method="post" accept-charset="utf-8" enctype="multipart/form-data">
<div data-content="Click To update" class="image" id="profile-image">
<input id="profile-image-upload" class="hidden" name="image" type="file" accept="image/x-png, image/gif, image/jpeg">
<?if(strlen($user['image'])){?>
<img src="<?=base_url().'uploads/profile/'.$user['image']?>" class="img-circle" alt="user profile pic" height="125px" width="125px">
<?}else{?>
<img src="<?=base_url()?>includes/img/avtar.png" class="img-circle" alt="user profile pic" height="125px" width="125px">
<?}?>
<input type="submit" class="hidden">
</div>
</form>
Javascript:
$("#changeProfilePicForm").on('submit',(function(e){
e.preventDefault();
var $form = $( this );
$.ajax({
url: $form.attr( 'action' ),
type: "POST",
data: new FormData($form),
contentType: false,
cache: false,
processData:false,
success: function(data){
console.log(data);
},
error: function(data){
console.log(data);
}
});
}));
document.getElementById('profile-image').onclick = function() {
document.getElementById('profile-image-upload').click();
};
document.getElementById('profile-image-upload').onchange = function(){
document.getElementById('changeProfilePicForm').submit();
};
PHP controller:
public function change_profile_pic()
{
$user_id = $this->session->user_id;
$image = $this->uploadimage();
if(strlen($image)){
$user_data['image'] = $image;
$updated = $this->user_model->update_user($user_id, $user_data);
$data['response'] = 1;
$data['image'] = $image;
// redirect(base_url()."user");
echo json_encode($data);
}else{
$data['response'] = 0;
$data['message'] = "error";
echo json_encode($data);
}
//redirect(base_url()."user");
}
Problem I am facing is, the form is not submitted via ajax. It is directory submitted as simple form. I can't figure out whats wrong with the code since image is being upload on simple form submission. Is there any problem with event binding or i am missing something here ?
When you call
document.getElementById('changeProfilePicForm').submit();
the submit event is not fired. Try
$('#changeProfilePicForm').trigger('submit');
Edit. Get rid of the form in html:
<input type="file" id="image">
js:
function handleUpload(event) {
var file = this.files[0];
if (!file) return;
var formData = new FormData();
formData.append('file', file);
return $.ajax({
type: 'POST',
url: '/images',
data: formData,
processData: false,
contentType: false,
//...
});
}
$('#image').on('change', handleUpload);
I believe FormData expects a native form element $form[0], not jQuery form element $form.
$("#changeProfilePicForm").submit(function (e) {
e.preventDefault();
var $form = $(this);
$.ajax({
url: $form.attr('action'),
type: "POST",
data: new FormData($form[0]),
contentType: false,
cache: false,
processData: false,
success: function (data) {
console.log(data);
},
error: function(data){
console.log(data);
}
});
}));

jquery: Removing class transferred from JSON response

I created a function in laravel that raises some pictures together and returns their names, so I can view them immediately on the page without having to refresh the browser. I want to allow deleting a photo, but it does not give that return values ​​through JSON are not in the DOM. What am I doing wrong?
HTML:
<form action="" enctype="multipart/form-data" id="data">
<input type="file" name="image[]" multiple>
<button type="submit">send</button>
</form>
<hr>
<div class="returns_img"> </div>
<script type="text/javascript">
$("form#data").submit(function(event){
event.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: "upimage",
type: "POST",
data: formData,
async: false,
success: function(msg){
$(".returns_img").append(msg);
},
cache: false,
contentType: false,
processData: false
});
});
$("#dell_msg").click(function(){
$(".up_side").removeClass(".list_img");
});
Routes.php:
Route::post('upimage', function(){
foreach (Input::file("image") as $image) {
$imagename = time(). $image->getClientOriginalName();
$upload = $image->move(public_path() . "/img/",$imagename);
if ($upload) {
$uploaddata [] = $imagename;
}
echo "<div class='list_img'><img src='/img/". $imagename. "'><button id='dell_msg'>X</button> </div>";
}

Categories

Resources