I'm getting this error when I try to update a file on my form..."You did not select a file to upload." ...and the problem is that I really am selecting a new file to upload...help me pls, I don't understand what is happening ...here is my code:
FORM
<form class="col s12" id="update_form" required="" enctype="multipart/form-data" aria-required="true" name="update_form" method="post" >
<div class="row">
<div class="input-field col s6">
<input id="update_name" type="text" required="" aria-required="true" name="name" class="validate">
<label for="first_name">Nombre</label>
</div>
<div class="input-field col s6">
<input id="update_last_name" name="lastname" required="" aria-required="true" type="text" class="validate">
<label for="last_name">Apellido</label>
</div>
</div>
<div class="row">
<div class="input-field col s6">
<input id="update_side" type="text" required="" aria-required="true" name="side" class="validate">
<label for="partido">Partido</label>
</div>
<div class="input-field col s6">
<input id="update_charge" type="text" required="" aria-required="true" name="charge" class="validate">
<label for="cargo">Cargo</label>
</div>
</div>
<div class="row">
<div class="input-field col s6">
<div class="file-field input-field no-margin-top">
<div class="btn light-blue darken-4">
<span>Animación/Imagen</span>
<input type="file" name="animation">
</div>
<div class="file-path-wrapper">
<input class="file-path validate" id="animation" name="animation" type="text">
</div>
</div>
</div>
<div class="input-field col s6">
<select id="update_section" required="" aria-required="true" name="section" autocomplete="off">
<option value="" disabled selected>Seleccione una opción</option>
<option value="1">Presidencia</option>
<option value="2">Senadores</option>
<option value="3">Diputados</option>
</select>
<label>Sección</label>
</div>
</div>
<input type="hidden" name="update_politic_hide" id="update_politic_hdn" value="">
</form>
CONTROLLER
public function update_politic(){
$this->load->model("politic");
$params;
if ($this->input->is_ajax_request()) {
if (empty($this->input->post("animation"))){
echo "first";
$data = $this->politic->get_file_name($this->input->post("update_politic_hide"));
$file = $data->POLITIC_FILE;//recupero el nombre de la imagen
$params["name"] = $this->input->post("name");
$params["lastname"] = $this->input->post("lastname");
$params["side"] = $this->input->post("side");
$params["charge"] = $this->input->post("charge");
$params["section"] = $this->input->post("section");
$params["animation"] = $file;
$params["id"] = $this->input->post("update_politic_hide");
if ($params["section"]=="Presidencia") {
$params["section"]=1;
}
if ($params["section"]=="Senadores") {
$params["section"]=2;
}
if ($params["section"]=="Diputados") {
$params["section"]=3;
}
}
else {
echo "second";
$config['upload_path'] = "./public/uploads/";
$config['allowed_types'] = "*";
//$config['overwrite'] = "true";
$config['max_size'] = "500000";
$config['max_width'] = "2000";
$config['max_height'] = "2000";
$this->load->library('upload', $config);
//$file = "animation";
if (!$this->upload->do_upload("animation")) {
$data['uploadError'] = $this->upload->display_errors();
echo $this->upload->display_errors();
}
else {
$file_info = $this->upload->data();
$params["name"] = $this->input->post("name");
$params["lastname"] = $this->input->post("lastname");
$params["side"] = $this->input->post("side");
$params["charge"] = $this->input->post("charge");
$params["animation"] = $file_info['file_name'];
$params["section"] = $this->input->post("section");
$params["id"] = $this->input->post("update_politic_hide");
if ($params["section"]=="Presidencia") {
$params["section"]=1;
}
if ($params["section"]=="Senadores") {
$params["section"]=2;
}
if ($params["section"]=="Diputados") {
$params["section"]=3;
}
}
}
$this->politic->update($params);
}
}
MODEL
public function update($param){
$id = $param["id"];
$values = array(
"POLITIC_NAME" => $param["name"],
"POLITIC_LASTNAME" => $param["lastname"],
"POLITIC_SIDE" => $param["side"],
"POLITIC_CHARGE" => $param["charge"],
"POLITIC_FILE" => $param["animation"],
"SECTION_ID" => $param["section"],
);
$this->db->where("POLITIC_ID",$id);
$this->db->update("politics",$values);
}
JAVASCRIPT
$("#update_politic_btn").click(function(event) {
/* Act on the event */
var chango = $("#update_form").serialize();
$.post(baseurl + 'admin/update_politic', chango,
function(data) {
console.log(data);
list_politic();
});
event.preventDefault();
});
function update_politic(id, name, lastname, section, side, charge, file) {
$("#update_politic_hdn").val(id);
$("#update_name").val(name);
$("#update_last_name").val(lastname);
$("#update_side").val(side);
$("#update_charge").val(charge);
$('[name=section]').val(section);
$("#animation").val(file);
$('select').material_select();
}
There are two name attributes having the same value animation.
<input type="file" name="animation">
and
<input class="file-path validate" id="animation" name="animation" type="text">
The second name attribute is overriding the first one. You need to give it a different name.
Change your Ajax code :
$("#update_politic_btn").click(function(event) {
var chango = new FormData($("#update_form")[0]);
// try this if above one not work
//var chango = new FormData($("#update_form"));
$.ajax({
url: baseurl + 'admin/update_politic',
type: 'POST',
data: chango,
async: false,
success: function (data) {
console.log(data);
list_politic();
},
cache: false,
contentType: false,
processData: false,
error : function() {
}
});
event.preventDefault();
});
Related
someone please help im trying to submit details together with image to databasei need help in figuring this whole thing out
<form id="register-form">
<!-- <div class="form-group">
<input type="file" id="imageInput" accept="image/*">
</div> -->
<div class="form-group">
<div class="file-upload">
<div class="image-upload-wrap">
<input name = 'sampleFile' enctype = "multipart/form-data" class="file-upload-input" type='file' id="profilepic" onchange="readImage(this)"
accept="image/*" />
<div class="drag-text">
<h3>Drag and drop a file or select add Image</h3>
</div>
</div>
<div class="file-upload-content d-none">
<img class="file-upload-image" src="#" id="imgPreview" />
<div class="image-title-wrap">
<button type="button" onclick="removeUpload()" class="remove-image">Remove <span
class="image-title">Uploaded Image</span></button>
</div>
</div>
</div>
</div>
<div class="form-group">
<label for="title">title:</label>
<input type="text" class="form-control" id="title" required>
</div>
<div class="form-group">
<label for="description">Description:</label>
<input type="text" class="form-control" id="description" required>
</div>
<div class="form-group">
<label for="release">Release:</label>
<input type="text" class="form-control" id="release" required>
</div>
<div class="form-group">
<label for="lang">Language_id:</label>
<input type="text" class="form-control" id="lang" required>
</div>
<div class="form-group">
<label for="rental_duration">Rental Duration:</label>
<input type="text" class="form-control" id="rental_duration" required>
</div>
<div class="form-group">
<label for="rental_rate">Rental rate:</label>
<input type="text" class="form-control" id="rental_rate" required>
</div>
<div class="form-group">
<label for="length">Length:</label>
<input type="text" class="form-control" id="length" required>
</div>
<div class="form-group">
<label for="replacement_cost">Replacement Cost:</label>
<input type="text" class="form-control" id="replacement_cost" required>
</div>
<div class="form-group">
<label for="rating">Rating:</label>
<input type="text" class="form-control" id="rating" required>
</div>
<div class="form-group">
<label for="special_features">Special Features:</label>
<input type="text" class="form-control" id="special_features" required>
</div>
<div class="form-group">
<label for="category_id">Category ID:</label>
<input type="text" class="form-control" id="category_id" required>
</div>
<div class="form-group">
<label for="actors">Actors:</label>
<input type="text" class="form-control" id="actors" required>
</div>
<div class="form-group">
<label for="store_id">Store_id:</label>
<input type="text" class="form-control" id="store_id" required>
</div>
<button type="submit" class="btn btn-primary">Register</button>
<button type="reset" class="btn btn-primary ml-5">Reset</button>
<button type="button" class="btn btn-primary ml-5" id="Logout">Log Out</button>
<!-- <input type="reset" value="Reset"> -->
</form>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
crossorigin="anonymous"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
const baseUrl = "http://localhost:8081";
const token = localStorage.getItem("token");
const loggedInUserID = parseInt(localStorage.getItem("loggedInUserID"));
console.log(token, loggedInUserID)
// document.getElementById("addImage").addEventListener("change", function () {
// readImage(this);
//});
// document.getElementById("submitBtn").addEventListener("click", function () {
// var title = document.getElementById("title").value;
//});
function readImage(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
var imgPreview = document.getElementById("imgPreview");
imgPreview.src = e.target.result;
document.getElementById("imgPreview").style.display = "block";
};
reader.readAsDataURL(input.files[0]);
}
}
if (token === null || isNaN(loggedInUserID)) {
window.location.href = "http://localhost:3001/home";
} else {
$("#register-form").submit((event) => {
// prevent page reload
event.preventDefault();
const pic = $("#profilepic").val()
const title = $("#title").val();
const description = $("#description").val();
const release = $("#release").val();
const lang = $("#lang").val();
const rental_duration = $("#rental_duration").val();
const rental_rate = $("#rental_rate").val();
const length = $("#length").val();
const replacement_cost = $("#replacement_cost").val();
const rating = $("#rating").val();
const feature = $("#special_features").val();
const category_id = $("#category_id").val();
const actors = $("#actors").val();
const store_id = $("#store_id").val();
const requestBody = {
image: pic,
title: title,
description: description,
release_year: release,
language_id: lang,
rental_duration: rental_duration,
rental_rate: rental_rate,
length: length,
replacement_cost: replacement_cost,
rating: rating,
special_features: feature,
category_id: category_id,
actors: actors,
store_id: store_id
};
const formData = new FormData();
formData.append("image", pic);
formData.append("title", title);
formData.append("description", description);
formData.append("release_year", release);
formData.append("language_id", lang);
formData.append("rental_duration", rental_duration);
formData.append("rental_rate", rental_rate);
formData.append("length", length);
formData.append("replacement_cost", replacement_cost);
formData.append("rating", rating);
formData.append("special_features", feature);
formData.append("category_id", category_id);
formData.append("actors", actors);
formData.append("store_id", store_id);
let token = localStorage.getItem("token");
console.log(requestBody);
axios.post(`${baseUrl}/film`, formData, { headers: { "Authorization": "Bearer " + token } })
.then((response) => {
console.log(formData)
window.location.href = "http://localhost:3001/home";
})
.catch((error) => {
console.log(error);
if (error.response.status === 400) {
alert("Validation failed");
} else {
alert("Something unexpected went wrong.");
}
});
});
$("#Logout").click(function () {
window.localStorage.clear();
localStorage.removeItem("token");
localStorage.removeItem("loggedInUserID");
window.location.assign("http://localhost:3001/home");
});
}
</script>
const fileUpload = require("express-fileupload");
app.use(fileUpload());
app.post("/upload", (req, res) => {
if (!req.files || Object.keys(req.files).length === 0) {
return res.status(400).send("No files were uploaded.");
}
let sampleFile = req.files.sampleFile;
// Use the mv() method to place the file in a upload directory
sampleFile.mv("./upload/" + sampleFile.name, (err) => {
if (err) return res.status(500).send(err);
res.send("File uploaded!");
});
});
my html form code and app.js code i just cannot send image to database idk why, i try usin express file upload but the code just cannot insert it in. Someone, please help i have 48 hours left before my deadline please!!!!!! this is my first time doing this , someone guide me
I am trying to save some store details and getting a response from the controller using Ajax but when I am trying to do so the request is not received by the Controller please see the code and help me what I am doing wrong here.
MasterAjaxClass: The class is used to send the request and receive a response
class MasterAjax{
constructor(){
this.requestType = null;
this.url = null;
this.timeout = 100000;
this.enctype = null;
this.data = null;
this.processData = null;
this.contentType = null;
this.responseData = null;
this.responseStatus = null;
this.responseStatusCode = null;
}
requestData(callBack){
var parameterError=false;
if(null == this.requestType){
parameterError=true;
console.log("Error: Request Type can't be null");
}
if(null === this.url || undefined === this.url || "undefined" === this.url){
parameterError=true;
console.log("Error: URL can't be null");
}
if(null == this.data || this.data.length <= 0){
//console.log("Warning: Data is null");
}
if(parameterError === false){
/*toggleSpinnerOn(); */
$.ajax({
type : this.requestType,
enctype : this.enctype,
processData : this.processData,
contentType : this.contentType,
// url : global_contextPath+"/"+this.url,
url : global_contextPath+"/"+this.url,
data: this.data,
timeout : this.timeout,
success : function(responseData,textStatus) {
/*toggleSpinnerOff();*/
callBack(responseData,textStatus);
},
error : function(responseData,textStatus) {
/*toggleSpinnerOff(); */
callBack(responseData,textStatus);
}
});
}
//return this.responseData;
}
}
Ajax Request method
function saveStore(){
let formData = new FormData();
//formData.append("key" , Value ) ;
formData.append("storeName", $("#storeName").val());
formData.append("country", $("#country").val());
formData.append("city", $("#city").val());
formData.append("street", $("#street").val());
formData.append("address", $("#address").val());
formData.append("zipCode", $("#zipCode").val());
formData.append("storeDescription", $("#storeDescription").val());
formData.append("storeOpenTime", $("#storeOpenTime").val());
formData.append("logoURL", $("#file-input-2").val());
console.log($("#storeName").val());
console.log($("#country").val());
console.log($("#city").val());
console.log($("#street").val());
console.log($("#address").val());
console.log($("#zipCode").val());
console.log($("#storeDescription").val());
console.log($("#storeOpenTime").val());
console.log($("#file-input-2").val());
var obj = new MasterAjax();
obj.requestType = "POST";
obj.url = "store/saveStore";
obj.data = formData;
obj.enctype ="multipart/form-data";
obj.contentType = false;
console.log("---------------------------")
for (var pair of formData.entries()) {
console.log(pair[0]+ ': ' + pair[1]);
}
console.log("---------------------------")
obj.requestData(function(responseData){
console.log(responseData);
if(responseData.status == "OK" || responseData.status == "ok"){
alert("success");
console.log(responseData)
}else{
alert(" failed");
console.log(responseData)
}
});
}
StoreForm.jsp
<form:form name="storeForms" modelAttribute="storeForm"
method="POST" enctype="multipart/form-data">
<%-- <c:if test="${not empty error}">
<div class="alert alert-danger" role="alert">
<h5 class="alert-heading">Failed to Save</h5>
<hr>
<p>${error}</p>
</div>
</c:if>
--%>
<!-- Hidden For Update employee -->
<form:input type="hidden" path="id" />
<!-- First row -->
<div class="form-row row-eq-spacing-sm">
<div class="col-sm">
<label for="first-name" class="required">Store Name</label>
<form:input type="text" path="storeName" class="form-control"
id="storeName" placeholder="Store Name" required="required" />
</div>
<div class="col-sm">
<label for="last-name" class="required">Country</label>
<form:input type="text" id="country" path="country" class="form-control" />
</div>
</div>
<!-- Second row container -->
<div class="form-row row-eq-spacing-sm">
<div class="col-sm">
<label for="first-name" class="required">City</label>
<form:input type="text" id="city" path="city" class="form-control" />
</div>
<div class="col-sm">
<label for="last-name" class="required">Street</label>
<form:input type="text" id="street" path="street" class="form-control" />
</div>
</div>
<!-- Third row container -->
<div class="form-row row-eq-spacing-sm">
<div class="col-sm">
<label for="first-name" class="required">Address</label>
<form:input type="text" id="address" path="address" class="form-control" />
</div>
<div class="col-sm">
<label for="last-name" class="required">Zip Code</label>
<form:input type="text" id="zipCode" path="zipCode" class="form-control" />
</div>
</div>
<div class="form-row row-eq-spacing-sm">
<div class="col-sm">
<label for="first-name" class="required">Store Description</label>
<form:input type="text" path="storeDescription" id="storeDescription"
class="form-control" />
</div>
<div class="col-sm">
<label for="last-name" class="required">Store Timings</label>
<form:input type="text" path="storeOpenTime" id="storeOpenTime" class="form-control" />
</div>
</div>
<div class="custom-file">
<form:input type="file" path="logoURL" id="file-input-2"
data-default-value="Size of logo should not Exeed 1mb" />
<label for="file-input-2">Choose logo</label>
</div>
<!-- Submit button container -->
<div class="text-right">
<!-- text-right = text-align: right -->
<input class="btn btn-primary" type="button" onclick="saveStore();" value="Add Store">
</div>
</form:form>
Controller Method
#Controller
#RequestMapping("/store")
public class StoreController {
#ResponseBody
#RequestMapping(value = "/saveStore" , method = {RequestMethod.POST},consumes = {"multipart/form-data"})
public APIResponseModal saveStore(#ModelAttribute("storeForm") StoresDTO store,#RequestPart("logoURL") MultipartFile file) {
logger.info("Store Save MEthod callled !!!!!!!!");
Stores storeModal = new Stores();
String logopath = "";
APIResponseModal apiResponse = new Utils().getDefaultApiResponse();
List<String> errorList = new ArrayList<String>();
try {
if(store !=null){
storeModal = new Stores(store);
if(!file.isEmpty()) {
if(file.getSize()>1000000) {//1000000 bytes == 1 mb
errorList.add("File size should be less than 1 MB");
}
logopath = Utils.storeLogoPath(file);
}
storeService.saveStore(storeModal, errorList,logopath);
if(errorList.isEmpty() && !Utils.isNotNull(errorList)) {
apiResponse.setStatus(HttpStatus.OK);
apiResponse.setData("--");
apiResponse.setMessage("Store Saved Successfully !!");
}else {
apiResponse.setMessage("Failed to save store !!");
apiResponse.setStatus(HttpStatus.BAD_REQUEST);
}
}
} catch (Exception e) {
e.printStackTrace();
apiResponse.setStatus(HttpStatus.BAD_REQUEST);
apiResponse.setData("--");
apiResponse.setMessage("Error Occured at our end !!");
}
logger.info("API RESPONSE:: ::"+ apiResponse);
return apiResponse;
}
}
Error On browser Console
Status :403
I have the form below, with 4 comboboxes "Metier" "tache" "tacrification" et "technicien", I select a Metier and a tache, after this I want that a popup box appears and show me a table that contains all the "techniciens" and their "tarification" (of course only the "techniciens" that are related with the "tache" already selected.)
After this I select a "technicien" from that table a now the form is completely filled with the "technicien" and it's "tarification".
iterventioncontroller
public function create()
{
$client = client::orderBy('id', 'asc')->get();
$metiers = metier::orderBy('id', 'asc')->get();
$technicien = Technicien::orderBy('id', 'desc')->get();
$tarifications = tarificationtache::orderBy('id', 'desc')->get();
return view('intervention.create')->with('technicien', $technicien)-
>with('client',$client)-
>with('metiers',$metiers)->with('tarifications',$tarifications);
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(InterventionRequest $request)
{
$intervention = new Intervention();
$intervention ->date_intervention =$request-
>input('date_intervention');
$intervention ->description =$request->input('description');
$intervention ->duree_prevu =$request->input('duree_prevu');
if($request->has('statut')){
$intervention->statut = $request->input('statut');
}else{
$intervention->statut = 0;
}
$intervention ->technicien_id = $request->input('technicien_id');
$intervention ->client_id = $request->input('client_id');
$intervention ->tarification_id = $request->tarification_id;
$intervention->save();
return redirect('intervention');
}
create.blade.php
#extends('Layouts/app')
#extends('Layouts/master')
#section('content')
<!-- jQuery -->
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
var getTachesByMetierUrl = "{{url('/tachesbymetier')}}";
var getAdresseByClientUrl = "{{url('/adressebyclient')}}";
var getTarificationsByTacheUrl = "{{url('/tarificationsbytache')}}";
var getTechniciensByTarificationtacheUrl = "
{{url('/techniciensbytarificationtache')}}";
//console.log(getMetiersByTechnicienUrl,getTachesByMetierUrl,getTarificationsByTacheUrl);
function getAdresseByClient(val) {
if(val.length>0) {
var client_id = val;
$.get(getAdresseByClientUrl+'/'+client_id,function(res) {
var html = '<option value="">-Select-</option>' ;
$.each(res.adresses,function(index,item) {
html+='<option
value="'+item.id+'">'+item.code_postal+'</option>';
});
$('#adresses').html(html);
});
}
}
function getTachesByMetier(val) {
if(val.length>0) {
var metier_id = val;
$.get(getTachesByMetierUrl+'/'+metier_id,function(res) {
var html = '<option value="">-Select-</option>' ;
$.each(res.taches,function(index,item) {
html+='<option
value="'+item.id+'">'+item.libelle_tache+'</option>';
});
$('#taches').html(html);
});
}
}
function getTarificationsByTache(val) {
if(val.length>0) {
var tache_id = val;
$.get(getTarificationsByTacheUrl+'/'+tache_id,function(res) {
var html = '<option value="">-Select-</option>' ;
$.each(res.tarifications,function(index,item) {
html+='<option
value="'+item.id+'">'+item.tarif+'</option>';
});
$('#tarifications').html(html);
});
}
}
function getTechniciensByTarificationtache(val) {
if(val.length>0) {
var tarificationtache_id = val;
$.get(getTechniciensByTarificationtacheUrl+'/'+tarificationtache_id,function(res) {
var html = '<option value="">-Select-</option>' ;
$.each(res.techniciens,function(index,item) {
html+='<option value="'+item.id+'">'+item.id+'</option>';
});
$('#techniciens').html(html);
});
}
}
#if(count($errors))
<div class="alert alert-danger" role="alert">
<ul>
#foreach($errors ->all() as $message)
<li>{{$message}}</li>
#endforeach
</ul>
</div>
#endif
<div class="container">
<div class="row"></div>
<div class="col-md-10">
<h1>Ajout Intervention</h1>
<form action=" {{url ('intervention') }}" method="post">
{{csrf_field()}}
<div class="form-group">
<label for="client">Client</label>
<select onchange="getAdresseByClient(this.value)"
name="client_id" id="client"
class="form-control">
<option value="">-Select-</option>
#foreach($client as $t)
<option value="{{$t->id }}">
{{$t->user->nom}}
</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="">date intervention</label>
<input class="form-control" type="date" id="example-date-
input" name
="date_intervention" value="{{old('date_intervention')}}">
</div>
<div class="form-group">
<label for="">description</label>
<input type="text" name ="description" class="form-
control"value="
{{old('description')}}">
</div>
<div class="form-group">
<label for="">duree_prevu</label>
<input class="form-control" type="datetime-local" name
="duree_prevu" value="
{{old('duree_prevu')}}">
</div>
<div class="form-group">
<div class="col-md-12">
<div class="col-md-4">
<label>Metier: </label>
<select onchange="getTachesByMetier(this.value)"
style="width: 200px"
class="productm form-control" id="metiers">
<option value="">-Select-</option>
#foreach($metiers as $t)
<option value="{{$t->id }}">
{{$t->libelle_metier}}
</option>
#endforeach
</select>
</div>
<div class="col-md-4">
<label>tache: </label>
<select onchange="getTarificationsByTache(this.value)"
style="width: 200px"
class="productname form-control" name="tache" id="taches">
<option value="">-Select-</option>
</select>
</div>
<div class="col-md-4">
<label>tarification: </label>
<select
onchange="getTechniciensByTarificationtache(this.value)"
style="width:
200px" class="productname form-control" name="tarificationtache_id"
id="tarifications">
<option value="">-Select-</option>
</select>
</div>
<div class="col-md-4">
<label>technicien: </label>
<select style="width: 200px" class="productname
form-control"
name="technicien_id" id="techniciens">
<option value="">-Select-</option>
</select>
</div>
</div>
</div>
</div>
</div>
</div>
<link
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-
datepicker/1.5.0/css/bootstrap-
datepicker.css" rel="stylesheet">
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-
datepicker/1.5.0/js/bootstrap-
datepicker.js"></script>
#endsection
You might want to look into bootstrap 4 modal.
I have PartialView
Here is code
<form>
<div class="form-group">
<label for="recipient-name" class="col-form-label">Выберите проект</label>
<select id="projectId" name="add_triangolazione" class="form-control">
</select>
</div>
<div class="form-group">
<label for="recipient-name" class="col-form-label">От:</label>
<input type="date" class="form-control" id="datefrom">
</div>
<div class="form-group">
<label for="recipient-name" class="col-form-label">До:</label>
<input type="date" class="form-control" id="dateto" placeholder="YYYY-MM-DD" data-date-split-input="true" >
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Наименование услуги:</label>
#Html.DropDownList("Service", null, "XXXX", htmlAttributes: new { #class = "form-control", #id = "serviceIdProject" })
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">График работы:</label>
<div>
<label for="message-text" class="col-form-label">С:</label>
<input type="time" class="form-control" id="workTime">
</div>
<div>
<label for="message-text" class="col-form-label">По:</label>
<input type="time"" class="form-control" id="workTimeTo">
</div>
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Количество:</label>
<textarea class="form-control" id="quantity"></textarea>
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Тариф:</label>
<textarea class="form-control" id="rate" readonly></textarea>
</div>
It loading into modal via script
Here is script code
$(document).on('click', '#addShow', function () {
ShowAndPopulate();
});
function ShowAndPopulate() {
$('#addProposalManager').load('/Manage/AddProposalManager', function () {
let email = $('#userId').text();
let getProposalsUrl = '/manage/populateprojects';
model = {
email: email
},
$.ajax({
url: getProposalsUrl,
data: JSON.stringify(model),
contentType: 'application/json; charset=utf-8',
type: 'POST',
dataType: 'json',
processData: false,
success: function (data) {
var list = data;
$.each(list, function (i, d) {
$('#projectId').append('<option value="' + d.Id + '">' + d.Name + '</option>');
});
}
})
});
}
Also in this field
#Html.DropDownList("Service", null, "XXXX", htmlAttributes: new { #class = "form-control", #id = "serviceIdProject" })
I need to do something on value change
So I wrote this code at script
$('#serviceIdProject').change(function () {
alert("Gotcha!");
// ServiceChange();
});
But when I change value, nothing happens.
Where can be my problem?
Thank's for help
Try using event delegation and also you seem to be using the wrong ID for the select:
$(document).on('change' , '#projectId' , function () {
alert("Gotcha!");
// ServiceChange();
});
i have created a form which is submitting data through ajax to the database.this works fine.how can i prevent entering sitename is already available in database.if that sitename already in database it should give error message.
Controller
public function user_add()
{
$data_save = array(
"Mnumber" => $this->input->post("Mnumber"),
"email" => $this->input->post("email"),
"fname" => $this->input->post("fname"),
"address" =>$this->input->post("address"),
"sitename" =>$this->input->post("sitename"),
/* "reqnum" => $this->input->post("reqnum"),*/
"title" => $this->input->post("title"),
"descr" => $this->input->post("descr"),
/*"payment" => $this->input->post("payment"),*/
"uniquekey" => $this->input->post("uniquekey")
/*"subscription" => $this->input->post("subscription"),
"email_sent" => $this->input->post("email_sent"),*/
);
if ($this->user_mod->AddUser($data_save)) {
echo "Successfully Saved";
}
else {
echo "error";
}
}
view
<script>
function save_user_new() {
var Mnumber = $('#Mnumber').val();
var email = $('#email').val();
var fname = $('#fname').val();
var address = $('#address').val();
var sitename = $('#sitename').val();
/*var reqnum = $('#reqnum').val();*/
var title = $('#title').val();
var descr = $('#descr').val();
var uniquekey = $('#uniquekey').val();
/*var subscription = $('#subscription').val();
var email_sent = $('#email_sent').val();
var payment = $('#payment').val();*/
if (sitename != "" && email != "") {
$.ajax({
type: "post",
async: false,
url: "<?php echo site_url('form_con/user_add'); ?>",
data: {
"Mnumber": Mnumber,
"email": email,
"fname": fname,
"address": address,
"sitename": sitename,
/*"reqnum": reqnum,*/
"title": title,
"descr": descr,
"uniquekey": uniquekey
/*"subscription": subscription,
"email_sent": email_sent,
"payment":payment*/
},
dataType: "html",
success: function (data) {
alert(data);
if (data == 'error') {
$('#success_msg').hide();
$('#error_msg1').show();
$('#error_msg1').html("Error : Something wrong.");
} else if (data == 'have') {
$('#success_msg').hide();
$('#error_msg1').show();
$('#error_msg1').html("Error : This Sitename is already exists.");
} else {
$('#error_msg1').hide();
$('#success_msg').show();
$('#success_msg').html("User details successfully saved.");
/*setTimeout(function() { location="features.php"},2000);*/
location.href = 'freecreate';
}
}
});
} else {
$('#success_msg').hide();
$('#error_msg1').show();
$('#error_msg1').html("Error : Please enter User Details.");
}
}
</script>
<form action="#" id="form_sample_1">
<div class="form-body">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Your First Name</label>
<input type="text" class="form-control" id="fname" name="fname" placeholder="Enter text" required="">
</div>
<div class="form-group">
<label class="control-label">Email Address</label>
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-envelope"></i></span>
<input type="email" class="form-control" id="email" name="email" placeholder="Email Address" required="">
</div>
</div>
<div class="form-group">
<label class="control-label">Your Mobile Number</label>
<input type="text" class="form-control" id="Mnumber" name="Mnumber" placeholder="Enter text" required="">
<!--<span class="help-block"> A block of help text. </span>-->
</div>
<div class="form-group">
<label class="control-label">Your Address</label>
<input type="text" class="form-control" id="address" name="address" placeholder="Enter text" required="">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Your Site Name</label>
<input type="text" class="form-control" id="sitename" name="sitename" placeholder="Enter text" required="">
<span class="help-block"> please enter the sitename only.if you wish to cretae site as john just type john.it will create the site automatically as john.site.mobi </span><br>
</div>
<div class="form-group">
<label class="control-label">Title of Your Web site</label>
<input type="text" class="form-control" id="title" name="title" placeholder="Enter text" required="">
</div>
<div class="form-group">
<label class="control-label">Description of Your Web Site</label>
<input type="text" class="form-control" id="descr" name="descr" placeholder="Enter text" required="">
<!--<input type="hidden" class="form-control" id="req_num" name="req_num" value="1" placeholder="Enter text">-->
<?php $uniquekey = md5(uniqid(rand(), true)); ?>
<input type="hidden" class="form-control" id="uniquekey" name="uniquekey" value="<?php echo $uniquekey ?>" placeholder="Enter text">
<!--<input type="hidden" class="form-control" id="subscription" name="subscription" value="1" placeholder="Enter text">
<input type="hidden" class="form-control" id="email_sent" name="email_sent" value="1" placeholder="Enter text">-->
<!--<input type="hidden" class="form-control" id="payment" name="payment" value="1" placeholder="Enter text">-->
</div>
</div>
<div class="form-actions right">
<!--<a class="btn green" onclick="save_user_new()">Submit</a>-->
<button type="submit" id="save_btn" class="btn green" onclick="save_user_new()">Submit</button>
<button type="button" class="btn default">Cancel</button>
</div>
</div>
</form>
Model
public function AddUser($data_save)
{
if ($this->db->insert('users', $data_save)) {
return true;
} else {
return false;
}
}
Write a validate function which actually checks for empty value in textbox and returns true or false. Consider below example.
function ValidateForm(form){
var valid=true;
$(form).find('input[type="text"]').each(function(){
if($(this).val()=="")
valid=false;
});
return valid;
}
function save_user_new() {
//getting all the values
//change if condition to
var form=$("#form_sample_1");
if(ValidateForm(form))
{
//continue with ajax
}
else
{
alert('Please fill all the fields');
return false;
}
}
Add jQuery required in save_user_new function
$("input").prop('required',true);
There is a couple of ways to do this.
As previously mentioned, write a validate method and check if the record already exists in the database.
Set the field to 'unique', and catch the error when you run the query,
also if you want to save yourself some time and coding write a helper function which will load all your post variables for your.
eg.
function LoadPostVariables($variables = [])
{
$CI = & get_instance();
$return_array = [];
foreach($variables as $key){
$p_val = $CI->input->post($key);
//you could perform some basic validation here
$return_array[$key]=$p_val;
}
}
$values = LoadPostVariables(['MNumber', 'email', 'fname', 'address', 'sitename', 'title', 'descr', 'uniquekey']);
public function AddUser($data_save)
{
$check = false;
$query = "SELECT * FROM users WHERE email='$data_save' LIMIT 1";
$result = mysqli_query($dbc, $query);
if($result){
while($row = mysqli_fetch_assoc($result)){
$check = true;
}
}
if($check == false){
// add data
}else{
echo 'Email already found'; exit();
}
}