Laravel 4.2 ajax pagination Routing Issue - ajax

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

Related

405 (Method Not Allowed) error on ajax in Laravel 8

I am trying to call an ajax function in my Laravel 8 Project. But on every call I am getting error POST http://127.0.0.1:8000/getReasonForVisit 405 (Method Not Allowed). I have tried many options like changing post method to get, change url etc. but no use. It would be helpful if someone can help me.
Here is my code.
JS File
function getReasonForVisit(catId) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'POST',
url : '/getReasonForVisit',
data : {'catId' : catId },
dataType: 'json',
success:function(data) {
console.log(data);
}
});
}
$('#treatment-category').on('change', function (){
var catId = $(this).val();
getReasonForVisit(catId);
});
View
<select class="form-control form-select" name="category" id="treatment-category">
<?php $categories = App::make("App\Http\Controllers\AppointmentsController")->getTreatmentCategories(); ?>
#foreach($categories as $cat)
<option value="{{ $cat->id }}">{{ $cat->category_name }}</option>
#endforeach
</select>
Route
Route::post('/getReasonForVisit', [App\Http\Controllers\AppointmentsController::class, 'getReasonForVisit'])->name('getReasonForVisit');
Controller
class AppointmentsController extends Controller
{
public function getTreatmentCategories() {
$categories = DB::table('treatment_category')->get();
return $categories;
}
public function getReasonForVisit() {
echo 111;
}
}
EDIT
I did cleared my route cache. now it's showing error CSRF token mismatch
Please change option type to method
$.ajax({
method: 'POST',
url : '/getReasonForVisit',
data : {'catId' : catId },
dataType: 'json',
success:function(data) {
console.log(data);
}
});
I resolved my issue. Actually I am missing csrf meta tag in my blade. So Now I added this code in view blade file in the <head> tag.
<head>
<meta name="csrf-token" content="{{ csrf_token() }}">
</head>

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();

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 search - returning all results even if no match and make delay to ajax

I have a problem with my search.
Problem 1
Currently if I type in the field it is searching however the search never ever stops, so if I type hello, it will make about 500 requests within a minute.
Problem 2
I am searching in film table to find matching 'title' as well as find business name corresponding to business_id in business table.
Problem 3
Each time request is made it brings back master page again i.e. loading all js and css (which might be why it is making so many requests?) but if I don't extend master, result blade doesn't work.
however even if I input 'e' it brings me back 'guardians of the galaxy' which doesn't have 'e' My thoughts are that it is searching throught business table as well somehow. They have both eloquent one to one relationships
Controller:
public function cinema_search($cinema_value) {
$cinema_text = $cinema_value;
if ($cinema_text==NULL) {
$data = Film::all();
} else {
$data = Film::where('title', 'LIKE', '%'.$cinema_text.'%')->with('business')->get();
}
return view('cinemasearch')->with('results',$data);
}
Form::
<form id="cinema_display">
<div class="form-group">
<input type="text" class="form-control" id="search_cinemas" onkeyup="search_cinema(this.value);" placeholder="Search film">
</div>
<div id="show"
</div>
</div>
</form>
ajax:
function search_cinema(cinema_value) {
$.ajax({
url: '/cinemasearch/' + cinema_value,
type: 'post',
dataType: 'html',
success: function(data) {
$('#show').append(data);
$('.se-pre-con').fadeOut('slow', function () {
$(".container").css({ opacity: 1.0 });
});
},
error: function(data) {
},
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
}
cinemasearch.blade(results):
#extends('master') #section('title', 'Live Oldham') #section('content')
#section('content')
<table style="width:100%">
#if (isset($results) && count($results) > 0)
#foreach( $results as $film )
<tr>
<td>{{ $film->business->name }}</td>
<td>{{ $film->title }}</td>
<td>{{ $film->times}}</td>
</tr>
#endforeach
#endif
</table>
#endsection
function search_data(search_value) {  
$.ajax({
        url: '/searching/' + search_value,
        type: 'post',
        dataType: 'html',
        success: function(data) {
            $('#show_search_result').append(data);
            $('.se-pre-con').fadeOut('slow', function () {
$(".container").css({ opacity: 1.0 });
            });
        },
        error: function(data) {
            $('body').html(data);
        },
        headers: {
        'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
        }
    });
}
function tram_stops(tram_value) {
    $.ajax({
        url: '/tramsearch/' + tram_value,
        type: 'post',
        dataType: 'html',
        success: function(data) {
            $("#display").html(data);
            var tram_value = tram_value;
        },
        error: function(data) {
            
        },
        headers: {
        'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
        }
    });
}
/*
setInterval(tram_stops, (30 * 1000));
*/
function search_cinema(cinema_value) {
    $.ajax({
        url: '/cinemasearch/' + cinema_value,
        type: 'post',
        dataType: 'html',
        success: function(data) {
                var items = JSON.parse(data);
                var showElement = $('#show');
                showElement.html('');
                $.each(data, function() {
                   showElement.append(this.title +' '+ this.times+'<br />');
                });
        },
        error: function(data) {
        },
        headers: {
        'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
        }
    });
}
You are returning the wrong response type from cinema_search. Ajax expects a JsonResponse, not what the view helper returns which is \Illuminate\Http\Response. Put your search results in:
return response()->json(['results' => $data]);
to start with if you just want the data. If you want to actually return the rendered view file, you would need to do:
return response()->json(['results' => view('cinemasearch')->with('results',$data)->render()]);
then inject that into your DOM. The problem with rendering server side is nothing is bound client side so if you have any interaction requiring JS, you'll need to create those manually in your success callback.
Problem 1:
Remove the keyUp event in your html and add an event in Jquery.
Your HTML structure is not correct
This:
<form id="cinema_display">
<div class="form-group">
<input type="text" class="form-control" id="search_cinemas" onkeyup="search_cinema(this.value);" placeholder="Search film">
</div>
<div id="show"
</div>
</div>
</form>
Should be:
<form id="cinema_display">
<div class="form-group">
<input type="text" class="form-control" id="search_cinemas" onkeyup="search_cinema(this.value);" placeholder="Search film">
<div id="show">
</div>
</div>
</form>
Then again you should consider to remove the onkeyup event. And change add it in Jquery to something like this:
Problem 2 & 3: I would recommend a raw Query and return an json instead of a view. And you shouldn't check if($cinema_text === NULL) this won't be the case ever. Unless you put NULL in your url and even then it will be an String and not NULL and if('NULL' === NULL) returns false look at this post for the diff of == and ===.
public function cinema_search($cinema_value) {
$cinema_text = $cinema_value;
if (empty($cinema_text)) {
$data = Film::all();
} else {
$data = DB::select('*')
->from('films')
->join('businesses', 'businesses.id', '=', 'films.business_id')
->where('films.title', 'LIKE', '%'.$cinema_text.'%')
->orWhere('bussiness.title', 'LIKE', '%'.$cinema_text.'%')
->get();
}
return response()->json(['results' => $data]);
}
Then in your JavaScript do something like this:
$( document ).ready(function() {
console.log( "ready!" );
$( "#search_cinemas" ).change(function() {
search_cinema(this.value);
console.log( "New value"+this.value+"!" );
});
function search_cinema(cinema_value) {
console.log('setup ajax');
$.ajax({
url: '/cinemasearch/' + cinema_value,
type: 'post',
success: function(data) {
console.log('success!');
var showElement = $('#show');
showElement.html('');
$.each(items, function() {
showElement.append(this.title +' '+ this.times+'<br />');
});
},
error: function(data) {
console.log(data);
},
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
}
});

Using Ajax to implement controller method which is passed an ID

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 .

Resources