I have a form where I want to upload images, I have read about it and I am trying withHTML5 + AJAX + JQUERY + PHP
So I have the following code belongs to a MODAL where I am going to capture the form data:
FORM
<form id="myForm" enctype="multipart/form-data" method="post">
<!-- Modal body -->
<br>
<img src="../img/img-services/img-service-2.jpg" class="rounded mx-auto d-block" alt="Cinque Terre" width="100" height="100">
<br>
<div class="upload-btn-wrapper">
<button class="upload-btn">Upload a file</button>
<input type="file" name="img_url" id="img_url" />
</div>
<div class="modal-body">
<input type="text" id="id" name="id" value="" hidden required="">
<label>Service Name</label>
<input type="text" id="name" name="name" value="" onkeypress="return soloLetras(event)" onblur="limpia()" class="form-control validate" required="" placeholder="Enter Service Name">
<p id="errorName" style="color:red; display: none;"></p>
<label>Service Type</label>
<select class="form-control" id="id_tipo_servicio" name="id_tipo_servicio">
<option value="0">Select option...</option>
<?php
while ($valores = mysqli_fetch_array($result)) {
echo '<option value="'.$valores[id_tipo_servicio].'">'.$valores[ts_nombre].'</option>';
}
?>
</select>
<p id="errorSelect" style="color:red; display: none;"></p>
<label>Description</label>
<textarea id="desc" name="desc" class="form-control validate" required="" placeholder="Enter Service Description"></textarea>
<p id="errorDesc" style="color:red; display: none;"></p>
<label>Cost</label>
<input type="number" id="cost" name="cost" value="" class="form-control validate" required="" placeholder="Enter Cost">
<p id="errorCost" style="color:red; display: none;"></p>
<div class="spinner-grow text-primary" style="display: none;" role="status" id="showLoad">
<span class="sr-only">Loading...</span>
</div>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="button" class="btn btn-success" id="saveButton" onclick="doAction()" style="display: none"><span id="load" class="spinner-border spinner-border-sm" role="status" style="display: none" aria-hidden="true"></span> Save</button>
<button type="button" class="btn btn-warning" id="edithButton" style="color:white;" onclick="doAction()" >Edith</button>
<button type="button" class="btn btn-danger" data-dismiss="modal" >Cancel</button>
</div>
Here is the JS file, where by JQUERY I obtain the data that the user leaves me, I assign them to their variables, valid, I make a formData and I send it in AJAX:
function doAction(){
var id_servicio = $('#id')[0].value;
var id_tipo_servicio = $('#id_tipo_servicio')[0].value;
var name = $('#name')[0].value;
var desc = $('#desc')[0].value;
var cost = $('#cost')[0].value;
var img_url = $('#img_url').prop('files')[0];
//insert
console.log("INSERT - nombre: " + name + "desc: " + desc + "precio: " + cost + "id_tipo_servicio " + id_tipo_servicio);
if(name === ""){
$( "#name" ).focus();
//document.getElementById("errorName").innerHTML = "Service Name is Required";
$("#errorName").show();
$("#errorName").html("Service Name is Required");
}else if(id_tipo_servicio === "" || id_tipo_servicio === "0"){
$( "#id_tipo_servicio" ).focus();
//document.getElementById("errorName").innerHTML = "Service Name is Required";
$("#errorName").hide();
$("#errorSelect").show();
$("#errorSelect").html("Service Type is Required");
}else if(desc === "" || desc === "0"){
$( "#desc" ).focus();
$("#errorSelect").hide();
$("#errorDesc").show();
//document.getElementById("errorDesc").innerHTML = "Service Description is Required";
$("#errorDesc").html("Service Name is Required");
}else if(cost === "" || cost === "0"){
$( "#cost" ).focus();
$("#errorDesc").hide();
$("#errorCost").show();
//document.getElementById("errorCost").innerHTML = "Service Cost is Required";
$("#errorCost").html("Service Cost is Required");
}else{
var formData = new FormData();
formData.append('name',name);
formData.append('id_tipo_servicio',id_tipo_servicio);
formData.append('desc',desc);
formData.append('cost',cost);
formData.append('archivo',img_url);
formData.append('function',"addService");
$.ajax({
data: formData, //send data via AJAX
url: '../controller/serviceController.php', //url file controller PHP
dataType: 'text', // what to expect back from the server
cache: false,
contentType: false,
processData: false,
type: 'post', //send POST data
beforeSend: function () {
document.getElementById("load").style.display = "block";
},
success: function (response) { //get request
if(response.success){
$("#successModalTitle").html("<i class='fas fa-check-circle color-success'></i> ¡Success!");
}else{
$("#successModalTitle").html("<i class='fas fa-exclamation-circle color-error'></i> ¡Error!");
}
$("#successModalDescription").html(response.message);
//alert(response.message);
$('#actionModal').modal('toggle');
$('#services').DataTable().ajax.reload();
$('.close').click();
}
});
}
}
And on this side is the PHP, where I receive the AJAX loaded with the DataForm, assign a value to their respective variables, connect to the database, build the INSERT and execute it ../controller/serviceController.php :
if(isset($_POST['function']) && !empty($_POST['function'])) {
$function = $_POST['function'];
//En función del parámetro que nos llegue ejecutamos una función u otra
switch($function) {
case 'addService':
# code...
$name = $_POST['name'];
$cost = $_POST['cost'];
$desc = $_POST['desc'];
$id_tipo_servicio = $_POST['id_tipo_servicio'];
$date = date("Y-m-d");
$iva = 0;
$status = 1;
$nombre = $_FILES['archivo']['name'];
$ruta = $_FILES['archivo']['tmp_name'];
$destino = ".../img/" . $nombre;
require_once 'conn/connection.php';
$connect = new connection();
$connection=$connect->connections();
$sql = "INSERT INTO servicios (id_tipo_servicio, ser_nombre, ser_descripcion, ser_img_url, ser_precio, ser_fecha_creacion, ser_fecha_actualizacion, ser_iva, ser_status) VALUES ('".$id_tipo_servicio ."','".$name."','".$desc."','".$destino."','".$cost."','".$date ."', '".$date."', '".$iva."', '".$status."');";
$jsondata = array();
if ($connection->query($sql)===true) {
$jsondata['success'] = true;
$jsondata['message'] = 'Felicidades! Has insertado el Servicio con Éxito.';
} else {
$jsondata['success'] = false;
$jsondata['message'] = 'Error! Ha ocurrido un error, avisa a un administrador.';
}
//Aunque el content-type no sea un problema en la mayoría de casos, es recomendable especificarlo
header('Content-type: application/json; charset=utf-8');
echo json_encode($jsondata, JSON_FORCE_OBJECT);
break;
}
}
What does the code do?
The code collects the data from the HTML, it goes to the JS loaded with data, I build a DataForm, I fill it out and this goes to AJAX, it sends it and now in PHP is where there is an error and it's weird because, IF IT INSERTS, BUT IT DOES NOT RETURN ME A SUCCESS MESSAGE, the PHP returns a false and returns an ERROR. I insist, but if INSERT.
I really don't know why it doesn't return TRUE if it doesn't have problems when INSERT , now I haven't been able to save the file to the server either.
so insert
And this is the ERROR that my dashboard shows and this is the strange thing because it is HOW ELSE IT WILL ENTER THE IF
When you send the data you are not doing anything with the file, you have to move it to the folder that you define as uploads and of course with sufficient write permissions.
with this code you verify that the route exists and creates it if it does not exist
So according to your comment you should only invert the if
example:
You are missing the
method
:in the ajax options.