I am working to solve an ajax issue I have where I am trying to auto populate an amount field based on the selection from the drop down box.
My table is layout as follows (Table name is Otheritemsmapping):
ID | Item | Amount
1 | Item 1 | Amount 1
2 | Item 2 | Amount 2
My modal in my Blade looks like this
<div class="modal fade" id="accountpayModal" tabindex="-1" role="dialog" aria-labelledby="accountpay" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title" id="addaccountModal">Pay from Account of {{$member->first_name}} {{$member->last_name}}</h3>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
{!!Form::open(array('action' => ['AccountController#item'], 'method'=>'POST', 'class'=>'form-horizontal'))!!}
<div class="modal-body">
<input type="hidden" name="member" value="{{$member->id}}">
<label class="label-control">Item:</label>
<div class="input-group">
<div class="form-group">
<select type="text" class="selectpicker" data-sytle="select-with-transition" name="item" value="C" id="selectBox">
#foreach ($otheritems as $o)
<option value ={{$o->item}}>{{$o->item}}</option>
#endforeach
</select>
</div>
</div>
<label class="label-control">Amount:</label>
<div class="form-group">
<div class="input-group">
<input type="text" class="form-control" name="amount" id="textField">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-round btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-round btn-primary">Save Changes</button>
</div>
{!!Form::close()!!}
</div>
</div>
</div>
I have the following JS in the same file as the above modal
<script>
$('#selectBox').change(function() {
var id = $(this).val();
var url = '{{ route("getPayments", ":id") }}';
url = url.replace(':id', id);
$.ajax({
url: url,
type: 'get',
dataType: 'json',
success: function(response) {
if (reponse != null) {
$('textField').val(response.amount);
}
}
});
});
</script>
I have the following on the Controller for getPayments
public function getPayments($id = 0)
{
$data = Otheritemmapping::where('item', $id)->first();
return response()->json($data);
}
I have added the following to my Web.php file
Route::get('get/payments/{id}', 'MemberController#getPayments')->name('getPayments');
However when selecting an item from the dropdown ($o->item), the amount is not being populated in the Amount field.
Any help would be great,
Thanks
in your code there's some typos.
<script>
$('#selectBox').change(function() {
let id = $(this).val();
let url = '{{ route("getPayments", ":id") }}';
url = url.replace(':id', id);
$.ajax({
url: url,
type: 'get',
dataType: 'json',
success: function(response) {
if (response != null) {
$('#textField').val(response.amount);
}
}
});
});
</script>
hope this will solve your problem. if still there's anything wrong then check the browser developer console. let me know the error and i will update the answer for you.
you should use id as the option value as id is unique.
Related
I'm new to laravel, I'm trying to achieve a functionality when selecting a year for a specific ID or number that year will be removed from the dropdown list or it will not be listed.
Below I added screenshots and my code so far. I'm actually struggling to figure this out. :(
Please let me know if you need to check my controller.php and others.
Here's my code:
JS:
$(document).ready(function () {
// input fields
$("#tax-dec-form").on('submit', function (e) {
e.preventDefault()
$('#tax-dec-form').find('span.error').remove() //resets error messages
let _url = null;
let data = $('#tax-dec-form').serialize();
if ($('#tax-dec-form').hasClass('new')) {
_url = 'add-tax-info'
data = $('#tax-dec-form').serialize() + "&pin_id=" + pin_id
} else {
_url = 'update-tax-info'
}
$.ajax({
url: _url,
type: "POST",
data: data,
success: function (response) {
if (response.code == 200) {
//console.log(response)
$('#tax-dec-form').removeClass('new');
swal({ title: "Success!", text: response.message, type: "success", buttonsStyling: false, confirmButtonClass: "btn btn-success" })
}
},
error: function (response) {
console.warn(response.responseJSON.errors)
$.each(response.responseJSON.errors, function (field_name, error) {
if ($(document).find('#tax-dec-form [name=' + field_name + ']').next().is('span')) {
$(document).find('#tax-dec-form [name=' + field_name + ']').next('span').remove()
}
$(document).find('#tax-dec-form [name=' + field_name + ']').after('<span class="error text-danger">' + error + '</span>')
})
}
})
})
$('[data-toggle="tooltip"]').tooltip()
})
//for dynamic year list
$(document).ready(function () {
var d = new Date();
for (var i = 0; i <= 40; i++) {
var option = "<option value=" + parseInt(d.getFullYear() + i) + ">" + parseInt(d.getFullYear() + i) + "</option>"
$('[id*=DropDownList1]').append(option);
}
});
Blade.php:
<div class="content menu-css">
<div class="container-fluid">
{{-- upper form here --}}
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header card-header-primary">
<h4 class="card-title">Tax Information</h4>
<p class="card-category">Please complete all fields</p>
</div>
<div class="form-group"> </div>
<div class="card-body">
#if (session('status'))
<div class="row">
<div class="col-sm-12">
<div class="alert alert-success">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<i class="material-icons">close</i>
</button>
<span>{{ session('status') }}</span>
</div>
</div>
</div>
#endif
<div class="form_container">
<form action="/action_page.php" id="tax-dec-form" {{$taxesInfo !== null ? '' : 'class=new'}}>
#csrf
<div class="form-group">
<label for="taxdeclarationnumber">Tax Declaration No:</label>
<input value="{{ $taxesInfo->tax_declaration_number ?? ''}}" type="text" class="form-control" name="tax_declaration_number" placeholder="Input Tax Declaration No..">
</div>
<div class="form-group"> </div>
<div class="form-group">
<label for="current">Current RPT: </label>
<input type="text" value="{{ $taxesInfo->current_rpt ?? ''}}" class="form-control" name="current_rpt" placeholder="Input Current RPT..">
</div>
<div class="form-group">
<label for="years" class="bmd-label-static">Select Tax Declaration Year</label>
<select id="DropDownList1" class="custom-select mr-sm-2" data-style="btn btn-secondary" name="year">
</select>
</div>
</form>
</div>
<div class="clearfix"> </div>
<div id="form-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal" id="btn-save1">Save</button>
</div>
<div class="clearfix"></div>
</div>
</div>
</div>
</div>
</div>
</div>
I'm using Fortify to manage users authentication and I have a modal form for the login. My problem is every time I submit the form I can't see any errors because the page refreshes and closes the modal with the login form.
I would like to know if this validation is possible in the frontend without refreshing the page so the modal won't close. I've tried with Ajax but I can't find the right way to manage this or even in which controller I'm supposed to handle the if statement for the response.
I'll be really thankful if anyone could help me.
Here's my modal:
<!-- LOGIN Modal -->
<form action="{{ route('login') }}" method="post">
#csrf
<div class="modal fade" id="login" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" >
<div class="modal-content">
<div class="modal-header">
<h5>Login</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div class="alert alert-danger print-error-msg" style="display:none">
<ul></ul>
</div>
<div class="mb-3 row">
<div class="col-sm"><br>
<input type="text" class="form-control" name="email" value="Email">
</div>
</div>
<div class="mb-3 row">
<div class="col-sm">
<input type="password" class="form-control" id="inputPassword" name="password" value="Password">
</div>
</div>
<div class="d-grid gap-2">
<button type="submit" id="btn-login" class="btn btn-login">Continuar</button>
</div>
</div>
<div class="modal-footer">
<label><u>Recuperar password</u></label>
</div>
</div>
</div>
</div>
</form>
And here's the Ajax:
$(document).ready(function() {
$("#btn-login").click(function(e) {
e.preventDefault();
var _token = $("input[name='_token']").val();
var email = $("input[name='email']").val();
var password = $("input[name='password']").val();
$.ajax({
url: config.routes.zone,
type: 'POST',
data: { _token: _token, email: email, password:password },
success: function(data) {
if ($.isEmptyObject(data.error)) {
window.location.href = {{ route('login') }};
} else {
printErrorMsg(data.error);
}
}
});
});
function printErrorMsg(msg) {
$(".print-error-msg").find("ul").html('');
$(".print-error-msg").css('display', 'block');
$.each(msg, function(key, value) {
$(".print-error-msg").find("ul").append('<li>' + value + '</li>');
});
}
});
I'm looking for a solution on my problem. I'm using bootstrap4 on laravel project. I have a modal that has a button which close it self and open a new modal. This is the code:
$("#newAddressBtn").on('click', function () {
$('#modalAddressees').modal('hide')
$('#modalAddressees').on('hidden.bs.modal', function () {
// Load up a new modal...
$('#modalNewAddress').modal('show');
})
});
Inside this new modal (modalNewAddress) I have a button that dismiss it. But when I dismiss it, I would to destroy it self because if I need to re-open it again, I would to start with empty data inside (such us the first show).
I wrote this code but nothing happens:
[....]
.on('core.form.valid', function () {
$.ajax({
url: "{{ route("addresses.store") }}",
headers: {'X-CSRF-Token': $('meta[name=_token]').attr('content')},
dataType: "JSON",
data: $("#addressForm").serialize(),
type: "POST",
success: function (data) {
destroyModal("#modalNewAddress");
},
error: function (data) {
console.log('error ' + data);
}
});
});
[....]
function destroyModal(modal){
$(modal).modal('dispose');
}
This is the code of the modal:
<div class="modal fade" tabindex="-1" role="dialog" id="modalNewAddress">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">New Address</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form method="POST" id="addressForm" action="{{ route("addresses.store") }}" class="needs-validation" novalidate="">
{{ csrf_field() }}
<div class="form-group row">
<label for="name" class="col-sm-3 col-form-label">Name</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="name" id="name" value="" placeholder="Name" required="">
</div>
</div>
<span class="float-right">
<button type="submit" id="save" class="btn btn-primary">Save</button>
</span>
<input type="hidden" name="ajax">
</form>
</div>
<div class="modal-footer bg-whitesmoke br">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
How can I solve the problem? Could you please help me?
You're not supposed to destroy the modal but recycle it.
The usage pattern would be as follows:
the modal does not contain data, but data fields you can reach with jQuery, such as:
<div id="adress-nome"></div>
<!-- more fields ... -->
before you open the modal, you populate it with a function, such as:
function updateModal(data)
{
$("#address-nome").val(data.nome);
// more data ...
}
function openModal(data)
{
updateModal(data);
$("#address-modal").modal("show");
}
when you're done with the modal, just hide it
when you re-open it, it will contain the new data
I am using codeigniter framework to develop my project. I am also using AJAX to edit the data. When I edit the first data it is being edited correctly but when I am updating the second data without refreshing the browser then previous edited data or current editing data both are updated with new result. Please solve my problem. Thanks in advance.
function editFunction(id)
{
$.ajax({
url: "edit_result/" +id,
data: {id:id},
type: "post",
async: false,
dataType: 'json',
success: function(response){
$('#reg_no').val(response.reg);
$('#total_marks').val(response.tot_marks);
$('#grade').val(response.grade);
},
error: function()
{
alert("error");
}
});
$('#updateBtn').click(function(event){
event.preventDefault();
var grade_id = document.getElementById("grade").value;
var total_id = document.getElementById("total_marks").value;
if(grade_id=='' || total_id=='')
{
$('#updateBtn').prop('disabled',true);
setTimeout(function(){document.getElementById("updateBtn").disabled = false;},2000);
$('.message').html('Please fill all fields').fadeIn().delay(1000).fadeOut('slow');;
}
else
{
$.ajax({
url: "edit_result_valid/" +id,
data: $(this).serialize(),
type: "post",
async: false,
dataType: 'json',
success: function(response){
alert('success');
},
error: function()
{
alert("error");
}
});
}
});
}
I am performing edit operation on modal. Please check also HTML code
<div class="modal fade" id="editModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span></button>
<h2 class="modal-title">Edit Result</h2>
<p class="message" style="color: red;"></p>
</div>
<div class="modal-body">
<form role="form" id="updateForm">
<div class="box-body">
<div class="form-group">
<label for="exampleInputEmail1">Reg No :</label>
<input type="text" class="form-control" id="reg_no" readonly="">
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label>Total Marks :</label>
<input type="number" class="form-control" id="total_marks" placeholder="Enter total marks" onfocus="colorFunction(this)" name="tot_marks">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label>Grade</label>
<?php
$firstItem[''] = 'Please select one...';
$options = array(
'A++' => 'A++ (90% & above)',
'A+' => 'A+ (80% to 89%)',
'A' => 'A (60% to 79%)',
'B+' => 'B+ (50% to 59%)',
'B' => 'B (40% to 49%)',
);
$options = array_merge($firstItem, $options);
$selected_option = $this->input->post('grade', TRUE);
echo form_dropdown('grade', $options,$selected_option,['class'=>'form-control','id'=>'grade','onfocus'=>'colorFunction(this)']); ?>
</div>
</div>
</div>
</div>
<!-- /.box-body -->
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger pull-left" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-success pull-right" data-dismiss="modal" id="updateBtn">Update</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
I have got an answer of my question. I am using off('click') in code you can see update code below.
$('#updateForm').off('click','#updateBtn').on('click','#updateBtn',function(event){
event.preventDefault();
var grade_id = document.getElementById("grade").value;
var total_id = document.getElementById("total_marks").value;
if(grade_id=='' || total_id=='')
{
$('#updateBtn').prop('disabled',true);
setTimeout(function(){document.getElementById("updateBtn").disabled = false;},2000);
$('.message').html('Please fill all fields').fadeIn().delay(1000).fadeOut('slow');;
}
else
{
$.ajax({
url: "edit_result_valid/" +id,
data: $("#updateForm").serialize(),
type: "post",
async: false,
dataType: 'json',
success: function(response){
if(response=='1')
{
$('.alert-success').show();
$('.alert-success').html('Result Updated Successfully').fadeIn().delay(4000).fadeOut('slow');
$('#example1').DataTable().ajax.reload();s
}
},
error: function()
{
alert("error");
}
});
}
});
play a game at view first. i guess you are not using primary key of db to update. let me explain.
at view:
at one more input element which type is hidden and has value your primary key . assign it an id having value tbl_id example
<input type="hidden" value="<?php echo {variable that has your primary key } ?>" id="tbl_id" >
and at ajax call before you start writing it
var id = $("#tbl_id").val();
when you call controller check you have id available or not
next you are going to call a model to update.
that is where your other all data get update.
when you are going to call model use statement before it
if($id != '') { // $id is what you have shared via ajax call
$this->model_name->update_function($id,$array); // $array is all other fields as per codeigniter need
} else { echo "unable to capture id"; exit; }
and last you update model..
all done by ajax :)
the following is the modal which is invoked on button click
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Compose New Task</h4>
</div>
<div class="modal-body db">
<div class="form-group db">
<label class="col-sm-6 control-label">Current Password </label>
<div class="col-sm-6">
<input type="password" id="current_password" class="form-control">
</div>
</div>
<div class="form-group">
<label class="col-sm-6 control-label">New Password </label>
<div class="col-sm-6">
<input type="password" id="new_password" class="form-control">
<input type="hidden" value="{{ csrf_token() }}" id="csrftoken">
</div>
</div>
<div class="form-group">
<div class="error" id="message"></div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="updatePassword">Save changes</button>
</div>
</div>
</div>
Relevant line in the above code is number 11
$("#updatePassword").click(function () {
var current_password = document.getElementById('current_password').value;
var new_password = document.getElementById('new_password').value;
var token = document.getElementById('csrftoken').value;
$.post('/modalupdatePassword', {'current_password': current_password, 'new_password': new_password, '_token': token}, function (data) {
var parsed = JSON.parse(data);
console.log(parsed);
$('#message').append(parsed);
});
});
and this is my modalPasswordUpdate function
public function modalUpdate(Request $request)
{
$current_password = bcrypt($request->current_password);
$updateRequest = User::where('id', Auth::user()->id)
->where('password', $current_password)
->first();
echo json_encode($current_password);
}
Now every time I send the request I am getting different hash
following is my updated code
Route::get('check', function()
{
echo $password = Hash::make('secret');
});
this also returns new password everytime
You are sending your request via post. Laravel documentation states, that the VerifyCsrfToken middleware will look for X-CSRF-TOKEN request headers during post requests, so do try the following.
Add the token to a meta tag in the head of your document.
<meta name="csrf-token" content="{{ csrf_token() }}" />
Now add the X-CSRF-TOKEN as a header to the global ajax settings like so
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Now all AJAX requests will automatically include the CSRF token.
You can read more about this on the Laravel docs right here.