As per my previos post, what I did was get all the categories, now I wanted to change the categories checkbox status using ajax. For this I had to get the category ID and the checkbox status using javascript.
My previous Code
@foreach($categories as $category)
<input class="checkbox_id" type="checkbox" id="{{$category->category_id}}" value="{{$category->category_id}}"
{{isset($selectedCategories) ? (in_array($cateogry->category_id, array_values($selectedCategories->categories->pluck('fk_category_id')->toArray())) ? 'checked' : '') : ''}}>
<label for="{{$category->category_id}}">
{{$category->category_name}}
</label>
@endforeach
$('body').delegate('.checkbox_id', 'click', function () {
var category_id = $(this).data('id');
if ($(this).is(':checked')) {
var check_status = 1;
}
else {
var check_status = 0;
}
var data = { 'id': category_id, 'check_status': check_status };
updateCategorty(data)
});
function updateCategorty(data) {
$.ajax({
url: '{!! route('updateCategory') !!}',
type: 'POST',
data: data,
success: function (data, textStatus, jqXHR) {
if (data.status == 200) {
toastr.success(data.message);
}
else {
toastr.warning(data.message);
}
},
error: function (jqXHR, textStatus, errorThrown) {
toastr.warning("Server error. Please try again later");
}
});
}
What we are doing here is checking if the input class with ‘checkbox_id’ is changed or not. If it is changed, then the next if statement will check if it is checked, and if its true then the ‘check_status’ variable will get the value to be 1 else the value will be 0.
All of the variables are assiged to the variable ‘data’. Then I have called the function updateCategory(data) where all the ajax call is done. The data is routed to the give route where the controller does the rest of the job.
I hope this helps.