I'm using ajax to implement infinite scroll pagination in laravel but I cannot access the url while I can with the enter the url in the adress bar or via the default pagination page list.
I get GET http://localhost:8888/gest/items?page=2 500 (Internal Server Error)
Scripts
<script type="text/javascript">
var page = 1;
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() >= $(document).height()) {
page++;
loadMoreData(page);
}
});
function loadMoreData(page){
$.ajax(
{
url: '?page=' + page,
type: "get",
beforeSend: function()
{
$('.ajax-load').show();
}
})
.done(function(data)
{
if(data.html == " "){
$('.ajax-load').html("No more records found");
return;
}
$('.ajax-load').hide();
$(".row-items").append(data.html);
})
.fail(function(jqXHR, ajaxOptions, thrownError)
{
alert('server not responding...');
});
}
</script>
And the controller
public function index(Request $request, $submenu = null){
$items = Item::paginate(5);
if ($request->ajax()) {
$view = view('data',compact('items'))->render();
return response()->json(['html'=>$view]);
}
return view('layouts.gest', compact('items'), ['submenu' => $submenu]);
}
EDIT
I also tested to add
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
The error was that laravel couldn't find the view data
Related
I am trying to get data from controller and send it in ajax.
The script is in app.blade.php.
Controller
public function show()
{
$number=Order::where('user_id',Auth::user()->id)->count();
return $number;
}
Route
Route::get('product_number', 'OrderController#show')->name('product_number');
JS
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "GET",
url: "product_number",
success: function (data) {
console.log(data);
},
error: function () {
console.log('Error');
}
});
});
</script>
In console it shows me the html view.
try this so you can get the error
public function show()
{
try {
$number=Order::where('user_id',Auth::user()->id)->count();
} catch (\Exception $e) {
echo $e->getMessage(); die;
}
return $number;
}
$(document).ready(function(){
$.ajax({
type: "GET",
url: "{{url('product_number')}}",
success: function (data) {
console.log(data);
},
error: function () {
console.log('Error');
}
});
});
How do i get my code so that if the 401 error appears with my AJAX button click code, then it either throws an error message when the button is clicked and says "you need to log in" or it redirects the user to login? at the moment it just throws the error in the dev console so a user has no idea on why the button isnt working.
Ajax js:
$('.visit').on('click', function (event) {
event.preventDefault();
// Make the button a variable here
var buttonToChange = $(this);
$.ajax({
method: 'POST',
url: urlVisit,
data: {
place_id: $(event.target).data("id"),
_token: token
},
success: function(){
// Change the button here
if(buttonToChange.hasClass('btn-visited')){
buttonToChange.addClass('btn-not-visited');
buttonToChange.removeClass('btn-visited');
buttonToChange.html('Not Visited');
//Count will go down
}
else{
// Do the opposite
buttonToChange.addClass('btn-visited');
buttonToChange.removeClass('btn-not-visited');
buttonToChange.html('Visited');
//count will go up
}
},
});
You could try the statusCode part of jQuery AJAX.
$('.visit').on('click', function (event) {
event.preventDefault();
// Make the button a variable here
var buttonToChange = $(this);
$.ajax({
method: 'POST',
url: urlVisit,
data: {
place_id: $(event.target).data("id"),
_token: token
},
statusCode: {
401: function() {
alert( "Not authenticated" );
}
}
success: function(){
// Change the button here
if(buttonToChange.hasClass('btn-visited')){
buttonToChange.addClass('btn-not-visited');
buttonToChange.removeClass('btn-visited');
buttonToChange.html('Not Visited');
//Count will go down
}
else{
// Do the opposite
buttonToChange.addClass('btn-visited');
buttonToChange.removeClass('btn-not-visited');
buttonToChange.html('Visited');
//count will go up
}
},
});
simple example
you can test this code by inspect in browser:
welcome.blade.php :
<script>
var urlVisit="{{route('route_test')}}"
var token = "{{csrf_token()}}"
$.ajax({
method: 'POST',
url: urlVisit,
data: {
place_id: 1,
_token: token
},
success: function (response) {
alert('ok')
},
error: function (xhr, ajaxOptions, thrownError) {
if (xhr.status == 419)
{
alert(xhr.responseText) // text of error
// do something
}
else if(xhr.status == 401)
{
// do something
}
}
});
</script>
web.php (route) :
use Illuminate\Http\Request;
Route::get('/', function () {
return view('welcome');
});
Route::post('test', function (Request $request) {
$place_id= $request->get('place_id');
return ('yes');
})->name('route_test');
Controller Function Code
public function siteadmin_get_subcategory(Request $request)
{
$product_id = $request->input('product');
$sub_category=array(
'product_id'=>$product_id,
);
$return = Category_model::get_subcategory($sub_category);
//return view('siteadmin.get-subcategory',['sub_category' => $sub_category]);
return view('siteadmin.get-subcategory',['sub_category' => $sub_category]);
}
Model Function Code (which gets subcategory on product id)
public static get_subcategory($sub_category)
{
return DB::table('le_product')->where('product_id', '=', $sub_category)->get();
}
View JavaScript Code
This is my Ajax concept for Dropdown list based on parent
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#product_id').change(function(){
var product = $('#product_id').val();
if(product != 0) {
$.ajax({
type:'post',
url:"<?php echo base_url('SiteadminController/siteadmin_getsub_category')?>",
data: { id:product },
cache:false,
success: function(returndata){
$('#subcategory').html(returndata);
}
});
}
})
})
</script>
You need to call the correct URL in your AJAX:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#product_id').change(function(){
var product = $('#product_id').val();
if(product != 0) {
$.ajax({
type:'post',
url:"<?php echo action('SiteadminController#siteadmin_getsub_category')?>",
data: { id:product },
cache:false,
success: function(returndata){
$('#subcategory').html(returndata);
}
});
}
})
})
</script>
Also AJAX is expecting JSON, from what I see, you will return HTML. So you need to make a Controller action to return JSON.
get_subcategory1
public function get_subcategory1()
{
/*$product_id = $request->input('product_id');
$data=array(
'product_id'=>$product_id,
);*/
//$get_subcategory1 = Category_model::get_subcategory1();
return view('siteadmin.get-subcategory1');
}
I have an ajax request handling validation of form fields (login+signup+forget password). In its success scenario, I want it to route to another page, but when I use Redirect::route('name'); as return from controller, it completes the request with 200 and generates another GET request which just returns the html as response and does not route to other page.
AJAX
$('form[data-remote]').on('submit', function (e) {
var form = $(this);
var method = form.find('input[name="_method"]').val() || 'POST';
var url = form.prop('action');
$.ajax({
type: method,
url: url,
data: form.serialize(),
beforeSend: function () {
$('#ajax-loading').show();
$(".has-error").text("");
$('#login-error').addClass('display-hide');
$('#forget-user-error').addClass('display-hide');
}
})
.done(function (data) {
if (data.signup_fail) {
$.each(data.errors, function (index, value) {
var errorSpan = '#' + index + '_error';
$(errorSpan).removeClass('hidden');
$(errorSpan).empty().append(value);
});
$('#successMessage').empty();
}
else if (data.email_fail) {
$('#email_error').text('This Email already in use against an account.');
}
else if (data.company_fail) {
$('#email-error-popup').trigger('click');
}
else if (data.login_fail) {
$('#login-error').removeClass('display-hide');
}
else if (data.forget_fail) {
$.each(data.errors, function (index, value) {
var errorSpan = '#' + index + '_error';
$(errorSpan).empty().append(value);
});
$('#successMessage').empty();
}
else if (data.forget_user_fail) {
$('#forget-user-error').removeClass('display-hide');
}
else if (data.reset_fail) {
$.each(data.errors, function (index, value) {
var errorSpan = '#' + index + '_error';
$(errorSpan).removeClass('hidden');
$(errorSpan).empty().append(value);
});
$('#successMessage').empty();
}
})
.fail(function (jqXHR, ajaxOptions, thrownError) {
alert('No response from server');
});
return false;
});
How can I route to the other page on success condition? The ajax is triggered on a form submit button.
As you are doing an ajax request you can't just redirect from the controller on successful validation. Instead, just return the url you want to redirect to, as response to the ajax request similar to the way you are returning the validation errors. And in your js file use that url to redirect to new page.
#your above code
else if (data.forget_user_fail) {
$('#forget-user-error').removeClass('display-hide');
}
else if (data.reset_fail) {
$.each(data.errors, function (index, value) {
var errorSpan = '#' + index + '_error';
$(errorSpan).removeClass('hidden');
$(errorSpan).empty().append(value);
});
$('#successMessage').empty();
}
else{
window.location.replace(data.redirect_url); //this will redirect to new page
}
})
.fail(function (jqXHR, ajaxOptions, thrownError) {
alert('No response from server');
});
return false;
});
public function index($id)
{
$project = Project::findOrFail($id);
if(Request::ajax())
{
$html = View::make('Milestones.indexpartial', $project)->render();
return Response::json(array('html' => $html));
}
return View::make('milestones.index')->with('project', $project)
->with('title','Milestones');
}
$(".ajaxul a").click(function()
{
var url = $(this).attr('href');
$.ajax(
{
url: url,
type: "get",
datatype: "html",
beforeSend: function()
{
$('#ajaxloading').show();
}
})
.done(function(data)
{
$('#ajaxloading').hide();
$(".refresh").empty().html(data.html);
})
.fail(function(jqXHR, ajaxOptions, thrownError)
{
alert('No response from server');
});
return false;
});
Please help me make this work.
I'm new to AJAX and laravel.
my problem was this line here:
$html = View::make('Milestones.indexpartial', $project)->render();
it gives an error. then i changed it to
$html = View::make('Milestones.indexpartial',array('project' => $project))->render();
the request is a success but the html is empty.
Please help me. Thank you.