How to show the modal in without reloading the page - javascript

Here i did form validation ,after form validation all fields filled and click the INVITE QUOTES button means i want show modal, and i want to fill the modal form after filled all field means i want to close that modal,but dont want to refresh the page,Here i click INVITE QUOTES button means page is refreshing and modal is not showing how can do this?
<script>
/*$('#businessForm').submit(function (e) {
e.preventDefault();
validateForm();
});*/
function validateForm() {
var ratesfor = document.forms["myForm"]["ratesfor"].value;
if (ratesfor == null || ratesfor == "") {
document.getElementById("rate_err").innerHTML = "Field is empty";
}
var no = document.forms["myForm"]["no"].value;
if (no == null || no == "") {
document.getElementById("no_err").innerHTML = "Field is empty";
}
var breath = document.forms["myForm"]["breath"].value;
if (breath == null || breath == "") {
document.getElementById("b_t_err").innerHTML = "Field is empty";
}
var height = document.forms["myForm"]["height"].value;
if (height == null || height == "") {
document.getElementById("height_err").innerHTML = "Field is empty";
}
var truck_type = document.forms["myForm"]["truck_type"].value;
if (truck_type == null || truck_type == "") {
document.getElementById("truck_type_err").innerHTML = "Field is empty";
}
var datepicker = document.forms["myForm"]["datepicker-13"].value;
if (datepicker == null || datepicker == "") {
document.getElementById("pickup_err").innerHTML = "Field is empty";
}
var myTime = document.forms["myForm"]["myTime"].value;
if (myTime == null || myTime == "") {
document.getElementById("time_err").innerHTML = "Field is empty";
}
var from = document.forms["myForm"]["from"].value;
if (from == null || from == "") {
document.getElementById("from_err").innerHTML = "Field is empty";
}
var to = document.forms["myForm"]["to"].value;
if (to == null || to == "") {
document.getElementById("to_err").innerHTML = "Field is empty";
return false;
}
else{
$('#businessForm').submit(function (e) {
e.preventDefault();
})
$.ajax({
url:'search_truck.php',
type:'POST',
data : { 'state_id' : city},
success:function(data){
//var res=jQuery.parseJSON(data);// convert the json
console.log(data);
},
});
}
}
</script>
<script>
$(document).ready(function(){
$("#myBtn").click(function(){
$("#myModal").modal();
});
});
$(document).ready(function(){
$("#Register").click(function(){
$("#myModal").hide();
$("#myModal_Register").modal();
});
});
</script>
<form id="businessForm" method="POST" onsubmit="return validateForm()" name="myForm" enctype="multipart/form-data">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="experience">Rates For</label>
<input type="ratesfor" class="form-control" id="ratesfor" name="ratesfor" placeholder="weight(kg)">
<span id="rate_err"></span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="length">Length</label>
<input type="text" class="form-control" id="no" name="no" placeholder="Length"><span id="no_err"></span>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="length"> </label>
<select class="form-control form-design col-lg-6 col-md-6 col-sm-12 col-xs-12" autocomplete="off" name="length" id="length" style="margin-top:25px;">
<option value="">feet</option>
<option value="">mm</option>
<option value="">mtr</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="breadth">Breadth</label>
<input type="text" class="form-control" id="breath" name="breath" placeholder="Breadth"><span id="b_t_err"></span>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="breadth"> </label>
<select class="form-control form-design col-lg-6 col-md-6 col-sm-12 col-xs-12" autocomplete="off" name="b_type" id="b_type" style="margin-top:25px;">
<option value="">feet</option>
<option value="">mm</option>
<option value="">mtr</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="height">Height</label>
<input type="text" class="form-control" id="height" name="height" placeholder="Height"><span id="height_err"></span>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="height"> </label>
<select class="form-control form-design col-lg-6 col-md-6 col-sm-12 col-xs-12" autocomplete="off" name="type" id="h_t" name="h_t" style="margin-top:25px;">
<option value="">feet</option>
<option value="">mm</option>
<option value="">mtr</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="experience">Type Of Truck</label>
<select id="truck_type" name="truck_type" autocomplete="off" class="form-control form-design col-lg-6 col-md-6 col-sm-12 col-xs-12">
<option value="feet">feet</option>
<option value="mm">mm</option>
<option value="mtr">mtr</option>
</select><span id="truck_type_err"></span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="date">Date of PickUp</label>
<br>
<input type="text" placeholder="DD-MM-YY" id="datepicker-13" name="datepicker-13" style="width:100%;height:35px;">
<span id="pickup_err"></span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="time">Time of PickUp</label>
<br>
<input type="time" class="form-control" id="myTime" name="myTime" placeholder="Time">
<span id="time_err"></span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="experience">Destination</label>
<select class="form-control form-design col-lg-6 col-md-6 col-sm-12 col-xs-12" autocomplete="off" id="from" name="from">
<option value="">From</option>
<option value="1">Ahmedabad</option>
<option value="2">Bangalore</option>
</select>
</div>
<span id="from_err"></span>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="experience"> </label>
<select class="form-control form-design col-lg-6 col-md-6 col-sm-12 col-xs-12" autocomplete="off" name="to" id="to" style="margin-top:25px;">
<option value="">To</option>
<option value="1">Guragon</option>
<option value="2">Hyderabad</option>
</select>
</div>
<span id="to_err"></span>
</div>
</div>
<br>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<button type="submit" class="btn btn-primary btn-lg btn-block">INVITE QUOTES</button>
</div>
</div>
</div>
</form>
<div class="container">
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog" style="z-index: 9999;">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header" style="padding:5px 50px;">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4>Login</h4>
</div>
<div class="modal-body" style="padding:40px 50px;">
<form role="form">
<div class="form-group">
<label for="usrname">Username</label>
<input type="text" class="form-control" id="usrname" placeholder="Enter Name">
</div>
<div class="form-group">
<label for="psw"> Password</label>
<input type="text" class="form-control" id="psw" placeholder="Enter password">
</div>
<div class="checkbox">
<label>
<input type="checkbox" value="" checked>Remember me</label>
</div>
<button type="submit" class="btn btn-info btn-block">Login </button>
</form>
</div>
<div class="modal-footer">
<p>Not a member? <b>Sign Up</b>
</p>
<!--<p>Forgot Password?</p>-->
</div>
</div>
</div>
</div>
<!--######
Login From End
#######--->
<!--#####
Register From Start
#####--->
<div class="modal fade" id="myModal_Register" role="dialog">
<div class="modal-dialog" style="z-index: 9999;">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header" style="padding:5px 50px;">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4>Registration</h4>
</div>
<div class="modal-body" style="padding:40px 50px;">
<form role="form">
<div class="form-group">
<label for="usrname"> Username</label>
<input type="text" class="form-control" id="usrname" placeholder="Enter name">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="text" class="form-control" id="email" placeholder="Enter email">
</div>
<div class="form-group">
<label for="psw">Password</label>
<input type="text" class="form-control" id="psw" placeholder="Enter password">
</div>
<div class="form-group">
<label for="psw"> Confirm Password</label>
<input type="text" class="form-control" id="psw" placeholder="Confirm password">
</div>
<button type="submit" class="btn btn-info btn-block">Submit</button>
</form>
</div>
<!-- <div class="modal-footer">
<p>Not a member? Sign Up</p>
<p>Forgot Password?</p>
</div>-->
</div>
</div>
</div>
</div>

Bro check this line:
<button type="submit" class="btn btn-primary btn-lg btn-block">INVITE QUOTES</button>
here you are using button type submit, submit button will submit the form and reloads the page. Instead use:
<button type="button" class="btn btn-primary btn-lg btn-block">INVITE QUOTES</button>

Related

how to add validation in javascript on form so that it should not append form when last row is empty (should not create another row untill all fields)

function add_variant(){
var thickness=document.forms["create_product"]["thickness"].value;
var thickness_unit=document.forms["create_product"]["thickness_unit"].value;
var product_qty=document.forms["create_product"]["product_qty"].value;
var product_cost_price=document.forms["create_product"]["product_cost_price"].value;
var product_unit=document.forms["create_product"]["product_unit"].value;
var product_color=document.forms["create_product"]["product_color"].value;
var thickness_dim =document.forms["create_product"]["thickness"].value;
console.log("thick"+thickness);
console.log("thick dim"+thickness_dim);
if(thickness == null || thickness == "", thickness_dim ==""|| thickness_dim==null)
{
alert('you must filled previous data');
return false;
}
var temp = document.getElementById("product_dimension").content;
var copy = document.importNode(temp,true);
document.getElementById("product_description").appendChild(copy);
}
<div class="col-md-2">
<label>Product Variants</label>
<a class="btn btn-primary" id="add_variant" onclick="add_variant()"><i class="fa fa-plus"></i> add Variant</a>
</div>
<div id="product_description">
<div class="row" >
<div class="col-sm-1">
<div class="form-group">
<label>Actions</label><br>
<button class="btn btn-danger"><i class="fa fa-trash"></i></button>
</div>
</div>
<div class="col-md-1">
<div class="form-group">
<label>Thickness</label>
<input type="number" class="form-control" name="thickness" id="thickness">
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>Thickness Unit</label>
<select class="form-control"name="thickness_unit" id="thickness_unit">
<option>mm</option>
<option>feet</option>
<option>Square feet</option>
<option>meter</option>
<option>mm square</option>
<option>Steel Gauge</option>
</select>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>Product Qty.</label>
<input type="number" class="form-control" name="product_qty" id="product_qty">
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>Product Cost Price</label>
<input type="number" class="form-control" name="product_cost_price" id="product_cost_price">
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>Product Unit</label>
<select class="form-control" name="product_unit" id="product_unit">
<option>Sheet</option>
<option>No</option>
</select>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>Product Color</label>
<input type="text" class="form-control" name="product_color" id="product_color">
</div>
</div>
</div>
</div>
<div>
<template id="product_dimension">
<div class="row">
<div class="col-md-1">
<div class="form-group">
<label>Actions</label><br>
<button class="btn btn-danger btnDelete"><i class="fa fa-trash"></i></button>
</div>
</div>
<div class="col-md-1">
<div class="form-group">
<label>Thickness</label>
<input type="number" class="form-control" name="thickness" id="thickness">
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>Thickness Unit</label>
<select class="form-control"name="thickness_unit" id="thickness_unit">
<option>mm</option>
<option>feet</option>
<option>Square feet</option>
<option>meter</option>
<option>mm square</option>
<option>Gauge</option>
</select>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>Product Qty.</label>
<input type="number" class="form-control" name="product_qty" id="product_qty">
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>Product Cost Price</label>
<input type="number" class="form-control" name="product_cost_price" id="product_cost_price">
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>Product Unit</label>
<select class="form-control" name="product_unit" id="product_unit">
<option>Sheet</option>
<option>Nos</option>
</select>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>Product Color</label>
<input type="text" class="form-control" name="product_color" id="product_color">
</div>
</div>
</div>
</template>
</div>
i am new to java script i am trying to add some validations on my add product form in which i am trying to perform some append function in whixh i want to append a div but if the previous row is empty then it should not add/append new row but while doing so it just check validation for the 1st row when i add 2 nd add try to add 3rd it shows error
will please anybody help me to solve this,here is my code
JS:
function add_variant(){
var thickness=document.forms["create_product"]["thickness"].value;
var thickness_unit=document.forms["create_product"]["thickness_unit"].value;
var product_qty=document.forms["create_product"]["product_qty"].value;
var product_cost_price=document.forms["create_product"]["product_cost_price"].value;
var product_unit=document.forms["create_product"]["product_unit"].value;
var product_color=document.forms["create_product"]["product_color"].value;
var thickness_dim =document.forms["create_product"]["thickness"].value;
console.log("thick"+thickness);
console.log("thick dim"+thickness_dim);
if(thickness == null || thickness == "", thickness_dim ==""|| thickness_dim==null)
{
alert('you must filled previous data');
return false;
}
var temp = document.getElementById("product_dimension").content;
var copy = document.importNode(temp,true);
document.getElementById("product_description").appendChild(copy);
}
<div id="product_description">
<div class="row" >
<div class="col-sm-1">
<button class="btn btn-danger"><i class="fa fa-
trash"></i></button>
</div>
<!--further fields-->
</div>
<template id="product_dimension">
<div class="row">
<div class="col-md-1">
<div class="form-group">
<button class="btn btn-danger btnDelete"><i class="fa fa-trash"></i>
</button>
<!--further fields->
</div>
</div>
</template>
`
Here is the code:
const addVariant = document.getElementById("add_variant");
const productDescription = document.getElementById("product_description");
const errorAlert = document.querySelector(".alert");
const template = `<div class="row my-4 p-3 rounded productTemp">
<div class="col-md-1">
<div class="form-group">
<label class="mb-2">Actions</label>
<br />
<button class="btn btn-danger btnDelete">
<i class="fa fa-trash"></i>
</button>
</div>
</div>
<div class="col-md-1">
<div class="form-group">
<label class="mb-2">Thickness</label>
<input type="number" class="form-control" name="thickness" />
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label class="mb-2">Thickness Unit</label>
<select class="form-control" name="thickness_unit">
<option>mm</option>
<option>feet</option>
<option>Square feet</option>
<option>meter</option>
<option>mm square</option>
<option>Gauge</option>
</select>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label class="mb-2">Product Qty.</label>
<input type="number" class="form-control" name="product_qty" />
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label class="mb-2">Product Cost Price</label>
<input type="number" class="form-control" name="product_cost_price" />
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label class="mb-2">Product Unit</label>
<select class="form-control" name="product_unit">
<option>Sheet</option>
<option>Nos</option>
</select>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label class="mb-2">Product Color</label>
<input type="text" class="form-control" name="product_color" />
</div>
</div>
</div>
`;
function addAlert(message) {
errorAlert.classList.add("show");
errorAlert.innerHTML = message;
setTimeout(() => {
errorAlert.classList.remove("show");
}, 3000);
}
addVariant.addEventListener("click", function() {
const productTemp = document.querySelectorAll(".productTemp");
const lastElement = productTemp[productTemp.length - 1];
const thickness = lastElement.querySelector('[name="thickness"]');
const thicknessUnit = lastElement.querySelector('[name="thickness_unit"]');
const productQty = lastElement.querySelector('[name="product_qty"]');
const productPrice = lastElement.querySelector('[name="product_cost_price"]');
const productUnit = lastElement.querySelector('[name="product_unit"]');
const productColor = lastElement.querySelector('[name="product_color"]');
if (
thickness.value !== "" &&
thicknessUnit.value !== "" &&
productQty.value !== "" &&
productPrice.value !== "" &&
productUnit.value !== "" &&
productColor.value !== ""
) {
productDescription.insertAdjacentHTML("beforeend", template);
} else {
addAlert("Fields can not be empty! 😑");
}
});
.productTemp {
background-color: #2c3035;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" integrity="sha512-iBBXm8fW90+nuLcSKlbmrPcLa0OT92xO1BIsZ+ywDWZCvqsWgccV3gFoRBv0z+8dLJgyAHIhR35VZc2oM/gI1w==" crossorigin="anonymous" />
<body class="bg-dark text-white">
<div class="container mt-5 bg-dark text-white">
<div class="alert alert-danger alert-dismissible fade mb-5" role="alert"></div>
<div class="col-md-2 mb-4">
<label class="mb-2">Product Variants</label>
<a class="btn btn-primary" id="add_variant">
<i class="fa fa-plus"></i> add Variant
</a>
</div>
<div id="product_description">
<div class="row my-4 p-3 rounded productTemp">
<div class="col-sm-1">
<div class="form-group">
<label class="mb-2">Actions</label>
<br />
<button class="btn btn-danger">
<i class="fa fa-trash"></i>
</button>
</div>
</div>
<div class="col-md-1">
<div class="form-group">
<label class="mb-2">Thickness</label>
<input type="number" class="form-control" name="thickness" />
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label class="mb-2">Thickness Unit</label>
<select class="form-control" name="thickness_unit">
<option>mm</option>
<option>feet</option>
<option>Square feet</option>
<option>meter</option>
<option>mm square</option>
<option>Steel Gauge</option>
</select>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label class="mb-2">Product Qty.</label>
<input type="number" class="form-control" name="product_qty" />
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label class="mb-2">Product Cost Price</label>
<input type="number" class="form-control" name="product_cost_price" />
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label class="mb-2">Product Unit</label>
<select class="form-control" name="product_unit">
<option>Sheet</option>
<option>No</option>
</select>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label class="mb-2">Product Color</label>
<input type="text" class="form-control" name="product_color" />
</div>
</div>
</div>
</div>
</div>
</body>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta3/dist/js/bootstrap.bundle.min.js" integrity="sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf" crossorigin="anonymous"></script>

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

I have to give some dependent fields in html,php,javascript

I need to give some dependency in the fields. Ex:
first i have two option that is Branch/Staff so, if i am selecting branch it should display the branches to select if he is selecting staff then i should be able to select the employee id and if am selecting employee id employee name should display and more over all these things user needs to feed the data. That is main category branch/staff should be standard but there after branches,employee number and name al these things user needs to feed
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function updatePrice() {
// Get the ex-GST price from its form element
var exPrice = document.getElementById("product_price").value;
var gstPrice = document.getElementById("cgst").value;
// Get the GST price
gstPrice = exPrice * 0.09;
var TPrice = parseInt(gstPrice) + parseInt(exPrice) + parseInt(gstPrice);
// Set the GST price in its form element
document.getElementById("cgst").value = gstPrice;
document.getElementById("igst").value = gstPrice;
document.getElementById("sgst").value = 0;
document.getElementById("total").value = TPrice;
}
</script>
</head>
<body>
<?php
public function addProduct($pro_name,$price,$stock,$date,$loc,$in_no,$gst_no,$cgst,$sgst,$igst,$total,$depre,$pur_from){
$pre_stmt = $this->con->prepare("INSERT INTO `products`( `product_name`, `product_price`, `product_stock`, `added_date`, `p_status`, `loc`, `in_no`, `gst_no`, `cgst`, `sgst`, `igst`, `total`, `depre`, `pur_from`)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
$status = 1;
$pre_stmt->bind_param("sdisisiiddddis",$cid,$bid,$pro_name,$price,$stock,$date,$status,$loc,$in_no,$gst_no,$cgst,$sgst,$igst,$total,$depre,$pur_from);
$result = $pre_stmt->execute() or die($this->con->error);
if ($result) {
return "NEW_PRODUCT_ADDED";
}else{
return 0;
}
}
if (isset($_POST["added_date"]) AND isset($_POST["product_name"]) ) {
$obj = new DBOperation();
$result = $obj->addProduct($_POST["select_cat"],
$_POST["select_brand"],
$_POST["product_name"],
$_POST["product_price"],
$_POST["product_qty"],
$_POST["added_date"],
$_POST["loc"],
$_POST["in_no"],
$_POST["gst_no"],
$_POST["cgst"],
$_POST["sgst"],
$_POST["igst"],
$_POST["total"],
$_POST["depre"],
$_POST["pur_from"]);
echo $result;
exit();
}
?>
<div class="modal fade" id="form_products" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Add new products</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form id="product_form" onsubmit="return false">
<div class="form-group">
<label>Category</label>
<select class="form-control" id="select_cat" name="select_cat" required/>
</select>
</div>
<div class="form-group">
<label>Brand</label>
<select class="form-control" id="select_brand" name="select_brand" required/>
</select>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label>RHFL ID</label>
<input type="text" class="form-control" name="product_name" id="product_name" placeholder="Enter RHFL ID" required>
</div>
<div class="form-group col-md-6">
<label>Invoice No</label>
<input type="text" class="form-control" name="in_no" id="in_no" placeholder="Enter Invoice No" required>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label>Location</label>
<input type="text" class="form-control" id="loc" name="loc" placeholder="Enter Location" required/>
</div>
<div class="form-group col-md-6">
<label>Purchase Date</label>
<input type="text" class="form-control" id="added_date" name="added_date" value="<?php echo date("Y-m-d"); ?>" readonly/>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label>Product Price</label>
<input type="text" class="form-control" id="product_price" name="product_price" onChange="updatePrice()" />
</div>
<div class="form-group col-md-6">
<label>GST No</label>
<input type="text" class="form-control" id="gst_no" name="gst_no" placeholder="Enter GST No" required/>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label>Purchased From</label>
<input type="text" class="form-control" id="pur_from" name="pur_from" placeholder="Enter From Where you purchased" required/>
</div>
<div class="form-group col-md-6">
<label>IGST</label>
<input type="text" class="form-control" id="igst" name="igst" onChange="updatePrice()" />
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="cgst">CGST</label>
<input type="text" class="form-control" id="cgst" name="cgst" readonly name="cgst" onChange="updatePrice()" />
</div>
<div class="form-group col-md-6">
<label>SGST</label>
<input type="text" class="form-control" id="sgst" name="sgst" onChange="updatePrice()" />
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label>Quantity</label>
<input type="text" class="form-control" id="product_qty" name="product_qty" placeholder="Enter Quantity" required/>
</div>
<div class="form-group col-md-6">
<label>Depreciation</label>
<input type="text" class="form-control" id="depre" name="depre" placeholder="Enter Price of SGST" required/>
</div>
</div>
<div class="form-group">
<label>Total</label>
<input type="text" class="form-control" id="total" name="total" onChange="updatePrice(this.form)" />
</div>
<button type="submit" class="btn btn-success">Add Product</button>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</body>
//add product
$("#product_form").on("submit",function(){
$.ajax({
url : DOMAIN+"/includes/process.php",
method : "POST",
data : $("#product_form").serialize(),
success : function(data){
if (data == "NEW_PRODUCT_ADDED") {
alert("New Product Added Successfully..!");
$("#product_name").val("");
$("#select_cat").val("");
$("#select_brand").val("");
$("#product_price").val("");
$("#product_qty").val("");
calculate();
}else{
console.log(data);
alert(data);
}
}
})
})

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'])){

Dynamic multiselect feature

I am creating the fields dynamically in HTML using this JS, and in multiselect I'm using bootstrap multiselect here is the code https://bootsnipp.com/snippets/Ekd8P when I click on the add more button it creates the form dynamically.
js code for creating a form dynamically :
$(function() {
// Remove button
$(document).on(
'click',
'[data-role="dynamic-fields"] > .form-horizontal [data-role="remove"]',
function(e) {
e.preventDefault();
$(this).closest('.form-horizontal').remove();
}
);
// Add button
var i = 1;
$(document).on(
'click',
'[data-role="dynamic-fields"] > .form-horizontal [data-role="add"]',
function(e) {
e.preventDefault();
var container = $(this).closest('[data-role="dynamic-fields"]');
new_field_group = container.children().filter('.form-horizontal:first-child').clone();
new_field_group.find('input').each(function() {
if (this.name == 'tags[0]') {
$(this).tagsinput('destroy');
$(this).tagsinput('removeAll');
this.name = this.name.replace('[0]', '[' + i + ']');
var new_container = $(this).closest('[class="form-group"]');
new_container.find(".bootstrap-tagsinput:first").remove();
} else {
$(this).val('');
}
});
new_field_group.find('select').each(function() {
if (this.name == 'addons[0]') {
$(this).multiselect('rebuild');
this.name = this.name.replace('[0]', '[' + i + ']');
var new_container = $(this).closest('[class="multiselect-native-select"]');
new_container.find(".multiselect-native-select > .multi").remove();
} else {
$(this).val('');
}
});
i += 1;
container.append(new_field_group);
}
);
});
and html code for form elements:
<form action="" method="post" novalidate="novalidate" enctype="multipart/form-data">
{{ csrf_field() }}
<div data-role="dynamic-fields">
<div class="form-horizontal">
<div class="row">
<div class="col-sm-4">
<div class="form-group">
<label for="Firstname5" class="col-sm-3">Enter Dish Name</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="Name1" name="Name[]" required data-rule-minlength="2">
</div>
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label for="Firstname5" class="col-sm-3">Enter Dish Price</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="Price" name="Price[]" required data-rule-minlength="2">
</div>
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label for="Firstname5" class="col-sm-3">Select Food Type</label>
<div class="col-sm-8">
<select id="select1" class="form-control" name="select[]" required>
#foreach($types as $type)
<option value="{{$loop->iteration}}">{{$type->food_type_name}}</option>
#endforeach
</select>
<p class="help-block" data-toggle="tooltip" data-placement="bottom" title="xyz"><i class="md md-info"></i></p>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-4">
<div class="form-group">
<label for="Firstname5" class="col-sm-3">Dish Description</label>
<div class="col-sm-8">
<textarea name="Description[]" id="field-value" class="form-control" rows="1"></textarea>
</div>
</div>
</div>
<div class="col-sm-4 contacts">
<div class="form-group">
<label class="col-sm-3" for="rolename">Add Addons</label>
<div class="col-sm-8">
<select id="dates-field2" class="multiselect-ak form-control" name="addons[0]" id="trigger3" data-role="multiselect" multiple="multiple">
#foreach($addons as $addon)
<option value="{{$addon->addonid}}">{{$addon->addon_name}}</option>
#endforeach
</select>
</div>
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label for="Firstname5" class="col-sm-3">Enter Tags</label>
<div class="col-sm-8">
<input type="text" value="" name="tags[0]" class="form-control" data-role="tagsinput" placeholder="e.g. spicy, healthy" />
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-4">
<div class="col-sm-4">
<div class="checkbox checkbox-styled">
<label><em>Half Plate Price</em>
<input type="checkbox" value="" class="trigger2" id="trigger2" name="question">
</label>
</div>
</div>
<div class="col-sm-4">
<div id="hidden_fields2" class="hidden_fields2" style="display:none;">
<input type="text" id="hidden_field2" name="Price2[]" placeholder="Please Enter" class="form-control">
</div>
</div>
</div>
<div class="col-sm-4">
<div class="col-sm-5">
<div class="checkbox checkbox-styled">
<label><em>Quarter Plate Price</em>
<input type="checkbox" value="" class="trigger" id="trigger" name="question">
</label>
</div>
</div>
<div class="col-sm-4">
<div id="hidden_fields" class="hidden_fields" style="display:none;">
<input type="text" id="hidden_field" name="Price3[]" placeholder="Please Enter" class="form-control">
</div>
</div>
</div>
</div>
<br>
<button class="btn btn-delete" data-toggle="tooltip" data-placement="bottom" title="Delete Field" data-role="remove">
Delete Item
</button>
<button class="btn ink-reaction btn-raised btn-primary" data-toggle="tooltip" data-placement="bottom" title="Add More Field" data-role="add">
Add More Items
</button>
</div>
<!-- /div.form-inline -->
</div>
<!-- /div[data-role="dynamic-fields"] -->
<div class="form-group">
<button type="submit" name="submit" href="#" class="btn ink-reaction btn-raised btn-primary" style="margin-top: -62px;margin-left: 160px;">Submit Items</button>
</div>
<!--end .form-group -->
</form>
The issue is that when I click on the add more item it reflects the multiselect dropdown twice as you see in this image.
I want that if I click on the add more item button it restates the multiselect dropdown as in the first state.
see this jsfiddle.net/akshaycic/svv742r7/7 it will clear all your doubt. on click plus button it is not reflect to "none selected" state it will remain in its initial state.
Any leads would be helpful. Thank you in advance.

Categories

Resources