I want to delete and update table row with modal by using ajax technique
in
laravel 5.7 but I m quite naive with ajax.
I would be appreciated if anyone helps and explain how ajax send/get data in
controller and is there any difference between using ajax in PHP and
laravel.?
this is my table
<table class="table table-striped">
<tr>
<th>ID</th>
<th>Title</th>
<th>Description</th>
</tr>
#foreach($project as $pro)
<tr>
<td>{{$pro->id}}</td>
<td>{{$pro->title}}</td>
<td>{{$pro->description}}</td>
<td>
<button class="btn btn-info"
data-toggle="modal" data-target="#edit">Edit</button>
<button class="btn btn-danger"
data-toggle="modal" data-target="#dlt">Delete</button>
</td>
<--------------------->
<div class="modal fade" id="edit" tabindex="-1" role="dialog" aria-
labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<form method="post" action="">
#method('PATCH')
#csrf
<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" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" name="title" >
</div>
<div class="form-group">
<label for="description">Description</label>
<input type="text" class="form-control"
name="description">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-
dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save
changes</button>
</div>
</form>
</div>
</div>
</div>
this is my modal code
<div class="modal fade" id="dlt" tabindex="-1" role="dialog" aria-
labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<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>
<h4 class="modal-title" id="myModalLabel">Adding
Project</h4>
</div>
<form method="post" action="">
#method('delete')
#csrf
<div class="modal-body">
<p class="text-center">
Are you sure, you want to delete this.?
</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-
dismiss="modal">No, Cancel</button>
<button type="submit" class="btn btn-info">Yes,
Delete</button>
</div>
</form>
</div>
</div>
</div>
my route
Route::resource('projects', 'ProjectsController');
There no difference between using ajax in PHP and laravel.
html adjustment, add this meta inside your html head.
<meta name="csrf-token" content="{{ csrf_token() }}" />
Update your delete button and add a hidden field inside your delete modal body.
<button class="btn btn-danger btn-delete-project" data-toggle="modal" data-target="#dlt" data-project-id="{{ $pro->id}}">Delete</button>
<input type="hidden" name="project_id" id="project_id" value="">
<button type="submit" class="btn btn-info delete-project-confirm">Yes, Delete</button>
Get Your deleted row,
<tr data-row-id="{{ $pro->id }}">
</tr>
Define your ajax function, there are many defferent technique you can do it. A simple one below.
/**
* project delete confirm modal
*/
$(document).on('click', '.btn-delete-project', function (e) {
e.preventDefault();
var projectId = $(this).data('project-id');
$('#dlt #project_id').val(projectId);
});
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
/**
* ajax call
*/
// give your delete button id
$(document).on('click', '.delete-project-confirm', function (e) {
e.preventDefault();
var projectId = $('#dlt #project_id').val();
var deletedRow = $('tr[data-row-id="' + projectId + '"]');
$.ajax({
type: 'delete',
url: '/project/' + projectId,
success: function () {
$('#dlt').modal('toggle');
deletedRow.remove();
// toastr.success('Order Has Been Deleted Successfully.');
},
error: function(XMLHttpRequest) {
// toastr.error('Something Went Wrong !');
}
});
});
In your ProjectController destroy() method,
public function destroy($id)
{
// dd($id);
$project = Project::findOrFail($id);
// dd($project);
$project->delete();
}
Related
Hi I'm new to Laravel and trying Laravel 8. In my web app there is a pop up to select a option, the select box is also dynamically populated. I need to fetch some data from the database to a table on the pop up based on the selected option without reloading the page.
The code of the pop up.
<div id="UpgradeStudentModal" class="modal fade" tabindex="-1" aria-labelledby="myModalLabel"
aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title mt-0" id="myModalLabel">Upgrade Student</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"
aria-label="Close"></button>
</div>
<div class="modal-body">
<form action="" method="post" enctype="multipart/form-data">
{{csrf_field()}}
<div class="mb-3">
<label for="" class="form-label">Teacher</label>
<select class="form-control" name="teacherId">
#foreach($teachers as $teacher)
<option value="{{$teacher->tId}}">{{$teacher->tName}}</option>
#endforeach
</select>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary waves-effect waves-light">Save
</button>
<button type="button" class="btn btn-outline-danger waves-effect waves-light"
data-bs-dismiss="modal">Close
</button>
</div>
</form>
</div>
</div>
</div>
</div>
Sorry but I have no code to describe what I have tried.
This is a screenshot of the pop up.
I need to get a dynamic output like this.
I can edit the question to provide more code as your request, I just don't know what
will help right now.
You can use Ajax to submit your form and fetch necessary data. I haven't your controller so can not place related values in my example for you but you can send it here or change this example in order to your real situation. Please look at this example:
<div id="UpgradeStudentModal" class="modal fade" tabindex="-1" aria-labelledby="myModalLabel"
aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title mt-0" id="myModalLabel">Upgrade Student</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"
aria-label="Close"></button>
</div>
<div class="modal-body">
<div class="mb-3">
<label for="" class="form-label">Teacher</label>
<select class="form-control" name="teacherId" id="teacherId">
#foreach($teachers as $teacher)
<option value="{{$teacher->tId}}">{{$teacher->tName}}</option>
#endforeach
</select>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline-danger waves-effect waves-light"
data-bs-dismiss="modal">Close
</button>
</div>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function () {
$('#teacherId').on('change', function () {
var idTeacher = this.value;
$.ajax({
url: "{{url('your form url')}}",
type: "POST",
data: {
teacher_id: idTeacher,
_token: '{{csrf_token()}}'
},
dataType: 'json',
success: function (result) {
$.each(result.teachers, function (key, value) {
$("#your-modal-div-id").append('<span>' + value.name + '</span>');
});
}
});
});
I have created a form for Making Category and on the same page I am displaying the categories in form of tables. In front of each category there is a Add button to add subcategory. I want to display a modal which has a form for subcategory .
I am not able to add subcategory. When I click submit the submitted details are displayed in raw form and it is selecting only Id 1 everytime
Controller:
public function subcat(Request $request, $id)
{
$data = new SubCategories();
$data->name = $request->input('name');
$data->categories_id=$id;
if($request->hasfile('image')){
$file = $request->file('image');
$extension = $file->getClientOriginalExtension();
$filename = time().'.'.$extension;
$file->move('uploads/subcategory/',$filename);
$data->image = $filename;
}else{
return $request;
$data->image = '';
}
$data->save();
return redirect('/admin/addCategory')->with('Success', 'SubCategory Added');
}
Blade
#extends('admin.master');
#section('content');
<div class="content-wrapper">
<div class="row">
<div class="container">
<form action="{{route('store')}}" method="POST">
{{csrf_field()}}
<label for="cat_name">Category Name</label>
<input type="text" name="cat_name" class="form-control">
<button type="submit" class="btn btn-success">Submit</button>
</form>
</div>
</div>
<div class="row">
<div class="container">
<table class="table table-dark">
<tr>
<thead>
<th>ID</th>
<th>Category</th>
<th>AddSubCategory</th>
</thead>
</tr>
<tbody>
#foreach($category as $col)
<tr>
<td>{{$col->id}}</td>
<td>{{$col->cat_name}}</td>
<td><a class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" href="/admin/category/{{$col->id}}">Add</a></td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="exampleModal" 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 SubCategory</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form action="{{route('storeSub',[$category[0]->id])}}" method="POST">
{{csrf_field()}}
<label for="name">SubCategory</label>
<input type="text" name="name" class="form-control">
<label for="image">Image</label>
<input type="file" name="image" class="form-control">
<button type="submit" class="btn btn-primary">Save changes</button>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
#endsection
Route
Route::prefix('/admin')->group( function() {
Route::get('/addCategory','\App\Http\Controllers\AdminController#index');
Route::post('/storecat','\App\Http\Controllers\AdminController#categories')->name('store');
Route::get('/addCategory','\App\Http\Controllers\AdminController#show');
Route::post('/category/{id}','\App\Http\Controllers\AdminController#subcat')->name('storeSub');
});
Your probably not summiting a file, so the else statement is the path you are on. Because of this line
else{
return $request; // Remove This
...
Everything stops at that point and you are returning the raw form request data which Laravel is automatically turning into JSON. You'll need to remove that line in order for the rest of your method to continue processing.
Because your modal is out of the foreach.
action="{{route('storeSub',[$category[0]->id])}}" on modal form can't handle above table's values.
Try to move modal area to foreach or, change modal's values with javascript dynamically.
The reason why everytime getting category id = 1 is, Because you're submitting on modal form action like
$category[0]->id
This means every time send category id = 1
So solutions is should be near to this in your blade file;
#extends('admin.master');
#section('content');
<div class="content-wrapper">
<div class="row">
<div class="container">
<form action="{{route('store')}}" method="POST">
{{csrf_field()}}
<label for="cat_name">Category Name</label>
<input type="text" name="cat_name" class="form-control">
<button type="submit" class="btn btn-success">Submit</button>
</form>
</div>
</div>
<div class="row">
<div class="container">
<table class="table table-dark">
<tr>
<thead>
<th>ID</th>
<th>Category</th>
<th>AddSubCategory</th>
</thead>
</tr>
<tbody>
#foreach($category as $col)
<tr>
<td>{{$col->id}}</td>
<td>{{$col->cat_name}}</td>
<td><a class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" href="/admin/category/{{$col->id}}">Add</a></td>
</tr>
<!-- Modal -->
<div class="modal fade" id="exampleModal" 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 SubCategory</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form action="{{route('storeSub',[$col->id])}}" method="POST">
{{csrf_field()}}
<label for="name">SubCategory</label>
<input type="text" name="name" class="form-control">
<label for="image">Image</label>
<input type="file" name="image" class="form-control">
<button type="submit" class="btn btn-primary">Save changes</button>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
</div>
#endsection
May be the problem is in your javascript file that operate the modal class. Please provide more information on the related script.
I'm having an issue getting data to transfer into my delete confirmation modal.
I've verified my delete route works in removing data from the data base but the issue I'm facing is that I can't pass the contact->id into the modal to access for deletion.
The Modal
<!-- Delete Warning Modal -->
<div class="modal modal-danger fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="Delete" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Delete Contact</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form action="{{ route('contacts.destroy', 'id') }}" method="post">
#csrf
#method('DELETE')
<input id="id" name="id")>
<h5 class="text-center">Are you sure you want to delete this contact?</h5>
<input id="firstName" name="firstName"><input id="lastName" name="lastName">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-sm btn-danger">Yes, Delete Contact</button>
</div>
</form>
</div>
</div>
</div>
<!-- End Delete Modal -->
Blade call
<td>
<a href="#"
data-id={{$value->id}}
class="btn btn-danger delete"
data-toggle="modal"
data-target="#deleteModal">Delete</a>
</td>
Contact Controller
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
// Need to find all addresses with the contacdt Id and delete them.
Address::where('contact_id', $id)->delete();
Contact::find($id)->delete();
return redirect()->route('contacts.index')->with('success','Contact deleted success');
}
To summarize, my issue is getting jQuery to transfer data to the modal so I can then use it to delete the data... right now my id=null
Jquery code:
$(document).on('click','.delete',function(){
let id = $(this).attr('data-id');
$('#id').val(id);
});
Also in your modal html code:
<input id="id" name="id">
In your bootstrap modal form change the following:
<form action="{{ route('contacts.destroy', 'id') }}" method="post">
#csrf
#method('DELETE')
<input id="id" name="id" hidden>
<h5 class="text-center">Are you sure you want to delete this contact?</h5>
<input id="firstName" name="firstName"><input id="lastName" name="lastName">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-sm btn-danger">Yes, Delete Contact</button>
</div>
</form>
In the above code you are passing the string parameter that is 'id' to the controller so it will detect 'id' which is string you need to bring little bit changes in your controller as well instead of taking 'id' directly as parameter you need to take the request as you are placing the selected id into the input field that is :
<input id="id" name="id" hidden value="">
Add the jquery:
<script>
$(document).on('click','.delete',function(){
let id = $(this).attr('data-id');
$('#id').val(id);
});
</script>
Controller should be:
public function destroy(Request $request)
{
$id= $request->id;
$items = yourModel::find($id);
$items->delete();
return redirect()->route('your page')->with('message', 'report details has been successfully deleted');
}
<div class="table-responsive">
<table class="table table-bordered table-sm">
<thead>
<tr>
<th>ID</th>
<th>Nombre</th>
<th>Usuario</th>
<th>Acción</th>
</tr>
</thead>
#foreach($users as $user)
<tbody>
<tr>
<td>{{ $user->id }}</td>
<td>{{ $user->nombre }}</td>
<td>{{ $user->login}}</td>
<td>
<i class="bi bi-pencil-square"></i>
<a data-bs-toggle="modal" class="btn btn-warning" data-bs-target="#deleteUserModal_{{$user->id}}"
data-action="{{ route('users.destroy', $user->id) }}"><i class="bi bi-trash"></i></a>
</td>
</tr>
</tbody>
<!-- Delete User Modal -->
<div class="modal fade" id="deleteUserModal_{{$user->id}}" data-backdrop="static" tabindex="-1" role="dialog"
aria-labelledby="deleteUserModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="deleteUserModalLabel">Esta acción es irreversible.</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<form action="{{ route('users.destroy', $user->id) }}">
<div class="modal-body">
#csrf
#method('DELETE')
<h5 class="text-center">¿Estás seguro de que quieres eliminar al usuario
{{ $user->nombre }} {{ $user->apellido_materno }} {{ $user->apellido_paterno }} ?</h5>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
<button type="submit" class="btn btn-danger">Si, Eliminar Usuario</button>
</div>
</form>
</div>
</div>
</div>
#endforeach
</table>
</div>
I have some rows shown in a table (each one is a row of the related model database table). For each row I show a button that shows a modal asking for confirmation to delete it.
[https://i.stack.imgur.com/tSquD.png][1]
[https://i.stack.imgur.com/gGhSO.png][2]
The modal code is a blade template.
For a table with a single row, i have no problem. I can pass the id as variable to the modal. But i dont know how to send the selected one (logically, its including the modal with the last value of the $subnet var).
What would be the correct way to achieve this?
...
#foreach($subnets as $subnet)
<tr>
<td>{{$subnet->name}}</td>
<td><button type="button" class="btn-xs btn-primary">Edit</button><button type="button" class="btn-xs btn-primary" data-toggle="modal" data-target="#deleteSubnet">Delete</button></td>
</tr>
#endforeach
#include('inc.modals.modal_deleteSubnet',['subnet' => $subnet])
...
<div class="modal fade" id="deleteSubnet" tabindex="-1" role="dialog" aria-labelledby="deleteSubnetLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="deleteSubnetLabel">Delete subnet</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
<form action="/subnets/{{$subnet->id}}" method="POST">
#csrf
#method('DELETE')
<p>Are you sure you want to delete this subnet ({{$subnet->name}})?<p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<span class="pull-right">
<input class="btn btn-primary" type="submit" value="Delete">
</span>
</form>
</div>
</div>
</div>
</div>
[1]: https://i.stack.imgur.com/tSquD.png
[2]: https://i.stack.imgur.com/gGhSO.png
In your form add a bind id
#foreach($subnets as $subnet)
<tr>
<td>{{$subnet->name}}</td>
<td>
<button type="button" class="btn-xs btn-primary" data-id="{{$subnet->id}}">Edit</button>
<button type="button" class="btn-xs btn-primary" data-id="{{$subnet->id}}" data-toggle="modal" data-target="#deleteSubnet">Delete</button>
</td>
</tr>
#endforeach
Add a "id" in your form to get in jquery. <form method="POST id="formId">
$(document).ready(function () {
// you can add a better validation to button like a ID or class
$("button").each(function () {
$(this).onClick(function () {
var action = "/subnets/" + $(this).data().id;
$("#formId").attr("action", action);
});
});
});
You might wanna check this section on Bootstrap's website.
In your case this could be translated to:
Add data-id="{{ $subnet->id }}" to your button.
<button type="button" class="btn-xs btn-primary">Edit</button><button type="button" class="btn-xs btn-primary" data-toggle="modal" data-target="#deleteSubnet" data-id="{{ $subnet->id }}">Delete</button>
Add this jQuery snippet.
$('#deleteSubnet').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget)
var id = button.data('id')
var modal = $(this)
modal.find('form').attr('action', '/subnets/' + id)
})
Without any javascript workarounds:
<button ... data-target="#deleteSubnet-{{ $subnet->id }}">Delete</button>
....
<div class="modal fade" id="deleteSubnet-{{ $subnet->id }}" ... >
....
</div>
Should work fine
<div class="modal fade" id="AddEditModal" role="dialog" ng-show="showEditModal">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button aria-hidden="true" data-dismiss="modal" class="close" type="button" ng-click="loadDetails()">
×
</button>
<h4 class="modal-title" ng-show="newType">Employee - New</h4>
<h4 class="modal-title" ng-hide="newType">Employee - Edit</h4>
</div>
<form class="form-horizontal" name="employeeForm" ng-submit="saveEmployee(detail,employeeForm.$valid)">
<div class="modal-body">
<p>
<div ng-repeat="error in errors">
<div class="alert alert-danger">
<button class="close" data-dismiss="alert">× </button>
<i class="fa fa-times-circle"></i>
{{error}}
</div>
</div>
</p>
<div class="row">
<div class="form-group required" ng-class="{ 'has-error' : employeeForm.EmpCode.$invalid && !employeeForm.EmpCode.$pristine }">
<label class="col-sm-4 control-label" for="EmpCode"><b>Employee Code:</b> </label>
<div class="col-sm-6">
<input class="form-control" type="text" name="EmpCode" ng-model="detail.EmpCode" required>
<p ng-show="employeeForm.EmpCode.$invalid && !employeeForm.EmpCode.$pristine" class="help-block">Employee is required.</p>
</div>
</div>
<div class="form-group required" ng-class="{ 'has-error' : employeeForm.FirstName.$invalid && !employeeForm.FirstName.$pristine }">
<label class="col-sm-4 control-label" for="FirstName"><b>First Name :</b> </label>
<div class="col-sm-6">
<input class="form-control" type="text" name="FirstName" ng-model="detail.FirstName" required>
<p ng-show="employeeForm.FirstName.$invalid && !employeeForm.FirstName.$pristine" class="help-block">First Name is required.</p>
</div>
</div>
<div class="form-group required" ng-class="{ 'has-error' : employeeForm.LastName.$invalid && !employeeForm.LastName.$pristine }">
<label class="col-sm-4 control-label" for="LastName"><b>Last Name :</b> </label>
<div class="col-sm-6">
<input class="form-control" type="text" name="LastName" ng-model="detail.LastName" required>
<p ng-show="employeeForm.LastName.$invalid && !employeeForm.LastName.$pristine" class="help-block">Last Name is required.</p>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-success" type="submit" ng-show="newType" ng-disabled="employeeForm.$invalid">
<i class="fa fa-save"></i>
Save
</button>
<button class="btn btn-success" type="submit" ng-hide="newType" ng-disabled="employeeForm.$invalid">
<i class="fa fa-save"></i>
Save Changes
</button>
<button type="button" class="btn btn-default" data-dismiss="modal" ng-click="removeFormDetails()"><i class="fa clip-close-3"></i>Close</button>
</div>
</form>
</div>
</div>
</div>
<!--Delete Section-->
<div class="modal fade" id="deleteModal" role="dialog" ng-show="showDeleteModal">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Delete</h4>
</div>
<div class="modal-body">
<p>Do you really want to delete this User?</p>
</div>
<div class="modal-footer">
<button class="btn btn-bricky" type="button" ng-click="deleteEmployee(detail)">
<i class="fa fa-trash-o"></i>
Delete
</button>
<button class="btn btn-green" data-dismiss="modal" type="button" ng-click="removeFormDetails()">
<i class="fa clip-close-3"></i>
Close
</button>
</div>
</div>
</div>
</div>
I have a popup model where user add the course name. I have added a form validation in my codeigniter controller and then if the validation is false, I am loading my view again with a form error showing above form input in the model, but due to page reload the model closes. What I want is if the form validation is false I want to reload the page with the modal open. I am not familiar with ajax. Any help will be really appreciated.
Codeigniter Controller
$this->form_validation->set_rules('course_name', 'Course Name', 'required|max_length[30]');
$this->form_validation->set_error_delimiters('<div class="text-danger">', '</div>');
if ($this->form_validation->run() ) {
echo "inserted";
}else {
$this->load->view('admin/coursename');
}
Codeigniter View (Modal Code)
<center><button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">Add Course</button><center>
<!-- Modal -->
<div class="modal fade" data-backdrop="static" data-keyboard="false" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add Course</h4>
</div>
<div class="modal-body">
<form action="" method="post">
<div class="form-group">
<label for="name">Course Name:</label>
<?php echo form_error('course_name'); ?>
<input type="text" class="form-control" id="name" name="course_name" placeholder="Enter course name...">
</div>
<div class="form-group">
<button type="submit" class="btn btn-success">Save</button>
<button type="reset" class="btn btn-warning">Cancel</button>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
You can use jquery ".ajax()" method to call the validation controller without refreshing, then the controller echoes its result which your j-query code will now have to interprete. An example code below.
You can modify your view code like this:
<div class="modal fade" data-backdrop="static" data-keyboard="false" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add Course</h4>
</div>
<div class="modal-body">
<div class="err">
</div>
<form action="" method="post" id ="yourform">
<div class="form-group">
<label for="name">Course Name:</label>
<?php echo form_error('course_name'); ?>
<input type="text" class="form-control" id="name" name="course_name" placeholder="Enter course name...">
</div>
<div class="form-group">
<button type="submit" class="btn btn-success">Save</button>
<button type="reset" class="btn btn-warning">Cancel</button>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
<script>
$("#yourform").submit(function (event) {
var form = $(this).closest('form');
field1 = $(form).find('.field1').val();
field2 = $(form).find('.field2').val();
$.ajax({
url: '<?php echo site_url('your/controller/url') ?>',
type: 'POST',
data: {field2: field2, field2: field2},
success: function (result) {
//alert(result);return false;
if (result == 1)
{
location.reload();
} else
{
$('#err').html(result);
}
}
});
event.preventDefault();
});
Then you can configure your controller like such :
<?php
$this->form_validation->set_rules('course_name', 'Course Name', 'required|max_length[30]');
$this->form_validation->set_error_delimiters('<div class="text-danger">', '</div>');
if ($this->form_validation->run()) {
echo "1";
} else {
echo "<b>" . validation_errors() . "</b>";
}
?>
Hope i helped
you can use location.reload("Your Page Name") function in ajax success function.