I have the below code which is inheriting from models for modelform, but failing to pass the condition for valid.
Model.py
class contact(models.Model):
fname = models.CharField(max_length=100)
lname = models.CharField(max_length=100)
email = models.EmailField()
phone = models.IntegerField()
message = models.CharField(max_length=100)
def __str__(self):
return self.fname
urls.py
urlpatterns = [
url(r'^$', 'asp.views.index', name='root'),
url(r'^contact/', 'asp.views.contact', name='contact'),
url(r'^new$', 'asp.views.new_user', name='new'),
url(r'^admin/', include(admin.site.urls)),
]
where asp is my application
def contact(request):
return render(request, "contact.html", {})
def new_user(request):
print( '$' * 100)
if request.method == 'POST':
form = contactform(request.POST or None)
print( '*' * 10)
if form.is_valid():
print( '!' * 10)
else:
form = contactform()
return render(request, "index.html", {'form':form})
For which $,* was printing, but not passing the condition for valid.
forms.py
class contactform(forms.ModelForm):
class Meta:
model = contact
exclude = ()
Below is my html page
<form class="form-horizontal" action="/new" method="post">{% csrf_token %}
{{ form }}
<fieldset>
<legend class="text-center header">Contact us</legend>
<div class="form-group">
<div class="col-md-10 col-md-offset-1">
<input id="fname" name="name" type="text" placeholder="First Name" class="form-control">
</div>
</div>
<div class="form-group">
<div class="col-md-10 col-md-offset-1">
<input id="lname" name="name" type="text" placeholder="Last Name" class="form-control">
</div>
</div>
<div class="form-group">
<div class="col-md-10 col-md-offset-1">
<input id="email" name="email" type="text" placeholder="Email Address" class="form-control">
</div>
</div>
<div class="form-group">
<div class="col-md-10 col-md-offset-1">
<input id="phone" name="phone" type="text" placeholder="Phone" class="form-control">
</div>
</div>
<div class="form-group">
<div class="col-md-10 col-md-offset-1">
<textarea class="form-control" id="message" name="message" placeholder="Enter your massage for us here. We will get back to you within 2 business days." rows="7"></textarea>
</div>
</div>
</fieldset>
</form>
Thanks in advance.
Related
i have a problem when updating the database
error: Method Illuminate\Database\Eloquent\Collection::save does not exist.
controller:
public function actualizar(Request $request){
$nuevoIngreso = \App\Models\Servicio::all();
$nuevoIngreso->costo = $request->costo;
$nuevoIngreso->duracion = $request->duracion;
$nuevoIngreso->mantenimiento = $request->mantenimiento;
$nuevoIngreso->save();
return redirect('servicios')->with('mensaje', 'Ficha Actualizada.');
}
blade.php
<form method="POST" action="{{ route('actualizar') }}">
{{method_field('PUT')}}
#csrf
#foreach ($servicios as $costo)
<h1 class="text-center text-primary"> {{$costo->tipo}} </h1>
<div class="form-group row">
<label for="example-text-input" class="col-md-2 col-form-label form-control-label">Costo</label>
<div class="col-md-10">
<input class="form-control" type="text" value="{{$costo->costo}}">
</div>
<label for="example-text-input" class="col-md-2 col-form-label form-control-label">Duración</label>
<div class="col-md-10">
<input class="form-control" type="text" value="{{$costo->duracion}}" id="example-text-input">
</div>
<label for="example-text-input" class="col-md-2 col-form-label form-control-label">Mantenimiento</label>
<div class="col-md-10">
<input class="form-control" type="text" value="{{$costo->mantenimiento}}" id="example-text-input">
</div>
</div>
<hr>
#endforeach
<button type="submit" class="btn btn-success float-right" float-rightdata-toggle="sweet-alert" data-sweet-alert="success">SAVE</button>
</form>
help please
Error is clear.you are calling static method all().So it should be
$nuevoIngreso =new \App\Models\Servicio();
$nuevoIngreso->costo = $request->costo;
$nuevoIngreso->duracion = $request->duracion;
$nuevoIngreso->mantenimiento = $request->mantenimiento;
$nuevoIngreso->save();
So if you are thinking to update particular record then find by id or any column
$nuevoIngreso =new \App\Models\Servicio::find($id);
$nuevoIngreso->costo = $request->costo;
$nuevoIngreso->duracion = $request->duracion;
$nuevoIngreso->mantenimiento = $request->mantenimiento;
$nuevoIngreso->save();
Updated
<form method="POST" action="{{ route('actualizar') }}">
{{method_field('PUT')}}
#csrf
#foreach ($servicios as $key=>$costo)
<h1 class="text-center text-primary"> {{$costo->tipo}} </h1>
<input class="form-control" type="hidden" value="{{$costo->id}}" name="service[{{$key}}][id]">
<div class="form-group row">
<label for="example-text-input" class="col-md-2 col-form-label form-control-label">Costo</label>
<div class="col-md-10">
<input class="form-control" type="text" value="{{$costo->costo}}" name="service[{{$key}}][costo]">
</div>
<label for="example-text-input" class="col-md-2 col-form-label form-control-label">Duración</label>
<div class="col-md-10">
<input class="form-control" type="text" value="{{$costo->duracion}}" id="example-text-input" name="service[{{$key}}][duracion]">
</div>
<label for="example-text-input" class="col-md-2 col-form-label form-control-label">Mantenimiento</label>
<div class="col-md-10">
<input class="form-control" type="text" value="{{$costo->mantenimiento}}" id="example-text-input" name="service[{{$key}}][mantenimiento]">
</div>
</div>
<hr>
#endforeach
<button type="submit" class="btn btn-success float-right" float-rightdata-toggle="sweet-alert" data-sweet-alert="success">SAVE</button>
</form>
Then in controller
foreach($request->service as $key=>$value){
$nuevoIngreso =new \App\Models\Servicio::find($value['id']);
if($nuevoIngreso){
$nuevoIngreso->costo = $value['costo'];
$nuevoIngreso->duracion = $value['duracion'];
$nuevoIngreso->mantenimiento = $value['mantenimiento'];
$nuevoIngreso->save();
}
}
This is my blade file for the update form. So how I should I retrieve those data in the form by checked the checkbox.
<div class="form-group row">
<label class="col-md-3 col-form-label form-control-label" for="input-description">Hobbies</label>
<div class="col-md-9">
<input type="checkbox" name="hobbies[]" class="form-control-label" value="football" > Football
<input type="checkbox" name="hobbies[]" class="form-control-label" value="basketball"> Basketball
<input type="checkbox" name="hobbies[]" class="form-control-label" value="table_tennis"> Table Tennis
<input type="checkbox" name="hobbies[]" class="form-control-label" value="hockey"> Hockey
<input type="checkbox" name="hobbies[]" class="form-control-label" value="others"> Others
</div>
</div>
</div>
This is my Controller
public function edit($id)
{
$student=Student::find($id);
return view('students.edit', compact('student'));
}
In the database, .hobbies are stored in hobbies column like this
["basketball","football",'table_tennis']
You should use foreach loop inside blade that will be more maintainable:
<div class="form-group row">
<label class="col-md-3 col-form-label form-control-label" for="input-description">Hobbies</label>
<div class="col-md-9">
#foreach($hobbies as $hobby)
<input type="checkbox" name="hobbies[]" #if(in_array($hobby,$checked_hobbies)) checked #endif class="form-control-label" value="{{ $hobby }}" > {{ $hobby }}
#endforeach
</div>
</div>
and of course you should pass hobbies and checked_hobbies array in controller:
$hobbies = ["basketball","football",'table_tennis'];
$checked_hobbies = ["basketball","football"];
return view('test', compact('hobbies','checked_hobbies'));
View: modAnimal.html (this is the first part of the view, after it there are input values in hidden div)
<form th:action="#{/animales/preModAnimal}" th:object="${animal}" method="post" enctype="multipart/form-data" id="formPreModAnimal">
<!-- INPUT TIPO DE ANIMAL -->
<label>Animal</label>
<input type="radio" th:field="*{tipo}" th:value="*{tipo.PERRO}" required />
<label>🐕</label>
<input type="radio" th:field="*{tipo}" th:value="*{tipo.GATO}" required />
<label>🐈</label>
<!-- INPUT SEXO DEL ANIMAL -->
<label>Sexo</label>
<input type="radio" th:field="*{sexo}" th:value="*{sexo.MACHO}" required />
<label>♂️</label>
<input type="radio" th:field="*{sexo}" th:value="*{sexo.HEMBRA}" required />
<label>♀️</label>
<!-- INPUT SELECT ANIMAL -->
<label for="selectAnimal">Animal</label>
<select th:fragment="animales" id="selectAnimal" required
class="form-control">
<option value="" selected="selected">Selecciona animal</option>
<option th:each="i : ${animales}"
th:text="${i.emojiTipo} + ' ' + ${i.emojiSexo} + ' - ' + ${i.nombre} + ' - ' + ${i.raza} + ' - ' + ${i.provincia.provincia} + ' (' + ${i.poblacion} + ')'"
th:value="${i.id}"></option>
</select>
</form>
Depending on the selected radios, the select drop-down will be loaded with the desired values.
This is done with jQuery
funcionesCheck_jQuery.js
$(document).ready(function() {
$('[name=tipo], [name=sexo]').change(function() {
$("#selectAnimal").load('/animales/checktiposexo', $('#formPreModAnimal :input[type=radio]').serialize());
});
});
And this is the controller
AnimalesController.java
#GetMapping("/modAnimal") public String pagMod(Model model) {
Animal animal = new Animal();
model.addAttribute("animal", animal);
Sexo[] opcionesSexo = Sexo.values();
model.addAttribute("sexos", opcionesSexo);
Tipo[] opcionesTipo = Tipo.values();
model.addAttribute("tipos", opcionesTipo);
return "animales/modAnimal";
}
#GetMapping("/checktiposexo")
public String filtroTipoSexo(Model model, #RequestParam(name = "tipo", required = false) Tipo tipo,
#RequestParam(name = "sexo", required = false) Sexo sexo) {
List<Animal> listaAnimales;
if (tipo == null && sexo == null) { // not working, i wanted this to act different, but nvm
listaAnimales = animalesRepo.findAll();
model.addAttribute("animales", listaAnimales);
} else if (tipo != null && sexo == null) {
listaAnimales = animalesRepo.findAllAnimalesByTipoOrSexo(tipo, sexo);
model.addAttribute("animales", listaAnimales);
} else if (tipo == null && sexo != null) {
listaAnimales = animalesRepo.findAllAnimalesByTipoOrSexo(tipo, sexo);
model.addAttribute("animales", listaAnimales);
} else {
listaAnimales = animalesRepo.findAllAnimalesByTipoAndSexo(tipo, sexo);
model.addAttribute("animales", listaAnimales);
}
return "animales/modAnimal :: animales"; //I'm returning animales as fragment
}
Then I want to fill some input values with the values given in the selected option in the same view mentioned at begin of the post.
Everytime the selected option changes, these inputs will re-show again. They're in a div (#modificarOculto) initially hidden at begin.
funcionesCheck_jQuery.js
$(document).ready(function() {
$( "#modificarOculto" ).hide();
$("[name=tipo], [name=sexo], #selectAnimal").change(function() {
$('#modificarOculto').hide('300');
$("#selectAnimal").change(function() {
inputSelectAnimal = $("#selectAnimal")[0];
selectAnimal = $("#selectAnimal").val();
if(selectAnimal>0){
$('#modificarOculto').show('slow');
}else if(selectAnimal==0){
$('#modificarOculto').hide('slow');
}
});
});
});
Remember, this is the part of the view below the view at begin. I want to load the selected values in these inputs.
modAnimal.html (again)
<div class="row cajita" id="modificarOculto">
<form th:action="#{/animales/modAnimal-submit}" id="formModAnimal"
th:object="${animal}" method="post" enctype="multipart/form-data">
<label >Nombre</label>
<input type="text" th:field="*{nombre}" class="form-control"
placeholder="Nombre del animal" required minlength=3
maxlength=50 />
<label>Animal</label>
<input type="radio" th:field="*{tipo}" th:value="*{tipo.PERRO}"required />
<label>🐕</label>
<input type="radio" th:field="*{tipo}" th:value="*{tipo.GATO}" required />
<label>🐈</label>
<label>Sexo</label>
<input type="radio" th:field="*{sexo}" th:value="*{sexo.MACHO}" required />
<label>♂️</label>
<input type="radio" th:field="*{sexo}" th:value="*{sexo.HEMBRA}" required />
<label>♀️</label>
<!-- INPUT PROVINCIA ANIMAL -->
<label>Provincia</label>
<select id="provincia" name="provincia" required>
<option value="">Load the selected provincia</option>
<option th:each="i : ${provincias}" th:text="${i.provincia}"
th:value="${i.id}">
</select>
<button type="submit" id="botonModificar">Modificar</button>
</form>
</div>
I know I need a form to submit the new values ("formModAnimal"), but... I know I don't need the form of begin ("formPreModAnimal"). What I don't really know if I would need to englobe the whole view (select part + input part) in a form together.
How could I send the data as object values from the selected value to input values? Is there any smart way to do it with Thymeleaf?
May I be able to associate the selected value to a fragment and send it to the form "formModAnimal" and use it as animal.attribute? That would be very comfortable.
How would you do this?
I've deleted all the bootstrap divs and classes for your overview comfort. I hope everything is clear for you!
Thanks in advance!
Okay, I've resolved it.
This is my new jQuery function in funcionesCheck_jQuery.js, where I load in div $('#modificarOculto') the serialized results of the selected drop-down $("#selectAnimal").
(I don't know why can't I just take the id of the drop-down, or why #RequestParam("selectAnimal") can't take it from the view directly...)
$(document).ready(function() {
//$("#modificarOculto").hide();
$("[name=tipo], [name=sexo], #selectAnimal").change(function() {
$('#modificarOculto').hide('300');
$("#selectAnimal").change(function() {
inputSelectAnimal = $("#selectAnimal")[0];
selectAnimal = $("#selectAnimal").val();
if (selectAnimal > 0) {
$('#modificarOculto').show('slow');
$('#modificarOculto').load('/animales/animalid', $("#selectAnimal").serialize());
} else if (selectAnimal == 0) {
$('#modificarOculto').hide('slow');
}
});
});
});
This is managed in the controller AnimalController.java: #RequestMapping("/animalid"), which will return a thymeleaf fragment with the selected animal values.
#RequestMapping("/animalid")
public String getAnimalByID(#RequestParam(name = "selectAnimal", required = false) int idAnimal, Model model) {
Animal animalModelo = new Animal();
model.addAttribute("animal", animalModelo);
Esterilizado[] opcionesEsterilizado = Esterilizado.values();
model.addAttribute("esterilizados", opcionesEsterilizado);
List<Provincia> listaProvincias = provinciasRepo.findAll();
model.addAttribute("provincias", listaProvincias);
Optional <Animal> animal = animalesRepo.findOneAnimalById(idAnimal);
if (animal.isPresent()) {
model.addAttribute("selectedAnimal", animal.get());
} else {
// ERROR?
}
return "animales/modAnimal :: selectedAnimal";
}
And finally, this is the second part of my View. I insert the Thymeleaf fragment inside the form and I use it as object too. This form is also ready to submit the given data to database (mapped). Now I'm working on updating the data instead inserting.
<div class="row cajita" id="modificarOculto">
<div class="col-md-9 offset-1">
<form th:action="#{/animales/modAnimal-submit}" id="formModAnimal"
th:object="${selectedAnimal}" method="post" enctype="multipart/form-data"
class="was-validated" th:fragment="selectedAnimal">
<th:block th:if="${selectedAnimal != null}">
<!-- INPUT NOMBRE ANIMAL -->
<div class="form-group row">
<label class="col-sm-2 col-form-label" for="nombre">Nombre</label>
<div class="col-sm-10">
<input type="text" th:name="nombre" th:value="${selectedAnimal.getNombre()}" class="form-control"
placeholder="Nombre del animal" required minlength=3
maxlength=50 />
</div>
</div>
<div class="form-group row">
<!-- INPUT TIPO DE ANIMAL -->
<label class="col-sm-2 col-form-label">Animal</label>
<div class="col-sm-1">
<div class="form-check">
<input type="radio" th:name="tipo" th:value="${selectedAnimal.tipo.PERRO}" th:checked="${selectedAnimal.getTipo()} == ${selectedAnimal.tipo.PERRO}"
class="form-check-input" required > <label class="form-check-label">🐕</label>
</div>
<div class="form-check">
<input type="radio" th:name="tipo" th:value="${selectedAnimal.tipo.GATO}" th:checked="${selectedAnimal.getTipo()} == ${selectedAnimal.tipo.GATO}"
class="form-check-input" required > <label class="form-check-label">🐈</label>
</div>
</div>
<!-- INPUT SEXO DEL ANIMAL -->
<label class="col-sm-1 col-form-label">Sexo</label>
<div class="col-sm-1">
<div class="form-check">
<input type="radio" th:name="sexo" th:value="${selectedAnimal.sexo.MACHO}" th:checked="${selectedAnimal.getSexo()} == ${selectedAnimal.sexo.MACHO}"
class="form-check-input" required > <label class="form-check-label">♂️</label>
</div>
<div class="form-check">
<input type="radio" th:name="sexo" th:value="${selectedAnimal.sexo.HEMBRA}" th:checked="${selectedAnimal.getSexo()} == ${selectedAnimal.sexo.HEMBRA}"
class="form-check-input" required > <label class="form-check-label">♀️</label>
</div>
</div>
<!-- INPUT RAZA -->
<label class="col-sm-1 col-form-label" for="nombre">Raza</label>
<div class="col-sm-6">
<input type="text" th:name="raza" th:value="${selectedAnimal.getRaza()}" class="form-control"
placeholder="Raza del animal" required minlength=3 maxlength=100 />
</div>
</div>
<div class="form-group row">
<!-- INPUT FECHA DE NACIMIENTO -->
<label class="col-sm-2 col-form-label" for="fnac">Fecha de
nacimiento</label>
<div class="col-sm-4">
<input type="date" th:name="fnac" th:id="fnac" th:value="${selectedAnimal.getFnac()}" class="form-control"
min="1990-01-01" required />
</div>
<!-- INPUT ESTERILIZADO -->
<label class="col-sm-2 col-form-label">Esterilizado</label>
<div class="col-sm-4">
<th:block th:each="i : ${esterilizados}">
<div class="form-check">
<input type="radio" th:name="esterilizado" th:id="'esterilizado'+${iStat.index+1}" required
th:value="${i}" class="form-check-input" th:checked="${selectedAnimal.getEsterilizado() == i}" > <label
class="form-check-label" th:for="'esterilizado'+${iStat.index+1}"
th:text="${#strings.capitalize(#strings.toLowerCase(i))}">Esterilizado</label>
</div>
</th:block>
</div>
</div>
<div class="form-group row">
<!-- INPUT PROVINCIA ANIMAL -->
<label class="col-sm-2 col-form-label" for="provincia">Provincia</label>
<div class="col-sm-4">
<select id="provincia" th:name="provincia" required
class="form-control">
<option th:each="i : ${provincias}" th:text="${i.provincia}"
th:value="${i.id}"
th:selected="${selectedAnimal.getProvincia().getId() == i.id}">
</select>
<!-- Si fuera un valor enum <td><select th:field="*{provincia}">
<option th:each="i : ${provincias}" th:text="${i.toString()}"
th:value="${i}"></option></select></td>-->
</div>
<!-- INPUT POBLACION ANIMAL -->
<label class="col-sm-2 col-form-label" for="fnac">Población</label>
<div class="col-sm-4">
<input type="text" th:name="poblacion" th:value="${selectedAnimal.getPoblacion()}" class="form-control"
required minlenght=2 maxlength=50 />
</div>
</div>
<!-- INPUT FOTO ANIMAL -->
<div class="form-group row">
<label class="col-sm-2 col-form-label" for="file">Foto</label>
<div class="col-sm-10">
<input type="file" name="file" accept="image/*"
class="form-control-file" id="validatedCustomFile" required />
<div class="invalid-feedback">Ningún archivo seleccionado</div>
</div>
<!-- INPUT FOTO EN LAS SOMBRAS -->
<label for="foto" style="display: none;">Foto</label> <input
type="text" th:name="foto"
th:value="${selectedAnimal.getFoto()}" maxlength=200
style="display: none;" />
</div>
<!-- INPUT DESCRIPCION ANIMAL -->
<div class="form-group row">
<label class="col-sm-2 col-form-label" for="descripcion">Descripción</label>
<div class="col-sm-10">
<textarea class="form-control" required rows="5" cols="50"
th:name="descripcion" minlength=50 maxlength=255
th:text="${selectedAnimal.getDescripcion()}" th:value="${selectedAnimal.getDescripcion()}"
placeholder="Historia, personalidad, enfermedades, comportamiento con otras mascotas"></textarea>
</div>
</div>
<div class="form-group row">
<div class="col-sm-12">
<button type="submit" class="btn btn-success float-right"
id="botonUpdateAnimal">Actualizar</button>
</div>
</div>
<div th:if="${message}" th:text="${message}"
th:class="${'alert ' + alertClass}" ></div>
</th:block>
</form>
</div>
</div>
I want to stop duplicate entry into form field. If I enter the same data which is already stored into database then it shows an error message or it won't stored. Please Help me guys. I am new in Django.
Form.html File
<form class="well form-horizontal" method="post" action="{% url 'manager_add' %}">
{% csrf_token %}
<fieldset>
<div class="form-group">
<label class="col-md-4 control-label">Manager Name</label>
<div class="col-md-6 inputGroupContainer">
<div class="input-group"><span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span><input id="fullName" name="mname" placeholder="Full Name" class="form-control" required="true" value="" type="text"></div>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Select Department</label>
<div class="col-md-6 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon" style="max-width: 100%;"><i class="glyphicon glyphicon-list"></i></span>
<select class="selectpicker form-control" name="dprtmnt">
<option>Department 1</option>
<option>Department 2</option>
<option>Department 3</option>
<option>Department 4</option>
</select>
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Email</label>
<div class="col-md-6 inputGroupContainer">
<div class="input-group"><span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i></span><input id="email" name="email" placeholder="Email" class="form-control" required="true" value="" type="text"></div>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Contact</label>
<div class="col-md-6 inputGroupContainer">
<div class="input-group"><span class="input-group-addon"><i class="glyphicon glyphicon-earphone"></i></span><input id="phoneNumber" name="phone" placeholder="Phone Number" class="form-control" required="true" value="" type="text"></div>
</div>
</div>
<button>Submit</button>
</fieldset>
</form>
Model.py File
class Manager(models.Model):
mname = models.CharField(max_length=20)
dprtmnt = models.CharField(max_length=10)
email = models.CharField(max_length=50)
phone = models.CharField(max_length=20)
def __str__(self):
return self.mname
View.py File
def manager_add(request):
print("Form is submitted successfully!")
mname = request.POST.get("mname", False)
dprtmnt = request.POST.get("dprtmnt", False)
email = request.POST.get("email", False)
phone = request.POST.get("phone", False)
ManagerAdd = Manager(mname = mname, dprtmnt = dprtmnt, email = email, phone = phone, is_active=False)
ManagerAdd.save()
return render(request,'manageradd.html')
You can use Manager.objects.get_or_create(), see this part of the doc.
You can also simple check if an entry already exists in your database:
try:
Manager.objects.get(mname = mname, dprtmnt = dprtmnt, email = email, phone = phone)
# Do things if manager exists
except:
# Create your new manager
Hello and good day everyone, I am having a problem in ajax. I have a variable named fd that contains object. But i cant find a way to put it together with other variable in "data:". I just want to pass the data of fd and also the other variables from other inputs of my form. Thank you very much.
$('#register_btn').click(function(e) {
var fd = new FormData();
var files = $('#image')[0].files[0];
fd.append('image',files);
var val1 = $('#email').val();
var val2 = $('#firstname').val();
var val3 = $('#middlename').val();
var val4 = $('#lastname').val();
var val5 = $('#emp_status').val();
var val6 = $('input[name=date_hired]').val();
var val7 = $('#account_type').val();
var val8 = $('#notes').val();
var val9 = $('#position').val();
var val10 = $('#cp_number').val();
var val11 = $('#tel_number').val();
var val12 = $('#address').val();
$.ajax({
type: 'POST',
url: 'process/add_employee_process.php',
contentType: false,
cache: false,
processData:false,
data: {email: val1, firstname: val2, middlename: val3, lastname: val4, emp_status: val5, date_hired: val6, account_type: val7, notes: val8, position: val9, cp_number: val10, tel_number: val11, address: val12,fd},
success:function(html) {
if(html=="Failed"){
$("#gifcheckmark").attr('src','../campfire.gif');
$("#gifcheckmark").css('display','inline');
$("#gifcheckmark").css('width','inline');
$("#notif_message").text("Failed");
$("#register_btn").css('display','none');
$("#decline_btn").css('display','none');
}
else{
$("#notif_message").text("Success");
$("#gifcheckmark").css('display','inline');
$("#gifcheckmark").css('width','inline');
$("#register_btn").css('display','none');
$("#decline_btn").css('display','none');
setInterval(successGif, 1600);
$('#qr').load('../phpqrcode/index.php');
$('#qr').show();
}
}
});
});
This is the form
<form role="form" style="width: 100%;">
<div class="box-body">
<div class="box-header with-border col-xs-12">
<div class="box-tools pull-right">
<button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button>
<button type="button" class="btn btn-box-tool" data-widget="remove"><i class="fa fa-remove"></i></button>
</div>
</div>
<div class="form-group col-md-3">
<label for="">Email </label>
<input type="email" id="email" class="form-control" id="exampleInputEmail1" placeholder="Email">
</div>
<div class="form-group col-md-3">
<label for="">Firstname </label>
<input type="text" id="firstname" class="form-control" id="" placeholder="Firstname">
</div>
<div class="form-group col-md-3">
<label for="">Middlename </label>
<input type="text" id="middlename" class="form-control" id="" placeholder="Middlename">
</div>
<div class="form-group col-md-3">
<label for="">Lastname </label>
<input type="text" id="lastname" class="form-control" id="" placeholder="Lastname">
</div>
<div class="form-group col-md-3">
<label for="">Employee Status </label>
<input type="text" id="emp_status" class="form-control" id="" placeholder="Employee Status">
</div>
<div class="form-group col-md-3">
<label for="">Date Hired </label>
<div class="input-group date">
<div class="input-group-addon">
<i class="fa fa-calendar"></i>
</div>
<input type="text" name="date_hired" class="form-control pull-right" id="datepicker">
</div>
</div>
<div class="form-group col-md-3">
<label for="">Account Type </label>
<input type="text" id="account_type" class="form-control" id="" placeholder="Account Type">
</div>
<div class="form-group col-md-3">
<label for="">Notes </label>
<input type="text" id="notes" class="form-control" id="" placeholder="Notes">
</div>
<div class="form-group col-md-3">
<label for="">Positions </label>
<input type="text" id="position" class="form-control" id="" placeholder="Positions">
</div>
<div class="form-group col-md-3">
<label for="">Cellphone Number </label>
<input type="text" id="cp_number" class="form-control" id="" placeholder="Cellphone Number">
</div>
<div class="form-group col-md-3">
<label for="">Telephone Number </label>
<input type="text" id="tel_number" class="form-control" id="" placeholder="Telephone Number">
</div>
<div class="form-group col-md-3">
<label for="">Address </label>
<input type="text" id="address" class="form-control" id="" placeholder="Address">
</div>
<div class="form-group col-xs-12">
<input type="hidden" name="size" value="1000000">
<div>
<input type="file" id="image" name="image">
</div>
</div>
<!-- /.box-body -->
<div class="col-xs-2">
<center><button type="button" id="confirm_btn" class="btn btn-primary" data-toggle="modal" data-target="#modal-default">
Submit
</button></center>
</div>
</form>
This is the add_employee_process.php
$db = mysqli_connect('localhost', 'root','','cjwebsolutions');
$image = $_FILES['image']['name'];
$target = "image/".basename($image);
if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
$msg = "Image uploaded successfully";
}else{
$msg = "Failed to upload image";
}
$emp_id = make_emp_id($_POST['date_hired']);
$_POST['emp_id'] = $emp_id;
// Required field names
$required_fields = array('email','firstname','middlename','lastname', 'emp_status', 'date_hired','account_type','notes','position','cp_number','tel_number','address','emp_id');
$data_insert_fields = array('email','firstname','middlename','lastname', 'emp_status', 'date_hired','account_type','notes','position','cp_number','tel_number','address','emp_id');
if (check_empty_fields($required_fields)) {
echo "Failed";
}
else
{
data_insert($data_insert_fields,"cj_accounts");
}