Laravel 5 pagination : MethodNotAllowedHttpException error - pagination

I have problem with my pagination:
Controller code:
$pagination = Orders::latest()->paginate(2);
return view('orders.index',compact('pagination')
);
View code:
{!! str_replace('/?', '?', $pagination->render()) !!}
All data have been loaded on page, that is fine, also pagination is on bottom, but when click on page 2, I get the following error:
MethodNotAllowedHttpException in compiled.php line 7717

Try to use Route::any instead of Route::post.

Related

POST FORM in node and receive data response back to same webpage

I have a webpage that takes form details, POSTS the data and should then show the results. I'm using express for my routing.
This all works fine by resending the data with the HTML template after the POST but I think there must be a better way by hiding the "results" HTML section then just showing it once the data is known from the form. I've shown a cutdown version of my pages below.
On first load, the page says "your result is undefined", which I would expect but is ugly.
I could remove the "result" section and create a 2nd HTML page to resend from the POST route with it in which would work but I think there must be a better way.
I want to hide the result section on 1st page load then make it appear on the button submit with the result data. I can get the section hide/unhide but I can't get the data results back to display them. On button submit the form results just appear in the weburl www.mywebsite.com/?data almost like a GET request
I have tried using FormData and npm 'form-data' in a POST but can't get it working following these examples https://javascript.info/formdata and https://www.npmjs.com/package/form-data.
My structure in Node is
Router.js file
return res.send(htmlFormTemplate({}));
});
router.post('/css',
[],
async (req, res) => {
let {data} = req.body;
///
result= do some calculation on {data}
///
return res.send(htmlFormTemplate({result}));
});
The htmlFormTemplate is a js file
module.exports = ({result}) => {
return `
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form class="box" method ="POST">
<inputname="data" />
<button>Submit</button>
</form>
<script>
///tried form processing here
</script>
<section id="Results">
<ul><li>Your result is ${result}</li></ul>
</section>
</body>
</html>
`;
};
I'm self-taught and new so hope this makes sense and thanks for any help/ideas
You can check if the result variable is null before it gets to the section div:
${ result === null ? '' :
`<section id="Results">
<ul><li>Your result is ${result}</li></ul>
</section>`}
Like this, it wont show the result div if result if null.
There is a very simple to solve this problem,
just use some templating engine for ex EJS, its very easy to use and will help you better,
and your result is undefined because your using a promise and it might have happened that the response might have not come and you loaded the page. Just use await
return await res.send(htmlFormTemplate({result}));

Generate pagination links on twig view using illuminate pagination

I'm having problem how can I able to generate links on twig view using the illuminate pagination. below is my codes.
Route:
$app->get('/', function ($request, $response) {
$data = Todo::paginate(5);
return $this->view->render($response, 'home.twig', [
'title' => 'Home',
'todolist' => $data,
]);
})->setName('homepage');
View:
{{todolist.links()}}
Error:
Call to a member function make() on null
btw I'm using Slim 3
Try this
Raw statement is to print the output as plain html (not text)
Refer to this link https://twig.sensiolabs.org/doc/2.x/filters/raw.html
{{todolist.links | raw}}
I tried on my slim 3 website and its works perfectly.
My Eloquent ver in the composer as below
"illuminate/database": "^5.2",
"illuminate/pagination": "~5.0"
If you're using Laravel pagination & Blade templates.
Try this in your blade file:
{{ $todolist->links() }}
Laravel docs: Displaying Pagination Results

(Post/Redirect/Get pattern) Laravel layout variables don't work after redirect

I'm using the Post/Redirect/Get (PRG) pattern in my Laravel controllers to prevent duplicate form submission.
It works well when I don't use layouts or when my layouts don't use any variable. The problem is my layout uses a variable named $title. When I load the view and the layout without redirect it works well, the title set in the controller is passed to the layout, but after processing a form and redirecting to the same route which uses the same layout and the same controller method I get a "Undefined variable: title" error coming from my layout file.
Here is my code:
File: app/routes.php
Route::get('contact', array('as' => 'show.contact.form', 'uses' => 'HomeController#showContactForm'));
Route::post('contact', array('as' => 'send.contact.email', 'uses' => 'HomeController#sendContactEmail'));
File: app/controllers/HomeController.php
class HomeController extends BaseController {
protected $layout = 'layouts.master';
public function showContactForm()
{
$this->layout->title = 'Contact form';
$this->layout->content = View::make('contact-form');
}
public function sendContactEmail()
{
$rules = ['email' => 'required|email', 'message' => 'required'];
$input = Input::only(array_keys($rules));
$validator = Validator::make($input, $rules);
if($validator->fails())
return Redirect::back()->withInput($input)->withErrors($validator);
// Code to send email omitted as is not relevant
Redirect::back()->withSuccess('Message sent!');
}
}
File: app/views/layouts/master.blade.php
<!DOCTYPE html>
<html>
<head>
<title>{{{ $title }}}</title>
</head>
<body>
#yield('body')
</body>
</html>
File: app/views/contact-form.blade.php
#section('body')
#if (Session::has('success'))
<div class="success">{{ Session::get('success') }}</div>
#endif
{{
Form::open(['route' => 'send.contact.email']),
Form::email('email', null, ['placeholder' => 'E-mail']),
Form::textarea('message', null, ['placeholder' => 'Message']),
Form::submit(_('Send')),
Form::close()
}}
#stop
I don't understand why after redirecting the next line of code is ignored
$this->layout->title = 'Contact form';
I've tried with Redirect::action('HomeController#sendContactEmail'); or Redirect::route('show.contact.form'); but the result is the same.
The controller in charge of rendering that view is exactly the same before the redirect than after the redirect, and it has no business logic at all, so why it only works on the first case but not in the second?
This
Redirect::back()->withSuccess('Message sent!');
should be
return Redirect::back()->withSuccess('Message sent!');
When layout attribute is set in a controller and method is not returning any response, controller try to render the layout. In your sendContactEmail() method both conditions fulfilled and controller tried to render layout before $title is set.
see callAction() in Illuminate\Routing\Controllers\controller.
http://laravel.com/api/source-class-Illuminate.Routing.Controllers.Controller.html#93-127
Have you tried using
return View::make('contact-form', array('title' => 'Contact Form'));
Instead of interacting with the layout directly?
Redirect::back() creates a 302 using the referer value of the current HTTP request. I would start by comparing the initial form request to the redirect request to see if that yields any clues. You could also try...
Redirect::route('HomeController#showContactForm')->withInput()...
I know it's less dynamic but it will generate the URL rather then rely on the referer value in the HTTP header.

jqGrid - Change filter/search pop up form - to be flat on page - not a dialog

I am using jqgrid.
I really need help with this, and have no clue how to do it, but i am sure its possible... can any one give me even a partial answer? were to start from?
I now have a requirement saying that for searching and filtering the grid I dont want the regular model form pop op thing opening, instead the filter should be open when entering the page but not as a pop up form , but should be on the top of the page but still have all the functions to it.
Needs to look like this:
And again having the select tag filled with the correct information (like they do in the popup form) and when clicking on "Save" it should send the request to the server, like regular.
Is this possible?
*******EDIT*******
The only thing i basically need is to have the filter with out the dialog part of it.
The solution of the problem for the old searching dialog you can find here. I modified the demo to the current implementation of the searching dialog in the jqGrid.
You can see the results on the demo:
The corresponding code is below:
var $grid = $('#list');
// create the grid
$grid.jqGrid({
// jqGrid opetions
});
// set searching deafauls
$.extend($.jgrid.search, {multipleSearch: true, multipleGroup: true, overlay: 0});
// during creating nevigator bar (optional) one don't need include searching button
$grid.jqGrid('navGrid', '#pager', {add: false, edit: false, del: false, search: false});
// create the searching dialog
$grid.jqGrid('searchGrid');
var gridSelector = $.jgrid.jqID($grid[0].id), // 'list'
$searchDialog = $("#searchmodfbox_" + gridSelector),
$gbox = $("#gbox_" + gridSelector);
// hide 'close' button of the searchring dialog
$searchDialog.find("a.ui-jqdialog-titlebar-close").hide();
// place the searching dialog above the grid
$searchDialog.insertBefore($gbox);
$searchDialog.css({position: "relative", zIndex: "auto", float: "left"})
$gbox.css({clear:"left"});
Here's the way I implemented it, using Oleg's excellent help.
I wanted my users to be able to immediately type in a search criteria (in this case, a user's name) and for the jqGrid to show the results. No messing around with the popup Search dialog.
Here's my end result:
To do this, I needed this HTML:
Employee name:
<input type="text" name="employeeName" id="employeeName" style="width:250px" />
<!-- This will be my jqGrid control and pager -->
<table id="tblEmployees"></table>
<div id="pager"></div>
and this JavaScript:
$("#employeeName").on('change keyup paste', function () {
SearchByEmployeeName();
});
function SearchByEmployeeName()
{
// Fetch the text from our <input> control
var searchString = $("#employeeName").val();
// Prepare to pass a new search filter to our jqGrid
var f = { groupOp: "AND", rules: [] };
// Remember to change the following line to reflect the jqGrid column you want to search for your string in
// In this example, I'm searching through the UserName column.
f.rules.push({ field: "UserName", op: "cn", data: searchString });
var grid = $('#tblEmployees');
grid[0].p.search = f.rules.length > 0;
$.extend(grid[0].p.postData, { filters: JSON.stringify(f) });
grid.trigger("reloadGrid", [{ page: 1 }]);
}
Again, my thanks to Oleg for showing how to use these search filters.
It really makes jqGrid much more user-friendly.

jQuery Masonry infinite scroll and picture overlap problems with my tumblr theme

I am new in programming(javascript) but I've done quite a research the past few days in order to make my tumblr theme work correctly. I know my question is common but as it seems I don't have enough knowledge to integrate correctly parts of code that were given in many similar examples.
My theme is supposed to override the "15 posts per page" limitation of tumblr and with an "endless scroll" option it should put all my posts (all of them pictures) in one endless page. Well, It doesn't. With a little help from here, I managed to wrap my {block:Posts} with the and with a couple of random changes in the masonry() call I ended up with this
As you can see my pictures are not overlapping (at last!) but after the 15 first posts it looks like a new page is created and the last pictures are not correctly aligned.
my jQuery masonry code is this:
<script type="text/javascript">
$(window).load(function () {
$('.autopagerize_page_element').masonry(),
$('.autopagerize_page_element').infinitescroll({
navSelector : "div.navigation",
// selector for the paged navigation (it will be hidden)
nextSelector : "div.navigation a#nextPage",
// selector for the NEXT link (to page 2)
itemSelector : ".autopagerize_page_element",
// selector for all items you'll retrieve
bufferPx : 10000,
extraScrollPx: 12000,
loadingImg : "http://b.imagehost.org/0548/Untitled-2.png",
loadingText : "<em></em>",
},
// call masonry as a callback.
function() { $('.autopagerize_page_element').masonry({ appendedContent: $(this) }); }
);
});
</script>
I know, its a mess...
Would really appreciate some help.
I'm not used to work with tumblr, but I can what is happening:
Line 110:
This script is creating a wrapper div around the entries each time you call to masonry, because of the script, each load looks like a new page, I think you can simply remove it.
Some tips:
You don't have to wait $(windows).load to execute masonry, change it by $(function()
To avoid image overlapping use appened masonry method and imagesLoad: Refer this
I see you're using masonry 1.0.1, be sure you're using masonry last version (2.1.06)
Example code:
$(function() {
//$('.autopagerize_page_element').masonry();
var $container = $('.autopagerize_page_element');
//wait until images are loaded
$container.imagesLoaded(function(){
$container.masonry({itemSelector: '.entry'});
});
$('.autopagerize_page_element').infinitescroll({
navSelector : "div.navigation",
// selector for the paged navigation (it will be hidden)
nextSelector : "div.navigation a#nextPage",
// selector for the NEXT link (to page 2)
itemSelector : ".entry",
// selector for all items you'll retrieve
bufferPx : 10000,
extraScrollPx: 12000,
loadingImg : "http://b.imagehost.org/0548/Untitled-2.png",
loadingText : "<em></em>",
},
// call masonry as a callback.
//function() { $('.autopagerize_page_element').masonry({ appendedContent: $(this) }); }
function( newElements ) {
// hide new items while they are loading
var $newElems = $( newElements ).css({ opacity: 0 });
// ensure that images load before adding to masonry layout
$newElems.imagesLoaded(function(){
// show elems now they're ready
$newElems.animate({ opacity: 1 });
$container.masonry( 'appended', $newElems, true );
});
}
);
});
and be sure to remove the last script in this header block:
<script type="text/javascript" src="http://static.tumblr.com/imovwvl/dJWl20ley/jqueryformasonry.js"></script>
<script type="text/javascript" src="jquery.masonry.min.js"></script> <!-- last masonry version -->
<script src="http://static.tumblr.com/df28qmy/SHUlh3i7s/jquery.infinitescroll.js"></script>
<!--<script src="http://static.tumblr.com/thpaaos/lLwkowcqm/jquery.masonry.js"></script>-->
Hope it helps

Resources