Passing values to codeigniter controler through ajax - ajax

I got a problem that's really ruining my life now. I'm trying to pass values to a codeigniter controller through Ajax.
I've read many things about it but I can't find why this is not working.
So I've made a form in a bootstrap modal windows to add a new member. The values are: first name, last name, email and passowrd.
I'm using jQuery validate to verify the infos and then I wanna pass the value to the controller.
$('#addMember form').validate({ // initialize plugin
rules: {
lname: {
required: true,
minlength: 2
},
name: {
required: true,
minlength: 2
},
mail: {
required: true,
email: true
},
password: {
required: true
},
repassword: {
required: true,
equalTo: "#password"
}
},
highlight: function (element) {
$(element).closest('.input-group')
.removeClass('success').addClass('error');
},
success: function (element) {
element.addClass('valid').closest('.input-group')
.removeClass('error').addClass('success');
},
submitHandler: function (form) {
// form validates so do the ajax
var dataString = $(form).serialize();
$.ajax({
type: $(form).attr('method'),
url: $(form).attr('action'),
data: dataString,
success: function (data, status) {
// ajax done
// do whatever & close the modal
alert(status);
$('.modal').modal('hide');
}
});
return false; // ajax used, block the normal submit
}
});
<div id="addMember" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<form id="addMemberForm" method="POST" action="<?php echo base_url('adminMembers/process_add_member');?>">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true"></span></button>
<h4 class="modal-title">Add a new member</h4>
</div>
<div class="modal-body">
<div class="input-group">
<span class="input-group-addon" id="basic-addon1">Last Name</span>
<input name="lname" type="text" class="form-control" placeholder="" aria-describedby="basic-addon1">
</div>
<div class="input-group">
<span class="input-group-addon" id="basic-addon1">First name</span>
<input name="name" type="text" class="form-control" placeholder="" aria-describedby="basic-addon1">
</div>
<div class="input-group">
<span class="input-group-addon" id="basic-addon1">Email</span>
<input name="mail" type="email" class="form-control" placeholder="" aria-describedby="basic-addon1">
</div>
<div class="input-group">
<span class="input-group-addon" id="basic-addon1">Password</span>
<input id="password" name="password" type="password" class="form-control" placeholder="" aria-describedby="basic-addon1">
</div>
<div class="input-group">
<span class="input-group-addon" id="basic-addon1">Password again</span>
<input name="repassword" type="password" class="form-control" placeholder="" aria-describedby="basic-addon1">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-primary" value="add">Add</button>
</div>
</form>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
I got a success message in an alert window so the ajax part is working.
Then I don't know how to use the values in my controller.
If I try to print $this->input->post('lname') I got an empty value.
Any ideas please?
EDIT: Might be useful:
My javascript code is placed right after the </div><!-- /.modal -->.
The function add_Member in my controller looks like:
public function process_add_member()
{
$this->membersManager->add_member();
}
And finally the model:
public function add_member()
{
$name = $this->input->post('name');
$lname = $this->input->post('lname');
$email = $this->input->post('mail');
$password = $this->input->post('password');
return $this->db->set(array('name' => $name,
'lname' => $lname,
'login' => $email,
'email' => $email,
'password' => $password))->insert($this->table);
}
As I said I tried to replace $this->input->post() by $_POST[] but still not working.
To finish I wanna ay that I've tried the same without using AJAX to pass the values and it is working. I need to use AJAX because I want the form to be in a bootstrap modal window.
The thing is that it seems my function process_add_Member() in the controller is not called. I can do anything in it and it won't happen.
Nobody? :( I really don't understand what is not working here.
HELP!
Is there someone that can help me please ?

Since you are passing data using the form serialize method insteading of using $this->input->post() retrieve the post value directly $_POST['<input_name>'] .
Hope this will solve your problem since.

You should use the form_open() helper function in your view, so that the CSRF token is included as a hidden field.
And in general: you should always use the helper functions and classes whenever possible. There is no use in working with a framework if you don't use the provided functions.

Related

Async Method returns 404

I got the following problem.
in my Controller, this method is supposed to return a JSON with the pets from the database. but is being called, the server returns a 404.
public async Task<JsonResult> GetPetsAsync(int ownerId )
{
var pets = await _dataContext.Pets
.Where(p => p.Owner.Id == ownerId)
.OrderBy(p => p.Name)
.ToListAsync();
return Json(pets);
}
=====================================================
This is the form that provides the OwnerId for the method to find the pets for that particular owner.
<div class="row m-auto align-content-center">
<div class="col-md-4">
<form asp-action="Assign" enctype="multipart/form-data">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="Id" />
<div class="form-group">
<label asp-for="OwnerId" class="form-label fw-bold"></label>
<select asp-for="OwnerId" asp-items="Model.Owners" class="form-control"></select>
<span asp-validation-for="OwnerId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="PetId" class="form-label fw-bold"></label>
<select asp-for="PetId" asp-items="Model.Pets" class="form-control"></select>
<span asp-validation-for="PetId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Remarks" class="form-label fw-bold "></label>
<textarea asp-for="Remarks" class="form-control"></textarea>
<span asp-validation-for="Remarks" class="text-danger"></span>
</div>
<div class="form-group mt-3">
<button value="Assign" type="submit" class="btn btn-primary btn-sm"><i class="bi bi-calendar-plus-fill"></i></button>
<a asp-action="Index" class="btn btn-success btn-sm"><i class="bi bi-arrow-return-left"></i> Go Back</a>
<span asp-validation-for="Remarks" class="text-danger"></span>
</div>
</form>
</div>
</div>
In my View -- the AJAX request to GetPetsAsync
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script type="text/javascript">
$(document).ready(function () {
$("#OwnerId").change(function () {
$("#PetId").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("GetPetsAsync", "Agenda")',
//Take the OwnerId and send it to the JsonResult Method to retrieve the pets
data: { ownerId: $("#OwnerId").val() },
dataType: 'Json',
success: function (pets) {
$("#PetId").append('<option value="0">(Select a pet...)</option>');
$.each(pets, function (i, pet) {
$("#PetId").append('<option value="'
+ pet.id + '">'
+ pet.name + '</option>');
});
},
error: function (ex) {
alert('Failed to retrieve pets. ' + ex.statusText);
}
});
return false;
})
});
</script>
It looks like this feature change is affecting you.
Async suffix for controller action names will be trimmed by default #14716
You can just drop the "Async" suffix from your view-side code. Which is why renaming your method "fixed" your problem.
You have control over this behavior in your app startup with SuppressAsyncSuffixInActionName
builder.Services.AddMvc(options =>
{
options.SuppressAsyncSuffixInActionNames = false;
});
Make sure the "httppost" attribute is used. If you continue to get an error, check the data part in the ajax section.
I found the solution. Incredibly just by changing the Method Name to GetPetAsyncronous the problem was solve. I don’t know why the previous method wouldn’t work. But It worked.

Frontend validation on Fortify Login in Laravel with AJAX

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

Bootstrap 4 destroy a modal when it is closed

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

Laravel : Insert data into database using Bootstrap Modal

I want to insert some data into database using Bootstrap Modal. But the problem is Save button doesn't work properly on Bootstrap Modal as I couldn't insert the data into database through form. If anyone could help me to find it please!?
Here is the form part in blade:
<div id="myAlert" class="modal hide">
<div class="modal-header">
<button data-dismiss="modal" class="close" type="button">×</button>
<h3>Create User</h3>
</div>
<div class="modal-body">
<div class="row-fluid">
<div class="span12">
<div class="widget-box">
<div class="widget-content nopadding">
<form action="#" method="get" id="userForm" class="form-horizontal">
<div class="control-group">
<label class="control-label">Name :</label>
<div class="controls">
<input class="span11" placeholder="Name" type="text">
</div>
</div>
<div class="control-group">
<label class="control-label">Email :</label>
<div class="controls">
<input class="span11" placeholder="Email" type="email">
</div>
</div>
<div class="control-group">
<label class="control-label">Password</label>
<div class="controls">
<input class="span11" placeholder="Enter Password" type="password">
</div>
</div>
<div class="control-group">
<label class="control-label">Confirm Password</label>
<div class="controls">
<input class="span11" placeholder="Confirm Password" type="password">
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer"><a data-dismiss="modal" class="btn btn-primary" href="#">Confirm</a> <a
data-dismiss="modal" class="btn" href="#">Cancel</a>
</div>
</div>
Here is the Ajax Part :
$('#userForm').on('success.form.fv', function(e) {
e.preventDefault();
$.ajax({
method: 'POST',
action:"{{ url('/register') }}",
data: $form.serialize()
});
});
You need the submit button. Try to put this code inside your form.
<button type="submit" class="btn btn-primary">Register</button>
Problem with your current Confirm button is: 1) he don't have type=submit; 2) he is outside the form.
first of all add type="submit" to your button
secondly check your network tab in the dev tools in your browser and check the request does it go to /register or not ?
if the request is hitting /register what's the parameters ?
Change form method get to post
I answer here for ajax call
Laravel ajax internal servor 500 (internal server-error)
Your input type elements are missing name attribute
<input class="span11" placeholder="Name" name="name" type="text">
<input class="span11" placeholder="Email" name="email" type="email">
<input class="span11" placeholder="Enter Password" name="password" type="password">
<input class="span11" placeholder="Confirm Password" name ="confirm_password" type="password">
You then retrieve the content using Request or Input by passing the value of the name attribute
At first change your form method from get to post. Then add save button with id btnSave.
Ajax :
$("#btnSave").click(function(e){
e.preventDefault()
var $form = $("#userForm");
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize(),
success: function (data, status) {
if(data.error){
return;
}
alert(data.success); // THis is success message
$('#myModal').modal('hide'); // Your modal Id
},
error: function (result) {
}
});
});
In controller :
public function store(Request $request)
{ try {
$inputs = $request->all();
ModelName::create($inputs);
$data = ['success' =>'Data saved successfully'];
} catch (\Exception $e) {
$data = ['error' =>$e->getMessage()];
}
return Response::json($data);
}
Form part in blade:
<div class="modal-footer"><a data-dismiss="modal" class="btn btn-primary" id="btnAdd">Confirm</a></div>
Ajax Part
$('#btnAdd').click(function () {
$.ajax({
url: '{{url('/register')}}',
type: 'POST',
data: $('#userForm').serialize(),
success: function (object) {
},
error: function (result) {
}
});
});

Laravel 5 hash changes every time with Ajax call

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.

Resources