Activate JS functionality on clone two inputs fields - php

i have a form with various fields, and a pair of buttons of clone and remove the cloned part of the form.
Also, i have in those fields a pair of inputs of integers that when i click in one of them
the value "jump" to the other field when clicked.
The problem is when i clone the form the functionality of "jump" do not attach to the other cloned inputs.
this is the clone function :
var regex = /^(.+?)(\d+)$/i;
var cloneIndex = 1;//$(".clonedInput").length;
function clone(){
cloneIndex++;
$(this).parents(".clonedInput").clone()
.appendTo("form")
.attr("id", "clonedInput" + cloneIndex)
.find("*")
.each(function() {
var id = this.id || "";
var match = id.match(regex) || [];
if (match.length == 3) {
this.id = match[1] + (cloneIndex);
//console.log(this.val);
//this.value = $(match).val();
//console.log("El valor seleccionado es ");
//this.val = match[1].val;
}
})
.on('click', 'button.clone', clone)
.on('click', 'button.remove', remove);
return false;
}
function remove(){
if($('.actions').length == 2){
console.log('accion cancelada');
}else{
$(this).parents(".clonedInput").remove();
}
return false;
}
$("button.clone").on("click", clone);
$("button.remove").on("click", remove);
an approach to this was made with this code using dinamicaly for php
$("input[id^='montoa']").on("click", function(e){
var montoa_id = this.id;
var montob_id = 'montob'+montoa_id.match(/(\d+)/g)[0];
$('#'+montoa_id).value = $('#'+montob_id).val();
$('#'+montob_id).value = '';
});
the inputs are this :
<div class="col-md-1">
<input type="text" name="monto[]" class="form-control" id="montoa1" placeholder="Debe">
</div>
<div class="col-md-1">
<input type="text" name="monto[]" class="form-control" id="montob1" placeholder="Haber">
</div>
and all the n-cloned fields are numbered by auto-increase the id like id="montoa2" and id="montob3" and so on.
all comments wil be very appreciated.
EDIT : Create a jsfiddle https://jsfiddle.net/o63c61sj/

today solved !
This time was add a param to a .clone() function
This because this is a deepWithDataAndEvent clonation event as jquery says.
.clone( [withDataAndEvents ] [, deepWithDataAndEvents ] )
The solution this time for me was clone(true).
Hope someone else could be useful. `
$(document).ready(function() {
$("input[id^='montoa']").attr("placeholder", "dollars");
$("input[id^='montob']").attr("placeholder", "dollars");
$("#montoa1").on('click', function() {
var montoa = $('#montoa1').val();
$('#montoa1').val($('#montob1').val());
$('#montob1').val(0);
});
$("#montob1").on('click', function() {
var montoa = $('#montoa1').val();
$('#montoa1').val(0);
$('#montob1').val(montoa);
});
}
/*
$("input[id^='montoa']").on("click", function(e){
var montoa_id = this.id;
var montob_id = 'montob'+montoa_id.match(/(\d+)/g)[0];
$('#'+montoa_id).value = $('#'+montob_id).val();
$('#'+montob_id).value = '';
});
$("input[id^='montob']").click(function(){
console.log(this.id);
});
*/
);
var regex = /^(.+?)(\d+)$/i;
var cloneIndex = 1; //$(".clonedInput").length;
function clone() {
cloneIndex++;
$(this).parents(".clonedInput").clone(true)
.appendTo("form")
.attr("id", "clonedInput" + cloneIndex)
.find("*")
.each(function() {
var id = this.id || "";
var match = id.match(regex) || [];
if (match.length == 3) {
this.id = match[1] + (cloneIndex);
}
})
.on('click', 'button.clone', clone)
.on('click', 'button.remove', remove);
return false;
}
function remove() {
if ($('.actions').length == 2) {
console.log('accion cancelada');
} else {
$(this).parents(".clonedInput").remove();
}
return false;
}
$("button.clone").on("click", clone);
$("button.remove").on("click", remove);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form action="#" method="post">
<div id="clonedInput1" class="clonedInput">
<div class="form-group row">
<div class="actions">
<div class="panel-group">
<div class="panel panel-primary">
<div class="panel-heading">
<div class="actions">
<button class="clone btn btn-success">Duplicar</button>
<button class="remove btn btn-warning">Quitar</button>
</div>
</div>
<div class="panel-body">
<div class="form-group row">
<div class="col-md-2">
same js functions on all cloned
</div>
<div class="col-md-1">
<input type="text" name="monto[]" class="form-control" id="montoa1" placeholder="Debe">
</div>
<div class="col-md-1">
<input type="text" name="monto[]" class="form-control" id="montob1" placeholder="Haber">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
`

Related

How to get the selected dropdown list in edit modal with Laravel

i am building a project with laravel where i am able to fetch the record from database into my modal but the problem is everytime do i update my modal then the options values in both the select also gets incremented with the same fetched result. How to avoid that. Here i am pasting two images before and after of edit and also what i have done till now. Please help me to complete it.
Before Image
After Image
My modal part
Edit
<div class="modal" id="editModal" tabindex="-1" role="dialog" aria-labelledby="insertModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title font-weight-bold" id="insertModalLabel">EditCustomer</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p><b>Please note:</b> Fields marked with <span class="control-label"></span> is mandatory</p>
<form action="{{ url('admin/update_product') }}" method="post" class="edit_database_operation">
#csrf
<input class="form-control" type="hidden" name="eid" id="eid">
{{-- <input class="form-control" type="hidden" name="brand_id" id="brand_id">
<input class="form-control" type="hidden" name="category_id" id="category_id"> --}}
<div class="form-row">
<div class="form-group col-md-6">
<label for="eproduct_category" class="control-label">Product Category</label>
<select id="eproduct_category" class="form-control" name="eproduct_category">
</select>
</div>
<div class="form-group col-md-6">
<label for="eproduct_brand" class="control-label">Product Brand</label>
<select id="eproduct_brand" class="form-control" name="eproduct_brand">
</select>
</div>
</div>
<button type="submit" class="btn btn-primary text-left">Submit</button>
</form>
</div>
</div>
</div>
</div>
The script part
$(document).on('click','.edit_product',function(e){
e.preventDefault();
var url = $(this).attr('data-href');
console.log(url);
$.ajax({
url:url,
method:"GET",
success:function(fb){
var resp = $.parseJSON(fb);
console.log(resp);
$('#eid').val(resp.id);
var brand_id = resp.brand_id;
brand_edit(brand_id);
var category_id = resp.category_id;
category_edit(category_id);
}
});
return false;
});
function brand_edit(brand_id){
url = '/admin/edit_product_brand/'+brand_id;
console.log(url);
$.ajax({
url:url,
method:"GET",
success:function(fb){
console.log(fb);
$('#eproduct_brand').append(fb);
}
});
return false;
}
function category_edit(category_id){
url = '/admin/edit_product_category/'+category_id;
console.log(url);
$.ajax({
url:url,
method:"GET",
success:function(fb){
console.log(fb);
$('#eproduct_category').append(fb);
}
});
return false;
}
$(document).on('submit','.edit_database_operation',function(e){
e.preventDefault();
var url = $(this).attr('action');
var data = $(this).serialize();
$.ajax({
url:url,
method:"POST",
data:data,
success:function(fb){
var resp = $.parseJSON(fb);
// console.log(resp);
if(resp.status=='true'){
toastr.success(resp.message,'Success');
$('#editModal').modal('hide');
$('.edit_database_operation')[0].reset();
$("#example1").load(" #example1 > *");
$("#example2").load(" #example2 > *");
// $('.edit_database_operation')[0].reset();
$("#eproduct_category").data("default-value",$("#eproduct_category").val());
}else if(resp.status=='false'){
$.each( resp.message, function( key , value ) {
toastr.error(value + '<br>','Error');
});
}else if(resp.status=='false-1'){
toastr.error(resp.message,'Error');
}
}
});
return false;
});
The Controller part
public function product_edit($id){
$edit = Product::where('id',$id)->first();
$arr = array('id'=>$edit->id,'category_id'=>$edit->category_id,'brand_id'=>$edit->brand_id);
echo json_encode($arr);
}
public function edit_product_brand($id){
$brande = Brand::where('status','active')->orderBy('id','DESC')->get();
$output = '';
// $output .= '';
foreach ($brande as $brand){
$brand_id = $brand->id;
$brand_name = $brand->brand_name;
$output .= '<option value="'.$brand_id.'" '.(($brand_id == $id) ? 'selected="selected"':"").'>'.$brand_name.'</option>';
}
// $output .='</select>';
return $output;
}
public function edit_product_category($id){
$category = Category::where('status','active')->orderBy('id','DESC')->get();
$output = '';
if(!$category->isEmpty()){
foreach ($category as $brand){
$category_id = $brand->id;
$category_name = $brand->category_name;
$output .= '<option value="'.$category_id.'" '.(($category_id == $id) ? 'selected="selected"':"").'>'.$category_name.'</option>';
}
}
return $output;
}
public function update_product(Request $request){
$update = Product::where('id',$request->eid)->first();
$validator = Validator::make($request->all(),
[
'eproduct_category'=>'required',
'eproduct_brand'=>'required',
],[
'eproduct_category.required'=>'Please enter product category',
'eproduct_brand.required'=>'Please enter product brand',
]);
if(!$validator->fails()){
$update->name = $request->eproduct_name;
$update->category_id = $request->eproduct_category;
$update->brand_id = $request->eproduct_brand;
if($update->update()){
$arr = array('status'=>'true','message'=>'Updated Successfully');
}else{
$arr = array('status'=>'false-1','message'=>'Not Updated');
}
}else{
$arr = array('status'=>'false','message'=>$validator->errors()->all());
}
echo json_encode($arr);
}
In your jquery code you have use .append() to append new options inside your select-box which just insert new elements to the end of each element in the set of matched elements.So that's the reason it was showing double values.
Instead use .html() to replace all element which are there inside your select-box. So you just need to change :
$('#eproduct_brand').append(fb);
To
$('#eproduct_brand').html(fb);
Same you do for eproduct_category as well.

Problem to insert into mysql with ajax and php

I want to insert in 2 tables of mysql, one table is about information of a product and the other one is for the images of those products.
I have this form
<form action="#" method="post" enctype="multipart/form-data" id="upload-multi-images">
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control" required autocomplete="off">
</div>
<div class="form-group">
<label>Price</label>
<input type="text" name="price" class="form-control" required autocomplete="off">
</div>
<div class="form-group">
<label>Stock</label>
<input type="text" name="stock" class="form-control" required autocomplete="off">
</div>
<div class="row">
<div class="col-xl-2 col-lg-2 col-md-3 col-sm-4 col-xs-12" id="add-photo-container">
<div class="add-new-photo first" id="add-photo">
<span><i class="icon-camera"></i></span>
</div>
<input type="file" multiple id="add-new-photo">
</div>
</div>
<div class="button-container">
<button type="submit">Subir imágenes</button>
</div>
</form>
I get the images and the information with this JS
$(document).on("submit", "#upload-multi-images", function (e) {
e.preventDefault();
$(document).on("submit", "#upload-multi-images", function (e) {
var namePro = document.getElementsByName('name')[0].value;
var price = document.getElementsByName('price')[0].value;
var stock = document.getElementsByName('stock')[0].value;
formData.append('namePro', namePro);
formData.append('price', price);
formData.append('stock', stock);
e.preventDefault();
//Envio mediante Ajax
$.ajax({
url: "upload.php",
type: "post",
dataType: "json",
data: formData,
cache: false,
contentType: false,
processData: false,
beforeSend: function () {
loading(true, "Adding photo...");
},
success: function (res) {
loading(false);
if (res.status == "true") {
createImages(res.all_ids);
$("#Images form .row > div:not(#add-photo-container)").remove();
formData = new FormData();
} else {
alert(res.error);
}
},
error: function (e) {
console.log(e.responseText);
}
});
});
Then y send the images to this php to send them to mysql
$namePRO = $_REQUEST['namePro'];
$price = $_REQUEST['price'];
$stock = $_REQUEST['stock'];
$insertDatos = $conexion->prepare("INSERT INTO products (name , price, stock) VALUES (:name, :price, :stock)");
$wasUploadedDATA = $insertDatos->execute(array(
":name" => $namePRO,
":price" => $price,
":stock" => $stock,
));
$idPRO = $conexion->lastInsertId();
if (isset($_FILES) && !empty($_FILES)) {
$files = array_filter($_FILES, function($item) {
return $item["name"][0] != "";
});
foreach ($files as $file) {
$tmp_name = $file["tmp_name"];
$name = $file["name"];
$path = "/images/$name";
$pathSYS = "/var/www/html/images/$name";
$insertImages = $conexion->prepare("INSERT INTO product_files (id_pro, name, web_path, system_path) VALUES (:idPRO, :name, :path, :pathSYS)");
$wasUploaded = $insertImages->execute(array(
":name" => $name,
":idPRO" => $idPRO,
":path" => $path,
":pathSYS" => $pathSYS,
));
if ($wasUploaded) {
$id = $conexion->lastInsertId();
$data["all_ids"]["id_$id"]["id"] = $id;
$data["all_ids"]["id_$id"]["name"] = $name;
move_uploaded_file($tmp_name, "images/$name");
}
else {
die("There was an error. Please contact with the admin.");
}
}
}
I also have these other JS but I think they are not very important
function getRandomString(length) {
var text = "";
var possible =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < length; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
function createPreview(file, id) {
var imgCodified = URL.createObjectURL(file);
var img = $('<div class="col-xl-2 col-lg-2 col-md-3 col-sm-4 col-xs-12"
id="'
+ id + '"><div class="image-container"> <figure> <img src="' + imgCodified +
'" alt="Foto del usuario"> <figcaption> <i class="icon-cross"></i>
</figcaption> </figure> </div></div>');
$(img).insertBefore("#add-photo-container");
}
function createImages(all_ids) {
for (const key in all_ids) {
var image = all_ids[key];
var img = $('<div class="col-xl-2 col-lg-2 col-md-3 col-sm-4 col-xs-12"
data-id="' + image.id + '"><div class="image-container"> <figure> <img
src="images/' + image.name + '" alt="Foto del usuario"> <figcaption> <i
class="icon-cross"></i> </figcaption> </figure> </div></div>');
$("#my-images").append(img);
}
}
function showModal(card) {
$("#" + card).show();
$(".modal").addClass("show");
}
function closeModal() {
$(".modal").removeClass("show");
setTimeout(function () {
$(".modal .modal-card").hide();
}, 300);
}
function loading(status, tag) {
if (status) {
$("#loading .tag").text(tag);
showModal("loading");
}
else {
closeModal();
}
}
function showMessage(message) {
$("#Message .tag").text(message);
showModal("Message");
}
I don't have all of your code, but I've identified the issue in your code and I'll just add add the fix here for you.
First of all, if you are using jquery, it's better to write your code in a unified format and use jquery everywhere and not switch between jquery and plain JavaScript.
Having that said, instead of using document.getElementsByName you can easily add id attribute to your html element and access them with $('#<id>') way in jquery.
Second, even if you are using javascript to grab your html element data, what you are doing is wrong. var namePro = document.getElementsByName('name'); will select the whole html <input> object and not it's value. So you have to change it to: document.getElementsByName("name")[0].value
So you have 2 options:
1- Use what you have already and just change it a bit to:
var namePro = document.getElementsByName('name')[0].value;
var price = document.getElementsByName('price')[0].value;
var stock = document.getElementsByName('stock')[0].value;
2- Or for switching to jquery, you need to add id to all of these elements in your html:
<div class="form-group">
<label>Name</label>
<input type="text" id="name" name="name" class="form-control" required autocomplete="off">
</div>
<div class="form-group">
<label>Price</label>
<input type="text" id="price" name="price" class="form-control" required autocomplete="off">
</div>
<div class="form-group">
<label>Stock</label>
<input type="text" id="stock" name="stock" class="form-control" required autocomplete="off">
</div>
And then change you JavaScript to:
formData.append('name', $('#name').val());
formData.append('price', $('#price').val());
formData.append('stock', $('#stock').val());
Update:
The sample code which works on my machine is like this:
HTML:
<form action="#" method="post" enctype="multipart/form-data" id="upload-multi-images">
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control" required autocomplete="off">
</div>
<div class="form-group">
<label>Price</label>
<input type="text" name="price" class="form-control" required autocomplete="off">
</div>
<div class="form-group">
<label>Stock</label>
<input type="text" name="stock" class="form-control" required autocomplete="off">
</div>
<div class="row">
<div class="col-xl-2 col-lg-2 col-md-3 col-sm-4 col-xs-12" id="add-photo-container">
<div class="add-new-photo first" id="add-photo">
<span><i class="icon-camera"></i></span>
</div>
<input type="file" multiple id="add-new-photo">
</div>
</div>
<div class="button-container">
<button type="submit">Subir imágenes</button>
</div>
</form>
JS #1:
var formData = new FormData();
$(document).ready(function(){
$(".modal").on("click", function (e) {
console.log(e);
if (($(e.target).hasClass("modal-main") || $(e.target).hasClass("close-modal")) && $("#loading").css("display") == "none") {
closeModal();
}
});
$(document).on("click", "#add-photo", function(){
$("#add-new-photo").click();
});
$(document).on("change", "#add-new-photo", function () {
var files = this.files;
var element;
var supportedImages = ["image/jpeg", "image/png", "image/gif"];
var InvalidElementFound = false;
for (var i = 0; i < files.length; i++) {
element = files[i];
if (supportedImages.indexOf(element.type) != -1) {
var id = getRandomString(7);
createPreview(element, id);
formData.append(id, element);
}
else {
InvalidElementFound = true;
}
}
if (InvalidElementFound) {
showMessage("Invalid Elements Found.");
}
else {
showMessage("All the files were uploaded succesfully.");
}
});
$(document).on("click", "#Images .image-container", function(e){
var parent = $(this).parent();
var id = $(parent).attr("id");
formData.delete(id);
$(parent).remove();
});
$(document).on("submit", "#upload-multi-images", function (e) {
e.preventDefault();
var namePro = document.getElementsByName('name')[0].value;
var price = document.getElementsByName('price')[0].value;
var stock = document.getElementsByName('stock')[0].value;
formData.append('namePro', namePro);
formData.append('price', price);
formData.append('stock', stock);
//Envio mediante Ajax
$.ajax({
url: "upload.php",
type: "post",
dataType: "json",
data: formData,
cache: false,
contentType: false,
processData: false,
beforeSend: function () {
loading(true, "Adding photo...");
},
success: function (res) {
console.log('success');
console.log(res);
loading(false);
if (res.status == "true") {
createImages(res.all_ids);
$("#Images form .row > div:not(#add-photo-container)").remove();
formData = new FormData();
} else {
alert(res.error);
}
},
error: function (e) {
console.log('error');
console.log(e.responseText);
}
});
});
$(document).on("click", "#MyImages .image-container", function (e) {
var parent = $(this).parent();
var id = $(parent).attr("data-id");
var data = {
id : id
}
$.post("delete.php", data, function(res) {
if (res == "true") {
showMessage("¡Images successfully removed!");
$(parent).remove();
}
else {
showMessage("Sorry, there was an error uploading the images.");
}
});
});
});
JS #2:
function getRandomString(length) {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < length; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
function createPreview(file, id) {
var imgCodified = URL.createObjectURL(file);
var img = $('<div class="col-xl-2 col-lg-2 col-md-3 col-sm-4 col-xs-12" id="'+ id + '"><div class="image-container"> <figure> <img src="' + imgCodified + '" alt="Foto del usuario"> <figcaption> <i class="icon-cross"></i></figcaption> </figure> </div></div>');
$(img).insertBefore("#add-photo-container");
}
function createImages(all_ids) {
for (const key in all_ids) {
var image = all_ids[key];
var img = $('<div class="col-xl-2 col-lg-2 col-md-3 col-sm-4 col-xs-12" data-id="' + image.id + '"><div class="image-container"> <figure> <img src="images/' + image.name + '" alt="Foto del usuario"> <figcaption> <i class="icon-cross"></i> </figcaption> </figure> </div></div>');
$("#my-images").append(img);
}
}
function showModal(card) {
$("#" + card).show();
$(".modal").addClass("show");
}
function closeModal() {
$(".modal").removeClass("show");
setTimeout(function () {
$(".modal .modal-card").hide();
}, 300);
}
function loading(status, tag) {
if (status) {
$("#loading .tag").text(tag);
showModal("loading");
}
else {
closeModal();
}
}
function showMessage(message) {
$("#Message .tag").text(message);
showModal("Message");
}
PHP: (upload.php)
$arr_ajax = array();
$arr_ajax['namePro'] = $_REQUEST['namePro'];
$arr_ajax['price'] = $_REQUEST['price'];
$arr_ajax['stock'] = $_REQUEST['stock'];
if (isset($_FILES) && !empty($_FILES)) {
$files = array_filter($_FILES, function($item) {
return $item["name"][0] != "";
});
$iCnt = 0;
foreach ($files as $file) {
$arr_ajax['Filename'.$iCnt] = $file["name"];
$iCnt++;
}
}
echo json_encode($arr_ajax);
And with this code, when I click on Submit button, I get the following response in my browser console:
index.html:79 success
index.html:80 {namePro: "Test Product", price: "100.00", stock: "15", Filename0: "faces1.jpg"}

Remove NaN from the total field while function is adding the two inputs together

I am adding two fields together to get the total but when i type into the first field the total field shows NaN which i need it not to. I have tried 5 different options to resolve this issue but none seem to remove NaN while the function runs.
$j(function() {
var new_fees = 0.00;
var referral_fees = 0.00;
$j('#new_fees').keyup(function() {
updateTotal();
});
$j('#referral_fees').keyup(function() {
updateTotal();
});
var net_fees=parseFloat($j('#net_fees').val());
if(isNaN(net_fees)){
net_fees=0;
}
var updateTotal = function () {
new_fees = parseFloat($j('#new_fees').val());
referral_fees = parseFloat($j('#referral_fees').val());
$j('#net_fees').val(new_fees + referral_fees);
var output_total = $j('#net_fees');
var total = new_fees + referral_fees;
output_total.val(total);
};
});
Here is the fiddle link but it doesn't seem to work at all in fiddle where as it does on my page
I updated your "updateTotal" method, please try it.
var updateTotal = function () {
new_fees = parseFloat($('#new_fees').val());
referral_fees = parseFloat($('#referral_fees').val());
$('#net_fees').val(new_fees + referral_fees);
var output_total = $('#net_fees');
var total = new_fees + referral_fees;
if(isNaN(total)){
total=0;
}
output_total.val(total);
};
try https://jsfiddle.net/ydLtcrya/1/
Try this
var new_fees = $("#new_fees").val();
var referral_fees = $("#referral_fees").val();
$('#new_fees').keyup(function() {
updateTotal();
});
$('#referral_fees').keyup(function() {
updateTotal();
});
var updateTotal = function () {
new_fees = parseFloat($('#new_fees').val());
referral_fees = parseFloat($('#referral_fees').val());
if(isNaN(new_fees))
net_fees=0;
if(isNaN(referral_fees))
referral_fees=0;
$('#net_fees').val(new_fees + referral_fees);
var output_total = $('#net_fees');
var total = new_fees + referral_fees;
if(isNaN(total ))
total=0.00;
output_total.val(total);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-xs-12 col-sm-2 nopadding">
<label for="template_range" class="col-xs-11 col-sm-11 col-md-11 col-lg-11 nopadding">New Fees<br><small>(net)</small></label>
<input type="text" class=" col-xs-5 form-control" id="new_fees" placeholder="0.00">
</div>
<div class="col-xs-12 col-sm-2 nopadding">
<label for="template_range" class="col-xs-11 col-sm-11 col-md-11 col-lg-11 nopadding">Referral Fees<br> <small>(net)</small></label>
<input type="text" class="col-xs-5 form-control" id="referral_fees" placeholder="0.00" >
</div>
<div class="col-xs-12 col-sm-2 nopadding">
<label for="template_range" class="col-xs-11 col-sm-11 col-md-11 col-lg-11 nopadding">Total Fees <br><small>(net)</small></label>
<input type="text" class="col-xs-5 form-control" value="0.00" id="net_fees" readonly>
</div>
<div class="col-xs-12 col-sm-2 nopadding">
<label for="template_range" class="col-xs-11 col-sm-11 col-md-11 col-lg-11 nopadding">Total Fees <br><small>(gross)</small></label>
<input type="text" class="col-xs-5 form-control" value="0.00" id="gross_fees" readonly>
</div>
You could default to 0 if the parseFloat return NaN
var updateTotal = function () {
new_fees = parseFloat($j('#new_fees').val()) || 0;
referral_fees = parseFloat($j('#referral_fees').val()) || 0;
$j('#net_fees').val(new_fees + referral_fees);
var output_total = $j('#net_fees');
var total = new_fees + referral_fees;
output_total.val(total);
};

How to use returned json response in view - laravel 5.2

I am using Laravel 5.2 + angularjs.
GOAL : Have to submit a form which have only check boxes. Based on the check box selected check box id fetch the data and return to the view. This returned data will be displayed in other div of same page.
For Example : Form is in div1 and returned data should be displayed in div2, div3 and div4. Only one division will be displayed on the view rest are hidden.
FINALLY - I am able to hide and display divisions using angular and I am able to submit the form which is in div1 using ajax. But I am unable to get the data back to the view from controller (data is returned in json format) and display on other divisions.
How can I display the returned response json object on the view ?
Below is my code :
Route :
Route::group(['middleware' => ['web']], function () {
Route::get('/form', 'PublicController#index'); // View will be displayed by using this method
Route::post('/form','PublicController#show'); // Form is submitted and data is returned using this "show" method
});
Controller :
class PublicController extends Controller
{
public function index(){
$crimetypes = crimetype::get();
$step1='';$step2='';$step3='';$step4='';$step5='';
return view('frontend.form')->withCrimetypes($crimetypes)->withStep1($step1)->withStep2($step2)->withStep3($step3)->withStep4($step4)->withStep5($step5);
}
public function show(Request $request, QuestionsRepository $questionsRepository){
$data = $questionsRepository->returnSteps($request);
$step1 = $data[0];
$step2 = $data[1];
$step3 = $data[2];
$step4 = $data[3];
$step5 = $data[4];
// Data is successfully coming till here...
return response()->json(['step1'=>$step1, 'step2'=>$step2, 'step3'=>$step3, 'step4'=>$step4, 'step5'=>$step5],200);
// Here it is not allowing to use any other return type other than response json..
}
}
View :
<div ng-show="div1">
<div>
{!! Form::open(array('method'=>'POST','url'=>'/form','id'=>'formid'))!!}
<div class="col-md-12 row">
<h2>Step - 1</h2>
<hr>
<br><p>Please select the relevant check boxes below.</p>
</div>
#foreach($crimetypes as $crimeType)
<div class="col-md-4">
<ul class="list-unstyled">
<li>
<div class="checkbox">
<label>
<input value="{{$crimeType->id}}" type="checkbox" name="id[]" id="checkid"> {{$crimeType->type}}
</label>
</div>
</li>
</ul>
</div>
#endforeach
<div class="col-md-12 row">
<div class="form-group">
<br>
<hr>
<input type="submit" ng-click="click1()" value="Next" class="btn btn-default">
</div>
</div>
{!!Form::close()!!}
</div>
</div>
<!-- On submitting above form hide the above div and display below div...this is working fine..-->
<div ng-show="div2">
<div class="col-md-12 row">
<h2>Step - 2 : Crime Details</h2>
<hr>
<h3>Can You Tell Us About The Crime</h3>
<br>
<h5><strong>#if (!empty($step1[0])) ? {{$step1[0]->question}} : ''#endif?</strong></h5>
<div class="row">
<div class="control-group">
<div class="form-group col-md-3">
<input type="number" class="form-control nbr" placeholder="xxx-xxx-xxx">
</div>
<div class="col-md-9"></div>
</div>
</div>
<h5><strong>#if (!empty($step1[1])) ? {{$step1[1]->question}} : ''#endif?</strong></h5>
<div class="row">
<div class="control-group">
<div class="form-group col-md-3">
<input type="number" class="form-control nbr" placeholder="xxx-xxx-xxx">
</div>
<div class="col-md-9"></div>
</div>
</div>
<h5><strong>#if (!empty($step1[2])) ? {{$step1[2]->question}} : ''#endif?</strong></h5>
<div class="row">
<div class="control-group">
<div class="form-group col-md-3">
<input type="textarea" class="form-control nbr">
</div>
<div class="col-md-9"></div>
</div>
</div>
<div class="row">
<br>
<hr>
<div class="form-group col-md-2">
<button ng-click="click2()" class="btn btn-default">Next</button>
</div>
<div class="form-group col-md-offset-10">
<button ng-click="click2()" class="btn btn-primary">Skip</button>
</div>
</div>
</div>
</div>
<!-- Similarly there are three more div's where I have to display the fetched data...-->
Script :
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('[name="_token"]').val()
}
});
$(document).ready(function(){
$('#formid').on('submit', function(e){
e.preventDefault();
var id = new Array();
$('input[name="id[]"]:checked').each(function()
{
id.push($(this).val());
});
var $form = $('form');
$.ajax({
url:$form.attr('url'),
type: $form.attr('method'),
data: {id},
dataType:'json',
success: function(data){
var step1 = data.step1;
var step2 = data.step2;
var step3 = data.step3;
var step4 = data.step4;
var step5 = data.step5;
// If I use success, I am able to get data to these variables but unable to make use them on view wherever required. But now I am trying to use the returned object directly on the view without callback in the ajax. Even by using callback if it is possible, please help me out...
}
});
});
});
</script>
I solved my problem, here is the code I changed/added :
AngularJs Files :
formCtrl.js :
angular.module('formCtrl', []).controller('formController', function($scope, $http, Comment){
Comment.get().success(function(data){
$scope.crimeTypes = data[0];
});
$scope.div1 = true;
$scope.div2 = false;
$scope.div3 = false;
$scope.div4 = false;
$scope.div5 = false;
$scope.div6 = false;
$scope.div7 = false;
$scope.selected = {};
$scope.click1 = function(data){
var id = [];
for(var i in data){
if(data[i].selected==true){
id.push(data[i].id);
}
}
$scope.selected = {id};
$http({
method : 'POST',
url : '/index1',
data : $.param($scope.selected),
headers :{'Content-Type':'application/x-www-form-urlencoded'}
})
.success(function(data) {
console.log(data);
});
$scope.div1 = false;
$scope.div2 = true;
$scope.div3 = false;
$scope.div4 = false;
$scope.div5 = false;
$scope.div6 = false;
$scope.div7 = false;
};
$scope.click2 = function(){
$scope.div1 = false;
$scope.div2 = false;
$scope.div3 = true;
$scope.div4 = false;
$scope.div5 = false;
$scope.div6 = false;
$scope.div7 = false;
};
$scope.click3 = function(){
$scope.div1 = false;
$scope.div2 = false;
$scope.div3 = false;
$scope.div4 = true;
$scope.div5 = false;
$scope.div6 = false;
$scope.div7 = false;
};
$scope.click4 = function(){
$scope.div1 = false;
$scope.div2 = false;
$scope.div3 = false;
$scope.div4 = false;
$scope.div5 = true;
$scope.div6 = false;
$scope.div7 = false;
};
$scope.click5 = function(){
$scope.div1 = false;
$scope.div2 = false;
$scope.div3 = false;
$scope.div4 = false;
$scope.div5 = false;
$scope.div6 = true;
$scope.div7 = false;
};
$scope.click6 = function(){
$scope.div1 = false;
$scope.div2 = false;
$scope.div3 = false;
$scope.div4 = false;
$scope.div5 = false;
$scope.div6 = false;
$scope.div7 = true;
};
});
formService.js :
angular.module('formService',[])
.factory('Comment', function($http){
return {
get:function(){
return $http.get('/index1data');
}
}
});
main.js :
var app = angular.module('angularApp', ['mainCtrl','formCtrl','formService'], function($interpolateProvider) {
$interpolateProvider.startSymbol('<%');
$interpolateProvider.endSymbol('%>');
});
No code change in Route and Controller files. In view only changed the div with checkbox class code to as shown below.
Laravel Files :
View :
<div class="checkbox">
<input value="<%crimeType.id%>" type="checkbox" ng-model="crimeType.selected" id="<%crimeType.type%>">
<label for="<%crimeType.type%>"><% crimeType.type %></label>
</div>
NOTE : I didn't used ajax script which I had posted in the question. Controller and Route files are not changed.

How to check if email exist while typing in MYSQL using jQuery, AJAX and CodeIgniter

I want to validate my form's input with database, so when user type on form's input and contain email already in use or exists it will display an alert and cant submit. I use CodeIgniter framework and jQuery.
I've tried using the code below to check if name exists and this could work. But when I apply it to the other case for email, it doesn't work and display message "The URI you submitted has disallowed characters."
How is the correct way to fix this?
View (kasir_halaman.php) :
<div id="addModal" class="modal fade" role="modal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title"><span class="glyphicon glyphicon-plus"></span> Tambah Kasir</h3>
</div>
<div class="modal-body">
<form action="<?php echo site_url('admin/kasir/addpetugas'); ?>" method="post" enctype="multipart/form-data">
<div class="form-group">
<label>Nama</label>
<input type="text" id="nama" name="nama" class="form-control" maxlength="100" required>
</div>
<div class="form-group">
<label>E-mail</label>
<input type="email" id="email" name="email" class="form-control" maxlength="150" required>
</div>
<div class="form-group">
<label>Kategori</label>
<select class="form-control" name="kategoripetugas" required>
<option value=""> -- Pilih Kategori -- </option>
<option value="1">Admin</option>
<option value="2">Kasir</option>
</select>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="password" class="form-control" maxlength="30">
</div>
<div class="form-group">
<label>Ulangi Password</label>
<input type="password" name="confirmpassword" class="form-control" maxlength="30">
</div>
<button type="submit" class="btn btn-primary" style="width:100%;">Tambah</button>
</form>
</div>
</div>
</div>
</div>
Controller (kasir.php) :
public function cekData($table, $field, $data)
{
$match = $this->Crud->read($table, array($field=>$data), null, null);
if($match->num_rows() > 0){
$report = 2;
}else{
$report = 1;
}
echo $report;
}
public function register_email_exists()
{
if (array_key_exists('email',$_POST)) {
if ($this->Crud->email_exists($this->input->post('email')) == TRUE ) {
echo false;
} else {
echo true;
}
}
}
Model (Crud.php) :
function email_exists($email)
{
$this->db->where('email', $email);
$query = $this->db->get('petugas');
if( $query->num_rows() > 0 ){ return TRUE; } else { return FALSE; }
}
jQuery AJAX (petugas.js) :
$(document).ready(function(){
var check1=0; var id;
$("#nama").bind("keyup change", function(){
var nama = $(this).val();
$.ajax({
url:'kasir/cekData/petugas/nama/'+nama,
data:{send:true},
success:function(data){
if(data==1){
$("#report1").text("");
check1=1;
}else{
$("#report1").text("*nama petugas sudah terpakai");
check1=0;
}
}
});
});
var check2=0;
$("#email").bind("keyup change", function(){
//var email = $(this).val();
$.ajax({
url:'kasir/register_email_exists',
data:{send:true},
success:function(data){
if(data==1){
$("#report2").text("");
check2=1;
}else{
$("#report2").text("*email sudah terpakai");
check2=0;
}
}
});
});
var check4=0;
$("#confirmpassword").bind("keyup change", function(){
var password = $("#password").val();
var confirmpassword = $(this).val();
if (password == confirmpassword){
$("#report4").text("");
check4=1;
}else{
$("#report4").text("*Password tidak sama");
check4=0;
}
});
$("#submit").click(function(event){
if(check1==0){
event.preventDefault();
}
if(check4==0){
event.preventDefault();
}
});
});
Use ajax post method instead and take data at php side from POST request
you can check more about jquery ajax here: http://api.jquery.com/jquery.post/
and about php post here: http://php.net/manual/en/reserved.variables.post.php
//JS
$("#email").bind("keyup change", function(){
var email = $(this).val();
$.ajax({
url:'kasir/register_email_exists',
type: "POST",// <---- ADD this to mention that your ajax is post
data:{ send:true, email:email },// <-- ADD email here as pram to be submitted
success:function(data){
if(data==1){
$("#report2").text("");
check2=1;
}else{
$("#report2").text("*email sudah terpakai");
check2=0;
}
}
});
});
// PHP
// At php side take your data from $_POST
$send = $_POST['send'];
$email = $_POST['email'];
...

Categories