Dropzone with PHP MVC - javascript

Hy, i have a form with general fields and a php file with a function to get the form filds and persist on mysql, i showd use dropzone to upload some files with these information, but when i press the submit button justo the filds are received on php, the files informations dont
my form code:
<form id="myDropzone" class="dropzone form-horizontal" method="POST">
<div class="form-group">
<label class="col-sm-2 control-label">Selecione o associado</label>
<select data-placeholder="Selecione o associado" name="idassociado" id="idassociado" class="select2_demo_1 form-control required" style="width:250px;">
<option value="">Selecionar</option>
<? print_r($home->associados); ?>
</select>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Marca</label>
<div class="col-sm-4"><input type="text" placeholder="Marca do veículo" id="marca" name="marca" class="form-control required"></div>
<label class="col-sm-1 control-label">Modelo.</label>
<div class="col-sm-2"><input type="text" placeholder="Modelo do veículo" id="modelo" name="modelo" class="form-control required"></div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Placa</label>
<div class="col-sm-4"><input type="text" placeholder="Placa do veículo" id="placa" name="placa" data-mask="aaa-9999" class="form-control required"></div>
<label class="col-sm-1 control-label">Eixos</label>
<div class="col-sm-2"><input type="text" placeholder="Número de eixos" id="eixos" name="eixos" class="form-control required"></div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Ano Fab.</label>
<div class="col-sm-2"><input type="text" placeholder="Ano de fabricação" data-mask="9999" id="ano_fab" name="ano_fab" class="form-control required"></div>
<label class="col-sm-3 control-label">Ano Modelo</label>
<div class="col-sm-2"><input type="text" id="ano_mod" name="ano_mod" placeholder="Ano do Modelo" data-mask="9999" class="form-control required"></div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Cor.</label>
<div class="col-sm-3"><input type="text" placeholder="Cor" id="cor" name="cor" class="form-control required"></div>
<label class="col-sm-2 control-label">Tipo</label>
<div class="col-sm-2">
<select data-placeholder="Selecione o tipo" name="tipo" id="tipo" class="select2_demo_1 form-control required" style="width:150px;">
<option value="">Selecionar</option>
<option value="Cavalo">Cavalo</option>
<option value="Carreta">Carreta</option>
<option value="Tanque">Tanque</option>
<option value="Truck">Truck</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Quilometragem</label>
<div class="col-sm-4"><input type="text" id="quilometragem" name="quilometragem" placeholder="Quilometragem" class="form-control required"></div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Chassi</label>
<div class="col-sm-3"><input type="text" id="chassi" name="chassi" placeholder="Chassi" class="form-control required"></div>
<label class="col-sm-1 control-label">Renavam</label>
<div class="col-sm-3"><input type="text" id="renavam" name="renavam" placeholder="Renavam" class="form-control required"></div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Valor da cobertura</label>
<div class="col-sm-2"><input type="text" id="valor_cobertura" name="valor_cobertura" placeholder="Valor da cobertura" class="form-control required"></div>
<label class="col-sm-1 control-label">Cotas.</label>
<div class="col-sm-1"><input type="text" readonly id="cotas" name="cotas" placeholder="Cotas" class="form-control"></div>
<label class="col-sm-1 control-label">Mensalidade</label>
<div class="col-sm-2"><input type="text" readonly id="mensalidade" name="mensalidade" Placeholder="Valor da Mensalidade" class="form-control required"></div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Número da ficha:</label>
<div class="col-sm-2"><input type="text" id="num_ficha" name="num_ficha" placeholder="Numero da ficha" class="form-control required"></div>
<div class="i-checks">
<label> <input type="checkbox" id="rastreador" name="rastreador" value="Sim"> <i></i>Rastreador </label>
<label> <input type="checkbox" id="guincho" name="guincho" value="Sim"> <i></i>Guincho </label></div>
</div>
<div class="form-group">
<div class="ibox-title">
<h5>Fotos do veículo</h5>
</div>
<div name="file" id="file" class="dropzone dz-clickable dz-default dz-file-preview">
</div>
</div>
<div class="form-group">
<div class="col-sm-2"></div>
<div class="col-sm-4"><button class="btn btn-primary" type="submit">Cadastrar</button></div>
</div>
</form>
Here is my dropzone code:
$(document).ready(function(){
$("div#file").dropzone({ url: "#" });
Dropzone.options.myDropzone = {
autoDiscover: false,
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 50,
maxFiles: 50,
paramName: 'pic',
addRemoveLinks: true,
previewContainer: '#dropzone',
clickable: false,
accept: function(file, done) {
console.log("uploaded");
done();
},
error: function(file, msg){
alert(msg);
},
init: function() {
var myDropzone = this;
this.element.querySelector("button[type=submit]").addEventListener("click", function(e) {
e.preventDefault();
e.stopPropagation();
myDropzone.processQueue();
});
}
};});
And on my model PHP function :
public function validate_veiculo_form () {
if (!empty($_FILES)) {
$tempFile = $_FILES['images']['tmp_name'];
$targetPath = $directory;
$targetFile = $targetPath. $_FILES['images']['name'];
move_uploaded_file($tempFile,$targetFile);
}else{
$this->error = "Array de fotos vazio";
return;
}}
The only result i get is the "Array de fotos vazio", someone can help me ?

Related

form inputs data failed to be received when element is inserted with JavaScript

I am trying to dynamically change the html of parent form element to display according the what the user wants to upload, then retrieve the data from that child element. I saved the list of children to dynamically input in the js folder leaving the parent form element empty.
The issue is:
a) When I dynamically input the preferred child element according to what user wants to upload, It doesn't retrieve the values even though it shows in the DOM that the element is there.
b) Whereas if I statically input the child element in html folder, it works just fine. but when the child is changed again, its still the statically inputted values I get back.
please how do I go about this?? Here's the codepen showing it.
<div class="upload-box container mt-3">
<div class="title-box-d">
<h3 class="title-d upload-type">Uploading A Car</h3>
</div>
<div class="box-collapse-wrap form ">
<div class="form-group mb-5">
<div class="row">
<div class="col-md-4">
<label for="upload">What Do You Want To Upload?</label>
<select class="form-control form-control-lg form-control-a" id="upload">
<option value="cars">Car</option>
<option value="houses">House/Home</option>
<option value="land">Land Properties</option>
</select>
</div>
</div>
</div>
<form class="form-a form-upload">
</div>
</form>
</div>
</div>
The JS
///////////////////////
/*--/ Project Logic /--*/
//////////////////////
const projectData = {
uploadCategories: {
carForm: ` <div class="row">
<div class="col-md-8 mb-2">
<div class="form-group">
<label for="file">Add Photo</label>
<input type="file" id="file" accept="image/*" multiple="multiple"
class="form-control form-control-lg form-control-a">
</div>
</div>
<div class="col-md-4 mb-2">
<div class="form-group">
<label for="location">Location</label>
<input type="text" class="form-control form-control-lg form-control-a" id="location">
</div>
</div>
<div class="col-md-4 mb-2">
<div class="form-group">
<label for="brand">Car Brand</label>
<input type="text" class="form-control form-control-lg form-control-a" id="brand"
placeholder="Eg Toyota, Lexus etc">
</div>
</div>
<div class="col-md-4 mb-2">
<div class="form-group">
<label for="car-model">Car Model</label>
<input type="text" class="form-control form-control-lg form-control-a" id="car-model"
placeholder="eg Venza, Sienna, Corolla Etc">
</div>
</div>
<div class="col-md-4 mb-2">
<div class="form-group">
<label for="year">Year</label>
<input type="number" class="form-control form-control-lg form-control-a" id="year">
</div>
</div>
<div class="col-md-4 mb-2">
<div class="form-group">
<label for="condition">Condition</label>
<select class="form-control form-control-lg form-control-a" id="condition">
<option>Brand New</option>
<option>Nigerian Used</option>
<option>Foreign Used</option>
</select>
</div>
</div>
<div class="col-md-4 mb-2">
<div class="form-group">
<label for="transmission">Transmission</label>
<select class="form-control form-control-lg form-control-a" id="transmission">
<option>Automatic</option>
<option>Manual</option>
</select>
</div>
</div>
<div class="col-md-4 mb-2">
<div class="form-group">
<label for="registered">Registered?</label>
<select class="form-control form-control-lg form-control-a" id="registered">
<option>Yes</option>
<option>No</option>
</select>
</div>
</div>
<div class="col-md-4 mb-2">
<div class="form-group">
<label for="mileage">Mileage</label>
<input type="number" class="form-control form-control-lg form-control-a" id="mileage"
placeholder="Mileage (km)">
<div class="form-group mt-3">
<label for="price">Price</label>
<input type="number" class="form-control form-control-lg form-control-a" id="price">
</div>
</div>
</div>
<div class="col-md-8 mb-2">
<div class="form-group">
<label for="description">Description</label>
<textarea class="form-control form-control-lg form-control-a"
placeholder="Add more description to your Ad" id="description" cols="30" rows="30"
style="height: 10rem;"></textarea>
</div>
</div>
<div class="col-md-12">
<button type="submit" class="btn btn-b">Upload</button>
</div>
</div>`,
houseForm: `<div class="row">
<div class="col-md-8 mb-2">
<div class="form-group">
<label for="file">Add Photo</label>
<input type="file" id="file" accept="image/*" multiple="multiple"
class="form-control form-control-lg form-control-a">
</div>
</div>
<div class="col-md-4 mb-2">
<div class="form-group">
<label for="location">Location</label>
<input type="text" class="form-control form-control-lg form-control-a" id="location">
</div>
</div>
<div class="col-md-4 mb-2">
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control form-control-lg form-control-a" id="title"
placeholder="Title or name of the Property">
</div>
</div>
<div class="col-md-4 mb-2">
<div class="form-group">
<label for="area">Property Size (sqm)</label>
<input type="number" class="form-control form-control-lg form-control-a" id="area">
</div>
</div>
<div class="col-md-4 mb-2">
<div class="form-group">
<label for="bedrooms">Bedrooms</label>
<input type="number" class="form-control form-control-lg form-control-a" id="bedrooms">
</div>
</div>
<div class="col-md-4 mb-2">
<div class="form-group">
<label for="bathrooms">Bathrooms</label>
<input type="number" class="form-control form-control-lg form-control-a" id="bathrooms">
</div>
</div>
<div class="col-md-4 mb-2">
<div class="form-group">
<label for="sale-status">For Sale Or rent?</label>
<select class="form-control form-control-lg form-control-a" id="sale-status">
<option>For Sale</option>
<option>For Rent</option>
</select>
</div>
</div>
<div class="col-md-4 mb-2">
<div class="row">
<div class="col-6">
<div class="form-group">
<label for="garage">Garage</label>
<input type="number" class="form-control form-control-lg form-control-a" id="garage">
</div>
</div>
<div class="col-6">
<div class="form-group">
<label for="price">Price</label>
<input type="number" class="form-control form-control-lg form-control-a" id="price">
</div>
</div>
</div>
</div>
<div class="col-md-4 mb-2">
<div class="form-group">
<label for="amenities">Other Amenities</label>
<select class="form-control form-control-lg form-control-a" id="amenities" multiple style="height: 10rem;">
<option>Parking Space</option>
<option>24 Hours Electricity</option>
<option>Internet</option>
<option>Air Conditioning</option>
<option>Security</option>
<option>Balcony</option>
<option>Tile Floor</option>
<option>Dish Washer</option>
<option>Dining Area</option>
<option>Kitchen Cabinet</option>
<option>Kitchen Shelf</option>
<option>Wardrobe</option>
<option>WIFI</option>
<option>POP Ceiling</option>
<option>Prepaid Meter</option>
<option>Concrete Flooring</option>
</select>
</div>
</div>
<div class="col-md-8 mb-2">
<div class="form-group">
<label for="description">Description</label>
<textarea class="form-control form-control-lg form-control-a" placeholder="Add more description to your Ad"
id="description" cols="30" rows="30" style="height: 10rem;"></textarea>
</div>
</div>
</div>
<div class="col-md-12">
<button type="submit" class="btn btn-b">Upload</button>
</div>`,
landForm: `<div class="row">
<div class="col-md-8 mb-2">
<div class="form-group">
<label for="file">Add Photo</label>
<input type="file" id="file" accept="image/*" multiple="multiple"
class="form-control form-control-lg form-control-a">
</div>
</div>
<div class="col-md-4 mb-2">
<div class="form-group">
<label for="location">Location</label>
<input type="text" class="form-control form-control-lg form-control-a" id="location">
</div>
</div>
<div class="col-md-4 mb-2">
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control form-control-lg form-control-a" id="title"
placeholder="Title or name of the Land.">
</div>
</div>
<div class="col-md-4 mb-2">
<div class="form-group">
<label for="area">Property Size (sqm)</label>
<input type="number" class="form-control form-control-lg form-control-a" id="area">
</div>
</div>
<div class="col-md-4 mb-2">
<div class="form-group">
<label for="land-type">Type Of Land</label>
<select class="form-control form-control-lg form-control-a" id="land-type" placeholder="What Type of Land is This?">
<option>Commercial Land</option>
<option>Farmland</option>
<option>Industrial Land</option>
<option>Mixed-use LAnd</option>
<option>Quarry</option>
<option>Residential Land</option>
</select>
</div>
</div>
<div class="col-md-4 mb-2">
<div class="row">
<div class="col-12">
<div class="form-group">
<label for="sale-status">For Sale Or Lease?</label>
<select class="form-control form-control-lg form-control-a" id="sale-status">
<option>For Sale</option>
<option>For Lease</option>
</select>
</div>
</div>
<div class="col-12">
<div class="form-group">
<label for="price">Price</label>
<input type="number" class="form-control form-control-lg form-control-a" id="price">
</div>
</div>
</div>
</div>
<div class="col-md-4 mb-2">
<div class="form-group">
<label for="amenities">Other Amenities</label>
<select class="form-control form-control-lg form-control-a" id="amenities" multiple style="height: 10rem;">
<option>Parking Space</option>
<option>Electric Supply</option>
<option>Domestic Sewage</option>
<option>Gas Supply</option>
<option>Rain Water Drainage</option>
<option>Water Supply</option>
</select>
</div>
</div>
<div class="col-md-4 mb-2">
<div class="form-group">
<label for="description">Description</label>
<textarea class="form-control form-control-lg form-control-a" placeholder="Add more description to your Ad"
id="description" cols="30" rows="30" style="height: 10rem;"></textarea>
</div>
</div>
</div>
<div class="col-md-12">
<button type="submit" class="btn btn-b">Upload</button>
</div>`
},
fromInputs: {
Name: $('#title'),
Brand: $('#brand'),
Model: $('#car-model'),
Location: $('#location'),
Description: $('#description'),
Status: $('#sale-status'),
Price: $('#price'),
Bedrooms: $('#bedrooms'),
Bathrooms: $('#bathrooms'),
Garage: $('#garage'),
Area: $('#area'),
Amenities: $('#amenities'),
'Type Of Land': $('#land-type'),
Year: $('#year'),
Condition: $('#condition'),
Transmission: $('#transmission'),
Registered: $('#registered'),
Mileage: $('#mileage'),
},
formImages: {
dataReferenceId: 'dataid',
images: []
},
dataToSubmit : ''
};
/*--/ Admin Page Code /--*/
// Check what typemof data user wants to upload and display from related to that
$('#upload').change(e => {
switch (e.target.value) {
case 'houses':
$('.upload-type').text('Uploading A House');
$('.form-upload').html(projectData.uploadCategories.houseForm);
break;
case 'land':
$('.upload-type').text('Uploading A Land');
$('.form-upload').html(projectData.uploadCategories.landForm);
break;
default:
$('.upload-type').text('Uploading A Car');
$('.form-upload').html(projectData.uploadCategories.carForm);
break;
}
});
// GET ALL UPLOAD FORM DATA INPUTED
$('.form-upload').submit(function (event) {
event.preventDefault();
// Check what category user wants to upload
const uploadCategory = $('#upload').val();
// GET ALL THE DATA FOR A FORM SESSION UPLOADED
const data = Object.entries(projectData.fromInputs).map(([key, value]) => [key, value && value.val()]);
// FILTER THE DATA TO RETURN ON THOSE WITH VALUES
const filteredData = Object.fromEntries(
data.filter(([key, value]) => value
));
console.log(filteredData);
// projectData.dataToSubmit = filteredData;
});
CODEPEN: https://codepen.io/genral-walker/pen/vYgqbvL
Main problem is that you're caching reference to elements that might not be in DOM at the time. You should store a selector instead:
fromInputs: {
Name: '#title',
Brand: '#brand',
Model: '#car-model',
Location: '#location',
Description: '#description',
Status: '#sale-status',
Price: '#price',
Bedrooms: '#bedrooms',
Bathrooms: '#bathrooms',
Garage: '#garage',
Area: '#area',
Amenities: '#amenities',
'Type Of Land': '#land-type',
Year: '#year',
Condition: '#condition',
Transmission: '#transmission',
Registered: '#registered',
Mileage: '#mileage',
},
And then look it up later:
const data = Object.entries(projectData.fromInputs).map(([key, value]) => {
console.log(key, value);
const $el = $(value);
return [key, $el.length && $el.val()];
});
https://codepen.io/genral-walker/pen/vYgqbvL?editors=1111

integrating dropzone with normal form

I have successfully integrated dropzone with my form using jquery. However, I have an issue with validation of the other form inputs. It seems the other form inputs do not respect the validation such as "required". I also tried using parsley for validation but does not work. when I remove the dropzone field, the validation works well.
Here is the form.
<form class="form-vertical"
id="createPropertyForm"
enctype="multipart/form-data"
method="POST"
>
<div class="col-md-12 col-lg-12 col-sm-12" >
<div class="col-md-6">
<div class="form-group">
<label class=" control-
label">Country</label>
<div class="inputGroupContainer">
<input id="country"
name="country" placeholder="Country" class="form-control" required
value="" type="text">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-
label">County</label>
<div
class="inputGroupContainer">
<input id="county"
name="county" placeholder="County" class="form-control" required value=""
type="text">
</div>
</div>
</div>
</div>
<div class="col-md-12 col-lg-12 col-sm-12" >
<div class="col-md-6">
<div class="form-group">
<label class=" control-
label">Town</label>
<div class=" inputGroupContainer">
<input id="town" name="town"
placeholder="Town" class="form-control" required value="" type="text">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-
label">Postcode</label>
<div class="inputGroupContainer">
<input id="postcode"
name="postcode" placeholder="Postcode" class="form-control" required
value=""
type="text">
</div>
</div>
</div>
</div>
<div class="col-md-12 col-lg-12 col-sm-12" >
<div class="col-md-6">
<div class="form-group">
<label class=" control-
label">Description</label>
<div class=" inputGroupContainer">
<textarea id="description"
name="description" placeholder="Description" class="form-control"
required="true" value="" type="text"></textarea>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-
label">Address</label>
<div class="inputGroupContainer">
<input id="address" name="address"
placeholder="Address" class="form-control" required value="" type="text">
</div>
</div>
</div>
</div>
<div class="col-md-12 col-lg-12 col-sm-12" >
<div class="col-md-6">
<div class="form-group">
<label class=" control-
label">Bedrooms</label>
<div class=" inputGroupContainer">
<select class=" form-control"
name="bedrooms" id="bedrooms" required>
</select>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-label
">Bathrooms</label>
<div class=" inputGroupContainer">
<select
class="selectpicker bathrooms form-control" name="bathrooms"
id="bathrooms"
required>
</select>
</div>
</div>
</div>
</div>
<div class="col-md-12 col-lg-12 col-sm-12" >
<div class="col-md-6">
<div class="form-group">
<label class=" control-
label">Price</label>
<div class="inputGroupContainer">
<input id="price" name="price"
placeholder="Price" class="form-control" required value="" type="number">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-
label">Property Type</label>
<div class=" inputGroupContainer">
<select
class="selectpicker form-control" name="propertyType" id="propertyType">
<option
value="">Choose type</option>
<?php
foreach
($propertyTypes as $propertyType) {
?>
<option value="<?=
$propertyType->id ?>"><?= $propertyType->title ?></option>
<?php
}
?>
</select>
</div>
</div>
</div>
</div>
<div class="col-md-12 col-lg-12 col-sm-12" >
<div class="col-md-6">
<div class="form-group">
<label class=" control-
label">Type</label>
<div class="col-md-12">
<div class="col-md-6 ">
<label><input type="radio"
name="type" class="form-control type" required>Sale</label>
</div>
<div class="col-md-6">
<label><input type="radio"
name="type" class="form-control type" required>Rent</label>
</div>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-
label">Upload Image</label>
<div class=" inputGroupContainer">
<div class="dropzone"
id="create-dropzone" >
<div class="fallback">
<input name="file"
type="file" required/>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6 col-sm-6">
<div class="dropzone-previews"></div>
</div>
</div>
<div class="col-md-6 col-sm-6">
<button class="btn btn-success btn-lg"
type="submit" id="submitCreateForm"> Submit </button>
</div>
</form>.
Here is the jquery code:
// Parsley for form validation
$('#createPropertyForm').parsley();
$('#editPropertyForm').parsley();
Dropzone.options.createDropzone = {
url: `${baseUrl}administrator/properties`,
autoProcessQueue: false,
parallelUploads: 1,
maxFiles: 1,
maxFileSize:2048,
uploadMultiple: false,
acceptedFiles: "image/*",
init: function () {
var submitButton = document.querySelector("#submitCreateForm");
var wrapperThis = this;
submitButton.addEventListener("click", function (e) {
e.preventDefault();
if (wrapperThis.files.length) {
wrapperThis.processQueue();
} else {
wrapperThis.submit();
}
});
this.on("addedfile", function (file) {
var removeButton = Dropzone.createElement("<button class='btn btn-block btn-danger'><i class='fa-times fa'></button>");
removeButton.addEventListener("click", function (e) {
e.preventDefault();
e.stopPropagation();
wrapperThis.removeFile(file);
});
file.previewElement.appendChild(removeButton);
});
this.on('sending', function (data, xhr, formData) {
formData.append("country", $("#country").val());
formData.append("county", $("#county").val());
formData.append("town", $("#town").val());
formData.append("postcode", $("#postcode").val());
formData.append("description", $("#description").val());
formData.append("address", $("#address").val());
formData.append("bathrooms", $("#bathrooms").val());
formData.append("price", $("#price").val());
formData.append("bedrooms", $("#bedrooms").val());
formData.append("propertyTypeId", $("#propertyType").val());
formData.append("type", $(".type").val());
});
this.on('success', function (files, response) {
toastr.success(response.message);
setTimeout(function () {
location.reload();
}, 1000);
});
this.on('error', function (file, error, xhr) {
file.status = 'queued';
if (xhr.status === 422){
toastr.error('An error occurred, please confirm that you have filled all inputs and try again');
}else{
toastr.error('An error occurred');
}
});
this.on("maxfilesexceeded", function(file) {
wrapperThis.removeFile(file);
});
}
};

Ajax PHP Form Submission with Image and Text

I'm writing an app that allows my wife to add her recipes to a database i have set up. I have a form set up with both text and a file input for an image. It works fine and she can upload text and image to the database. Now, I'm trying to add a feature so that she can edit it. It's the same exact form only the data goes to a different PHP file for processing. When she clicks the "Edit" button it populates all the text inputs with the data pulled from the server and she can edit. She can also add a new photo if she wishes. Despite the fact that it's the same form, it will not upload the image. The text uploads fine, but the $_POST['recipeImage'] is always empty when I look at the object being sent to the server (recipeImage: "");
I am baffled and cannot see why this isn't working. Here is the code:
HTML FORM (IMAGE UPLOAD IS A BOTTOM):
<div id="editRecipeModal">
<div class="col-md-8">
<div class="card">
<form action="../PHP/modify_recipe.php" method="POST" role="form" class="form-horizontal" enctype="multipart/form-data" id="editRecipeForm" name="editRecipeForm">
<input class="form-control" type="hidden" value="" id="creatorIdEdit" name="creatorId">
<input class="form-control" type="hidden" value="" id="recipeIdEdit" name="recipeId" value="">
<div class="card-header card-header-text" data-background-color="purple">
<h4 class="card-title"><i class="far fa-edit"></i> Edit Recipe</h4>
</div>
<div class="card-content"
<div class="row">
<label class="col-sm-2 label-on-left">Recipe Name</label>
<div class="col-sm-9">
<div class="form-group label-floating is-empty">
<label class="control-label"></label>
<input class="form-control" type="text" name="name" maxlength="150" id="editRecipeName" required>
</div>
</div>
</div>
<div class="row">
<label class="col-sm-2 label-on-left">Prep Time</label>
<div class="col-sm-9">
<div class="form-group label-floating is-empty">
<label class="control-label"></label>
<input class="form-control" type="number" name="prepTime" id="editPrepTime" required>
<span class="help-block">Numbers Only. In minutes... ie: 120 Minutes</span>
</div>
</div>
</div>
<div class="row">
<label class="col-sm-2 label-on-left">Servings</label>
<div class="col-sm-9">
<div class="form-group label-floating is-empty">
<label class="control-label"></label>
<input class="form-control" type="number" name="servings" id="editServings" required>
<span class="help-block">Numbers Only...</span>
</div>
</div>
</div>
<div class="row">
<label class="col-sm-2 label-on-left">Calories</label>
<div class="col-sm-9">
<div class="form-group label-floating is-empty">
<label class="control-label"></label>
<input class="form-control" type="number" name="calories" id="editCalories" required>
<span class="help-block">Numbers Only</span>
</div>
</div>
</div>
<div class="row">
<label class="col-sm-2 label-on-left">Brief Description</label>
<div class="col-sm-9">
<div class="form-group label-floating is-empty">
<label class="control-label"></label>
<textarea class="form-control" name="description" id="editBriefDescription" rows="5" required></textarea>
</div>
</div>
</div>
<hr>
<div class="row">
<label class="col-sm-2 label-on-left">Ingredients</label>
<div class="col-sm-9">
<div class="form-group label-floating is-empty">
<label class="control-label"></label>
<textarea class="form-control" name="ingredients" id="editPasteIngredientsShow" rows="20" required></textarea>
</div>
</div>
</div>
<div class="row">
<label class="col-sm-2 label-on-left">Recipe Steps</label>
<div class="col-sm-9">
<div class="form-group label-floating is-empty">
<label class="control-label"></label>
<textarea class="form-control" name="directions" id="editPasteStepsShow" rows="20" required></textarea>
</div>
</div>
</div>
<div class="row">
<label class="col-sm-2 label-on-left">Search Tags</label>
<div class="col-sm-9">
<div class="form-group label-floating is-empty">
<label class="control-label"></label>
<input class="form-control" type="text" id="editTags" name="tags" required>
</div>
</div>
</div><br> <br> <br> <br>
<div class="row">
<div class="col-md-12">
<div class="row">
<div class="col-lg-4 col-md-6 col-sm-3">
<select class="selectpicker" data-style="btn btn-primary btn-round" title="vegOrVegan" data-size="7" id="vegOrVeganEditSelect">
<option disabled selected>Dietary Restrictions</option>
<option value="" name="">None</option>
<option value="T" name="T">Vegetarian</option>
<option value="VG" name="VG">Vegan</option>
</select>
<input type="hidden" id="vegOrVeganEdit" name="vegOrVegan">
</div>
<div class="col-lg-4 col-md-6 col-sm-3">
<select class="selectpicker" id="suggestedPairingEditSelect" data-style="btn btn-primary btn-round" title="Suggested Pairing" data-size="7">
<option disabled selected>Suggested Pairing</option>
<option value="" name="">None</option>
<option value="B" name="B">Beer</option>
<option value="WW" name="WW">White Wine</option>
<option value="RW" name="RW">Red Wine</option>
</select>
<input type="hidden" id="suggestedPairingEdit" name="suggestedPairing" value="">
</div>
<div class="col-lg-4 col-md-6 col-sm-3">
<select class="selectpicker" id="" data-style="btn btn-primary btn-round" title="Some Other Attributes" data-size="7">
<option disabled selected>Some Other Attributes</option>
<option value="" name="">None</option>
<option value="B" name="B">Beer</option>
<option value="WW" name="WW">White Wine</option>
<option value="WW" name="WW">Red Wine</option>
</select>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12" style="text-align: center;">
</div>
</div>
<div class="row" style="width: 80%; margin: 0 auto;">
<div class="col-sm-4"></div>
<div class="col-sm-4" style="text-align: center;">
<div class="fileinput fileinput-new text-center" data-provides="fileinput">
<div class="fileinput-new thumbnail">
<img src="../assets/img/placeholder.jpg" alt="...">
</div>
<div class="fileinput-preview fileinput-exists thumbnail"></div>
<div>
<span class="btn btn-rose btn-round btn-file">
<span class="fileinput-new">Select image</span>
<span class="fileinput-exists">Change</span>
<input type="file" name="recipeImage" id="recipeImageEdit" />
</span>
<i class="fa fa-times"></i> Remove
</div>
</div>
</div>
<div class="col-sm-4"></div>
</div>
<br><br>
<div class="row">
<div class="col-sm-2"></div>
<div class="col-sm-4" style=" text-align: center; margin: 0; padding: 0;"><button class="btn btn-primary btn-lg modRecButton" type="submit" id="submitRecipe">Submit Changes</button></div>
<div class="col-sm-4 closePanel" style="text-align: center; margin: 0; padding: 0;" id="closePanel"><button type="button" class="btn btn-default btn-lg">Cancel Changes</button>
</div>
<div class="col-sm-2"></div>
</div>
</div>
</form>
</div>
</div>
</div>
AJAX CODE
$(document).ready(function(e) {
$("#editRecipeForm").on('submit', (function(e) {
e.preventDefault();
$.ajax({
url: "../PHP/modify_recipe.php",
type: "POST",
data: new FormData(this),
cache: false,
contentType: false,
processData: false,
success: function(response) {
let parsedResponse = JSON.parse(response);
let newObject = parsedResponse[0]
if (parsedResponse == 'notModified') {
showErrorModal();
}else{
reBuildAfterObjectChange(newObject.recipeId, parsedResponse);
}
},
error: function() {
showErrorModal();
}
});
}));
});
PHP CODE
<?php
include 'db_operations.php';
if(isset($_POST['name'])&& isset($_POST['description']) && isset($_POST['ingredients'])&& isset($_POST['directions']) && isset($_POST['suggestedPairing']) && isset($_POST['prepTime']) && isset($_POST['servings']) && isset($_POST['calories']) && isset($_POST['vegOrVegan']) && isset($_POST['recipeId']) && isset($_POST['creatorId']))
{
$result = '';
$name = $_POST['name'];
$description = $_POST['description'];
$ingredients = $_POST['ingredients'];
$ingredients = str_replace(';', '-', $ingredients);
$ingredients = str_replace('\n', ';', $ingredients);
$directions = $_POST['directions'];
$directions = str_replace(';', '-', $directions);
$directions = str_replace('\n', ';', $directions);
$suggestedPairing = $_POST['suggestedPairing'];
$prepTime = $_POST['prepTime'];
$servings = $_POST['servings'];
$calories = $_POST['calories'];
$vegOrVegan = $_POST['vegOrVegan'];
$recipeId = $_POST['recipeId'];
$creatorId = $_POST['creatorId'];
$tags = $_POST['tags'];
$time=time();
$lastModified = (date("Y-m-d H:i:s", $time));
modifyRecipe_recipes($name, $description, $ingredients, $directions, $suggestedPairing, $prepTime, $servings, $calories, $vegOrVegan, $lastModified, $creatorId, $recipeId, $tags);
}
if(isset($_POST['recipeImage'])){
$size = $_FILES['recipeImage']['size'];
if($size > 0){
$tmp_dir = $_FILES["recipeImage"]["tmp_name"];
$tmpImg = $_FILES['recipeImage']['name'];
$ext = strtolower(pathinfo($tmpImg, PATHINFO_EXTENSION));
$recipeImage = rand(10000, 10000000).".".$ext;
move_uploaded_file($tmp_dir, "../userRecipeImages/".$recipeImage);
$sql = 'UPDATE recipes SET recipeImage = :recipeImage WHERE creatorId = :creatorId AND recipeId= :recipeId';
$stmt = $conn->prepare($sql);
$stmt->bindParam(':creatorId', $creatorId, PDO::PARAM_STR);
$stmt->bindParam(':recipeImage', $recipeImage, PDO::PARAM_STR);
$stmt->bindParam(':recipeId', $recipeId, PDO::PARAM_STR);
$stmt->execute();
}
}
$modifiedRecipeDate = getLastModified_recipes($lastModified, $creatorId);
if ($modifiedRecipeDate === $lastModified) {
$newObject = getSingleRecipeById_recipes($recipeId, $creatorId);
echo json_encode($newObject);
}
else {
$result = "notModified";
echo json_encode($result);
}
?>
You obviously forgot to change $_POST['recipeImage'] to $_FILES['recipeImage']
Files are contained in the $_FILES global variable not $_POST
Change this
if(isset($_POST['recipeImage'])){
to
if(isset($_FILES['recipeImage'])){

error after reload div using jquery load

I have a div with id content
here is my script
<script>
$(document).ready(function(){
$("#avt").fileinput();
$('#updateuser').on('submit', function (e) {
e.preventDefault();
if($('#pwd').val() == $('#repwd').val()){
var formData = new FormData($(this)[0]);
$.ajax({
type: 'post',
url: 'user/edit',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (data) {
$("#content").load(location.href + " #content");
}
});
}else{
$('#errordisplay').html(' <div class="alert alert-danger alert-dismissible"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> <h4><i class="icon fa fa-ban"></i> Alert!</h4> Nhập lại password không đúng!Xin nhập lại!</div>');
}
});
});
</script>
enter image description here
at the first click update,data updated but I look like the javascript not working anymore and css error.
here is image when page normal
enter image description here
here is content div
<div class="body-content outer-top-xs" id="content">
<div class="container">
<div class="row">
<div class="col-md-5">
<div class="box wow fadeInUp outer-bottom-xs animated" style="visibility: visible; animation-name: fadeInUp;">
<h3 class="section-title">Thông Tin Người Dùng</h3>
<div class="box-body outer-top-xs">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<img src="<?= upload_url() ?>/avt/<?= $info['avatar'] ?>" class="img-responsive img-circle" ></div>
</div>
<div class="row">
<hr>
<span class="text-bold">Họ và Tên : </span><span class="text-muted"><?= $info['fullname'] ?> ( <?= $info['username'] ?>)</span>
<hr>
<span class="text-bold">Ngày Đăng Kí : </span><span class="text-muted"><?= $info['date_register'] ?></span>
<hr>
</div>
</div>
<!-- /.sidebar-widget-body -->
</div></div>
<div class="col-md-7">
<div class="box wow fadeInUp outer-bottom-xs animated" style="visibility: visible; animation-name: fadeInUp;">
<h3 class="section-title">Cập Nhật Thông Tin</h3>
<div class="box-body outer-top-xs">
<form class="form-horizontal" id="updateuser">
<div class="box-body">
<div class="form-group">
<label for="avt" class="col-sm-2 control-label">Avatar</label>
<div class="col-sm-10">
<input name="img" class="file" type="file" >
</div>
</div>
<div class="form-group">
<label for="username" class="col-sm-2 control-label">Username</label>
<div class="col-sm-4">
<input class="form-control" id="username" name="username" placeholder="Username" type="text" readonly="readonly" value="<?= $info['username'] ?>">
<input id="uid" name="uid" type="hidden" readonly="readonly" value="<?= $info['userid'] ?>">
</div>
<label for="fullname" class="col-sm-2 control-label">Họ Tên </label>
<div class="col-sm-4">
<input class="form-control" id="fullname" name="fullname" placeholder="Fullname" type="text" value="<?= $info['fullname'] ?>">
</div>
</div>
<div class="form-group">
<label for="pwd" class="col-sm-2 control-label">New Pwd</label>
<div class="col-sm-4">
<input class="form-control" id="pwd" name="pwd" placeholder="Password" type="password" >
</div>
<label for="repwd" class="col-sm-2 control-label">Reinput</label>
<div class="col-sm-4">
<input class="form-control" id="repwd" name="repwd" placeholder=" Retype Password" type="password">
</div>
</div>
<div class="form-group">
<label for="email" class="col-sm-2 control-label">Email *</label>
<div class="col-sm-4">
<input class="form-control" required id="email" name="email" placeholder="Email" type="email" value="<?= $info['email'] ?>">
</div>
<label for="addr" class="col-sm-2 control-label">Địa Chỉ</label>
<div class="col-sm-4">
<input class="form-control" id="addr" name="addr" placeholder="Địa Chỉ" type="text" value="<?= $info['address'] ?>">
</div>
</div>
<div class="form-group">
<label for="gender" class="col-sm-2 control-label">Giới Tính</label>
<div class="col-sm-10">
<label class="col-sm-3 radio-inline"><input type="radio" name="gender" value="0" <?php if($info['gender'] ==0) echo 'checked' ?> >Nam</label>
<label class="col-sm-3 radio-inline"><input type="radio" name="gender" value="1" <?php if($info['gender'] ==1) echo 'checked' ?>>Nữ</label>
<label class="col-sm-3 radio-inline"><input type="radio" name="gender" value="2" <?php if($info['gender'] ==2) echo 'checked' ?>>Khác</label>
</div>
</div>
<div class="form-group">
<label for="phone" class="col-sm-2 control-label">SĐT</label>
<div class="col-sm-4">
<input class="form-control" id="phone" name="phone" placeholder="Số Điện Thoại" type="text" value="<?= $info['phone'] ?>">
</div>
<label for="group" class="col-sm-2 control-label">Group</label>
<div class="col-sm-4">
<select class="form-control" id="group" name="group">
<?php foreach($listgroup as $item): ?>
<option value="<?= $item['groupid'] ?>" <?php if($info['groupid'] ==$item['groupid']) echo 'selected' ?>><?= $item['name'] ?></option>
<?php endforeach ?>
</select>
</div>
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" class="btn bg-tit pull-right">Update</button>
</div>
<!-- /.box-footer -->
</form>
</div>
<!-- /.sidebar-widget-body -->
</div></div>
</div>
<!-- /.row -->
</div>
<!-- /.container -->
</div>
$("#content").load(location.href + " #content");
should be
$("#content").load(location.href + " #content > *");

Simplify angular controller posting to Firebase using AngularFire

I'm new to angular but picking it up quickly. I have this controller that works, based on demo code ive hacked together, but there has to be an easier cleaner way to get all the fields and post so if i want to add a new field i dont need to keep adding it in the various locations.
Heres the controller:
'use strict';
angular.module('goskirmishApp').controller('addEvent', function ($scope, fbutil, $timeout) {
// synchronize a read-only, synchronized array of messages, limit to most recent 10
$scope.messages = fbutil.syncArray('messages', {limit: 10});
// display any errors
$scope.messages.$loaded().catch(alert);
// provide a method for adding a message
$scope.addMessage = function(newEventName,newEventType,newStartDate,newStartTime,newEndDate,newEndTime,newEventDescription,newAddress,newPostcode,newTicketInformation,newBookLink) {
if( newEventName ) {
// push a message to the end of the array
$scope.messages.$add({
eventName: newEventName,
eventType: newEventType,
startDate: newStartDate,
startTime: newStartTime,
endDate: newEndDate,
endTime: newEndTime,
eventDescription: newEventDescription,
address: newAddress,
postcode: newPostcode,
ticketInformation: newTicketInformation,
bookLink: newBookLink
})
// display any errors
.catch(alert);
}
};
function alert(msg) {
$scope.err = msg;
$timeout(function() {
$scope.err = null;
}, 5000);
}
});
And the view:
<h2>Add Event</h2>
<p class="alert alert-danger" ng-show="err">{{err}}</p>
<form role="form">
<div class="form-group">
<label>Event Name</label>
<input class="form-control" type="text" ng-model="newEventName">
</div>
<div class="form-group">
<label>Event Type</label>
<select class="form-control" ng-model="newEventType">
<option value="" disabled selected>Game type</option>
<option value="milsim">Skirmish</option>
<option value="milsim">Special Event</option>
<option value="milsim">Weekender</option>
<option value="milsim">Milsim</option>
</select>
</div>
<div class="form-group">
<label>Start Date & Time</label>
<div class="row">
<div class="col-sm-6">
<input class="form-control" type="date" placeholder="Date" ng-model="newStartDate"/>
</div>
<div class="col-sm-6">
<input class="form-control" type="time" placeholder="Time" ng-model="newStartTime"/>
</div>
</div>
</div>
<div class="form-group">
<label>End Date & Time</label>
<div class="row">
<div class="col-sm-6">
<input class="form-control" type="date" placeholder="Date" ng-model="newEndDate"/>
</div>
<div class="col-sm-6">
<input class="form-control" type="time" placeholder="Time" ng-model="newEndTime"/>
</div>
</div>
</div>
<div class="form-group">
<label>Event Description</label>
<textarea class="form-control" rows="4" ng-model="newEventDescription"></textarea>
</div>
<div class="form-group">
<label>Address</label>
<input class="form-control" ng-model="newAddress">
</div>
<div class="form-group">
<label>Postcode</label>
<input class="form-control" ng-model="newPostcode">
</div>
<div class="form-group">
<label>Ticket Information</label>
<textarea class="form-control" rows="4" ng-model="newTicketInformation"></textarea>
</div>
<div class="form-group">
<label>Booking Link</label>
<input class="form-control" ng-model="newBookLink">
</div>
<button type="submit" class="btn btn-danger" ng-click="addMessage(newEventName,newEventType,newStartDate,newStartTime,newEndDate,newEndTime,newEventDescription,newAddress,newPostcode,newTicketInformation,newBookLink,newLat,newLong,newApproved);newEventName = null;newEventType = null;newStartDate = null;newStartTime = null;newEndDate = null;newEndTime = null;newEventDescription = null;newAddress = null;newPostcode = null;newTicketInformation = null;newBookLink = null;">Add Event</button>
</form>
Help is greatly appreciated!
Define all your input in a object that you will be directly send send to firebase
For example init in your controller this :
$scope.form = {};
After in your template just define your input as 'form attributes'.
<h2>Add Event</h2>
<p class="alert alert-danger" ng-show="err">{{err}}</p>
<form role="form">
<div class="form-group">
<label>Event Name</label>
<input class="form-control" type="text" ng-model="form.eventName">
</div>
<div class="form-group">
<label>Event Type</label>
<select class="form-control" ng-model="form.eventType">
<option value="" disabled selected>Game type</option>
<option value="milsim">Skirmish</option>
<option value="milsim">Special Event</option>
<option value="milsim">Weekender</option>
<option value="milsim">Milsim</option>
</select>
</div>
<div class="form-group">
<label>Start Date & Time</label>
<div class="row">
<div class="col-sm-6">
<input class="form-control" type="date" placeholder="Date" ng-model="form.startDate"/>
</div>
<div class="col-sm-6">
<input class="form-control" type="time" placeholder="Time" ng-model="form.startTime"/>
</div>
</div>
</div>
<div class="form-group">
<label>End Date & Time</label>
<div class="row">
<div class="col-sm-6">
<input class="form-control" type="date" placeholder="Date" ng-model="form.endDate"/>
</div>
<div class="col-sm-6">
<input class="form-control" type="time" placeholder="Time" ng-model="form.endTime"/>
</div>
</div>
</div>
<div class="form-group">
<label>Event Description</label>
<textarea class="form-control" rows="4" ng-model="form.eventDescription"></textarea>
</div>
<div class="form-group">
<label>Address</label>
<input class="form-control" ng-model="form.address">
</div>
<div class="form-group">
<label>Postcode</label>
<input class="form-control" ng-model="form.postcode">
</div>
<div class="form-group">
<label>Ticket Information</label>
<textarea class="form-control" rows="4" ng-model="form.ticketInformation"></textarea>
</div>
<div class="form-group">
<label>Booking Link</label>
<input class="form-control" ng-model="form.bookLink">
</div>
<button type="submit" class="btn btn-danger" ng-click="addMessage()">Add Event</button>
</form>
and directly in your addMessage function
$scope.addMessage = function() {
if( $scope.form.eventName ) {
// push a message to the end of the array
$scope.messages.$add($scope.form)
// display any errors
.catch(alert);
//Reset your form
$scope.form = {};
}
};

Categories

Resources