Using Ajax to implement controller method which is passed an ID - ajax

I have a button that toggles a boolean value in my DB table. It works but reloads the page each time, so I'd like to toggle it using AJAX. I'm not sure how to do an AJAX post request that can provide the controller with the ID it needs. This is what I have so far:
TaskController Method:
public function updateCompleted($id)
{
$task = Task::findOrFail($id);
if($task->completed) {
$task->completed = false;
} else {
$task->completed = true;
}
$task->save();
Session::flash('message', 'Task updated!');
return redirect('tasks');
}
Button used to toggle (in this case, the first task with ID of 1):
{{ Form::open(array('action' => array('TaskController#updateCompleted', $task->id))) }}
{{ Form::hidden('_method', 'PATCH') }}
#if ($task->completed)
{{ Form::button('<span class="glyphicon glyphicon-ok"></span>', array('class'=>'btn btn-danger', 'type'=>'submit')) }}
#else
{{ Form::button('<span class="glyphicon glyphicon-remove"></span>', array('class'=>'btn btn-danger ajaxSubmit', 'type'=>'submit')) }}
#endif
{{ Form::close() }}
AJAX that doesn't work...
$('.ajaxSubmit').click(function(e) {
e.preventDefault();
$.ajax({
url: 'tasks/complete/{id}',
type: 'POST',
success: function(response)
{
console.log("working");
}
});
});
And route:
Route::patch('tasks/complete/{id}', 'TaskController#updateCompleted');
How do I get the Ajax to work? Thanks

try this
add the id in hidden input with id of "myid" for example
$('.ajaxSubmit').click(function(e) {
var data = $("#myid").val();
e.preventDefault();
$.ajax({
url: '/tasks/complete',
type: 'POST',
data: data,
success: function(response)
{
console.log("working");
}
});
});
do this
Route::post('tasks/complete', 'TaskController#updateCompleted');
don't forget CSRF .

Related

How can I delete using ajax in laravel?

BLADE FILE
<td><button class="deleteuser" data-id="{{ $user->id }}" data-token="{{ csrf_token() }}" >DELETE</button>
</td>
AJAX
$(document).ready( function () {
$(".deleteuser").click(function(){
var id = $(this).data("id");
var token = $(this).data("token");
$.ajax(
{
url: "user/delete/"+id,
type: 'DELETE',
dataType: "JSON",
data: {
"id": id,
"_method": 'DELETE',
"_token": token,
},
success: function ()
{
console.log("it Work");
}
});
console.log("It failed");
});
});
CONTROLLER
public function destroyuser($id){
$this->authorize('Admin');
User::find($id)->delete($id);
return response()->json([
'success' => 'Record has been deleted successfully!'
]);
return view('viewuser');
}
If I click on delete button, there is no response. Any suggestion or correction will be appreciated. Thanks in advance
I don't know if the JS is in a different file but to check if the "$( document ).ready()" is working add a console.log() call at the beginning.
$(document).ready( function () {console.log("document is ready")
$(".deleteuser").click(function(){
Refresh the page and check if "document is ready" is logged to the console.
If it isn't then the javascript is not loading
Check if the route is properly defined
You can replace your url as this and check:
var id = data.id;
var url = "{{route('your_route',":id") }}";
url = url.replace(':id', id);
pass url in your ajax url param
Or make above changes:
BLADE FILE
<td>
<button style="background-color: red;" onclick="clickOffConfirmed" title="Delete" class="btn btn-sm btn-clean btn-icon btn-icon-md delete"><i class="la la-trash" style="color: white;"></i></button>
</td>
SCRIPT
<script>
$(document).ready(function() {
$(document).on('click', '.delete', function ()
{
var obj = $(this);
var id=$(this).closest('td').find(".delete_id").val();
var result = confirm("Are you sure want to delete?");
if(result)
{
$.ajax(
{
type: "POST",
url: "{{route('delete_method')}}",
data: {
'_token': $('input[name="_token"]').val(),
'id': id
},
cache: false,
success: function (data)
{
if (data.status === 'success')
{
window.location = "{{route('redirect_route')}}";
toastr["success"]("Deleted Successfully", "Success");
}
else if (data.status === 'error')
{
location.reload();
toastr["error"]("Something went wrong", "Opps");
}
}
});
}
});
});
</script>
Controller
public function delete_method(Request $request)
{
$del = ModelName::findOrFail($request->id)->delete();
if($del)
{
return response()->json(['status' => 'success']);
}
else{
return response()->json(['status' => 'error']);
}
}
Route
Route::post('/test/delete','TestController#delete_method')->name('delete_method');
In your ajax codes, change this:
url: "user/delete/"+id,
To:
url: "{{ url('user/delete') }}/" + id
If your ajax codes are inside of your blade file also you can use this way:
url: "{{ route('YOUR_ROUTE_NAME', $user->id) }}/"
You incorrectly define delete function!
change
User::find($id)->delete($id);
To
User::find($id)->delete();

toggle active/inactive states in Laravel

I want to update active and inactive status in laravel with toggle. Status show perfectly. But controller doesn't work. Here
is my code.
blade file
#foreach($data as $srial => $row)
<tr>
<td>{{$row->name}}</td>
<td>
<input data-id="{{$row->id}}" class="toggle-class" type="checkbox" data-onstyle="success" data-offstyle="danger" data-toggle="toggle" data-on="Active" data-off="InActive" {{ $row->status ? 'checked' : '' }}>
</td>
</tr>
#endforeach
<script>
$(document).ready(function(){
$('.toggle-class').change(function () {
let status = $(this).prop('checked') === true ? 1 : 0;
let userId = $(this).data('id');
$.ajax({
type: "GET",
dataType: "json",
url: '{{ route('/changeStatus') }}',
data: {'status': status, 'user_id': userId},
success: function (data) {
console.log(data.message);
}
});
});
});
</script>
Controller
public function changeUserStatus(Request $request)
{
$file=DB::table('students')->where('id',$id)->first();
$user=$file->status;
$task ['status']= $request->user_id;
$data=DB::table('students')->where('id',$request)->update($task);
}
Route
Route::get('/changeStatus', 'AdminController#ChangeUserStatus')->name('/changeStatus');
Try bellow query:
public function changeUserStatus(Request $request)
{
DB::table('students')->where('id', $request->user_id)->update(['status' => $request->status]);
}
Where condition is wrong, need to pass user id and status in update.
and in view, ajax type must be post
$(document).ready(function(){
$('.toggle-class').change(function () {
let status = $(this).prop('checked') === true ? 1 : 0;
let userId = $(this).data('id');
$.ajax({
type: "POST",
dataType: "json",
url: "{{ route('/changeStatus') }}",
data: {'status': status, 'user_id': userId},
success: function (data) {
console.log(data.message);
}
});
});
});
Route must be post type
Route::post('/changeStatus', 'AdminController#ChangeUserStatus')->name('/changeStatus');

Laravel Ajax Update 1 Column of record

I have a user schedule record that I can update easily without one form field called disabled_dates. disabled_dates is setup to store an array of dates a user can add one at a time. What I did was add a form field with its own button using a javascript function disable() in the onclick attribute to update the record.
<div class='input-group text-center'>
{!! Form::text('disabled_dates', null , ['class' => 'form-control text-center datetimepicker15', 'id' => 'disable_date', 'placeholder' => '']) !!}
<span class="input-group-btn">
<button type="button" onclick="disable();" class="btn btn-fab btn-round btn-success">
<i class="material-icons">add</i>
</button>
</span>
Then created the disable(); like so
function disable() {
var CSRF_TOKEN = '{{ csrf_token() }}';
var disabled_date = document.getElementById('disable_date').value;
$.ajax({
type:'PUT',
url:'/schedule',
data:{_token: CSRF_TOKEN, blocked_date: disabled_date},
success:function(response) {
console.log(response);
}
});
}
The controller function used is
public function add_blocked_day(Request $request)
{
$schedule = User::find(auth()->user()->id)->schedule;
$current_blocked_dates = $schedule->disabled_dates;
$schedule->disabled_dates = $current_blocked_dates. ','.$request->blocked_date;
$schedule->save();
exit;
}
All Im getting now is too many redirects. The solution Im thinking is to seperate disabled_dates and enclose in its own form tags, because its calling the original form route somehow
I got it to work by changing the function to this
$(document).on("click", ".add-day" , function() {
var CSRF_TOKEN = '{{ csrf_token() }}';
var disabled_date = document.getElementById('disable_date').value;
$.ajax({
type:'POST',
url:'schedule/blocked-day',
data:{_token: CSRF_TOKEN, blocked_date: disabled_date},
success:function(response) {
console.log(response);
}
});
});

how send id in ajax for laravel

i want to run my ajax after click on one of the options in select tag. and send id of option to ajax url.
please help me . these are my codes.
#foreach($emails as $mail)
<option id="{{$mail->id}}">{{$mail->email}}</option>
#endforeach
</select>
my ajax
$(document).ready(function () {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('.select option').on('click',function () {
var id=$('.select option:selected').attr("id");
$.ajax({
url:'/mailactive',
type:'get',
dataType:'json',
data:{id:id}
})
})
})
try to use this:
give to your select an id, for example id_select
use #id_select > option:selected in your jQuery selector instead of .select option:selected
then tell me if you still can't get the id
In Your Laravel Blade
<select id="email">
#foreach($emails as $mail)
<option id="{{ $mail->id }}"> {{ $mail->email }} </option>
#endforeach
</select>
If your Route is POST method
$(document).ready(function () {
var id = $('#email').children(":selected").attr("id");
$.post('{{ url('your_POST_route_url') }}', {
'_token': "{{ csrf_token() }}", id:id,
}, function (data) {
console.log(data); // Print your response into your console
});
});
If your Route is GET method
$(document).ready(function () {
var id = $('#email').children(":selected").attr("id");
$.get('{{ url('your_GET_route_url') }}', {
id:id,
}, function (data) {
console.log(data); // Print your response to your console
});
});
You should have return data from your GET or POST method.

Laravel 4.2 ajax pagination Routing Issue

Showing this message in console
GET http://localhost/ajax/pagination?page=5 404 (Not Found)
View page (pages.post) :
#foreach ($posts as $post)
<article>
<h2>{{ $post->title }}</h2>
</article>
#endforeach
{{ $posts->links() }}
<script>
$(document).ready(function() {
$(document).on('click', '.pagination a', function (e) {
getPosts($(this).attr('href').split('page=')[1]);
e.preventDefault();
});
});
function getPosts(page) {
$.ajax({
type:'GET',
url : '/ajax/pagination?page=' + page,
}).done(function (data) {
$('.posts').html(data);
location.hash = page;
})
}
</script>
Route :
Route::get('/ajax/pagination',array('before' =>'auth' ,
'uses'=>'CampaignsController#showPostspag'));
Controller :
public function showPostspag()
{
$posts = Address::paginate(5);
return View::make('pages.post')->with('posts',$posts);
}
Where is my mistake? I think that is ajax url and routing problem..
Try this..
if "ajax" your root directory means update following code
function getPosts(page) {
$.ajax({
type:'GET',
url : 'pagination?page=' + page,
}).done(function (data) {
$('.posts').html(data);
location.hash = page;
})
}
Route :
Route::get('pagination',array('before' =>'auth' ,
'uses'=>'CampaignsController#showPostspag'));

Resources