Laravel - Prevent form resubmission on refresh - forms

How can I prevent my form from resubmitting when I refresh the page. Solutions I've found suggest a redirection, which I am using.
The form in view admin.enrollform.blade.php:
<form id="enrollform" class="form-horizontal" role="form" method="post"
enctype="multipart/form-data"
action="{{route('storeStudent', ['site' => $site->site_url, 'lang' => $lang] )}}">
<input type="visible" name="_token" id="_token" value="{{ csrf_token() }}"/>
...
</form>
The laravel controller:
public function store(Request $request, $site, $lang = null)
{
....
return view('admin.enrollform', [
'message' => $message
]);
}
If successful, the controller returns a view, which points to the same page. So the same page is loaded again, with a message. And the form is empty.
However if I click refresh at this point, the form submits again. I would like for it just refresh the page, with or without the message it had received from the controller.
Is there any way for me to use the CSRF token to validate this? From what I understand the CSRF token only validates if the session is valid, and has nothing to do with the form itself.
Thanks.

Use return back()
return back()->with(['message' => $message]);

Related

Slim4 PUT and DELETE not recognized when called in the browser

*According to the documentation https://www.slimframework.com/docs/v2/routing/put.html and https://www.slimframework.com/docs/v4/middleware/method-overriding.html I can mimic PUT or DELETE request in Slim4 by adding _method input and by adding Method Overriding Middleware
after the routing middleware. For some reason Chrome does not cooperate with me.
So here is my code:
routes.php:
$app->get('/dashboard', \App\Action\Dashboard::class);
$app->delete('/dashboard', function(Request $request, Response $response ) {
$response->getBody()->write("DELETING");
return $response;
});
$app->put('/dashboard', function(Request $request, Response $response ) {
$response->getBody()->write("ADDING");
return $response;
});
$app->post('/dashboard', function(Request $request, Response $response ) {
$response->getBody()->write("UPDATING");
return $response;
});
middleware.php
use Slim\App;
use Slim\Middleware\ErrorMiddleware;
use Slim\Views\TwigMiddleware;
use Slim\Middleware\MethodOverrideMiddleware;
return function (App $app) {
$app->addBodyParsingMiddleware();
$app->add(TwigMiddleware::class);
$app->addRoutingMiddleware();
$app->add(new Slim\Middleware\MethodOverrideMiddleware);
$app->add(ErrorMiddleware::class);
};
get('/dashboard', ...) displays a simple HTML:
<form action="/dashboard" method="post">
<input type="hidden" name="_METHOD" value="PUT"/>
<button type="submit">Send PUT request</button>
</form>
<form action="/dashboard" method="post">
<input type="hidden" name="_METHOD" value="DELETE"/>
<button type="submit">Send DELETE request</button>
</form>
Regardless which button I press, I got the Unexpected error:
POST header
Surprisingly, when I Chrome ARC to simulate PUT/DELETE requests, proper response is returned. I'm pulling my hairs out because of this. Can anybody show me what I did wrong and why my client (Chrome) is so stubborn?
Thank you in advance for any tip(s).

fatfree framework, repopulate fields after unsuccessful validation

I have GET route which shows the contact form, and POST route when user submits the form, then in my controller method I do some validation tests on data being submitted.. how would I now send user back to form if data is not valid, with entered data being re-populated in form fields?
I know I can use isset(#POST.fieldname) in my template, but what's the right way of
sending entered data back to that view, and how to redirect user back to the
form? Is the f3->reroute method right way of doing that?
I think you can take as a rule to include input data inside your form views. This way, any form view will be easily reusable with any source of data.
For example:
Your form view:
<form action="" method="post">
<input type="text" name="email" value="{{ ##input.email }}"/>
<input type="text" name="message" value="{{ ##input.message }}"/>
<button type="submit">Submit form</button>
</form>
Your controller class:
class myController {
function get($f3) {
$this->renderForm();
}
function post($f3) {
$post=$f3->clean($_POST);
//validate form data here
if ($form_validated) {//valid form data
} else //invalid form data
$this->renderForm($post);
}
protected function renderForm($input=array()) {
$tpl=Template::instance();
//variant 1:
echo $tpl->render('form.html','text/html',array('input'=>$input))
// or variant 2:
Base::instance()->set('input',$input);
echo $tpl->render('form.html');
}
}
In some other contexts, you can feed a form view with data coming from a db mapper (for example when editing an entry from a back-office): $this->renderForm($mapper->cast())

csrf_token symfony2 validate

I'm new working with symfony2 and I have a problem when I try to validate the csrf token in a custom form, my question is ¿how can I validate the csrf token in the controller?
This is my code in my view.
<form role="form" action="{{ path('default_select_city_check') }}" method="post">
<input type="hidden" name="_csrf_token" value="{{ csrf_token('default_select_city_check') }}">
...
</form>
This is my code in the controller:
public function selectCityCheckAction(Request $request) {
// in this part, how can I compare the token value in the form with the token value in the session?
}
Thank you for your help
add a function in your controller:
public function isCsrfTokenValid($intention, $token_name = '_csrf_token')
{
return $this->get('form.csrf_provider')
->isCsrfTokenValid($intention, $this->getRequest()->get($token_name));
}
in your Action:
if ($this->isCsrfTokenValid('default_select_city_check')) {
//do something you want
}

REST Codeigniter, jquery/ajax does not display response

I'm trying to get a helloworld type program working with REST CI/jquery. I've included my (really rudimentary) REST controller, view file and javascript file and am hoping that the error that has eluded me jumps out at you.
Two issues:
The response I get from the server does not get displayed - the screen gets refreshed instead (I know this is some very basic thing I've missed). If I step through the code, I see the display of the result but then, screen gets refreshed. And somehow, I cannot step into my "success" function. Why, oh why?
2.Upon success, I'd like to redirect the user to another url, say, www.google.com. Would I do this in the javascript file? or server side?
Thank you in advance for helping me!
[Added after solving the issue: My problem has nothing to do with REST or Codeigniter. A purely javascript problem]
The REST Controller:
<?php
require APPPATH.'/libraries/REST_Controller.php';
class Myex extends REST_Controller {
function contact_post(){
$result=array();
$fname=$this->post('fname');
$lname=$this->post('lname');
$result['message']="contact_post has your name";
$result['fname']=$fname."XX";
$result['lname']=$lname."YY";
$this->response($result,200);
}
}
?>
The view file:
<?php $this->load->view('includes/header')?>
<div id="input-div">
<form name="cookieform" id="login" method="post">
First Name: <input type="text" name="fname" id="fname" class="text"/>
Last Name: <input type="text" name="lname" id="lname" class="text"/>
<input type="submit" name="submit" value="Submit" id='submit' class="page"/>
</form>
</div>
<div id="resp-div">
response goes here
</div>
<?php $this->load->view('includes/footer')?>
The javascript file:
function postsuccess(output) {
$('#soln-div').html(output.message +'for user '+output.fname+' whose last name is '+output.lname).show('slow');
}
function post_contact() {
$('#submit').click(function(){
var output;
var fdata,res;
var furl=global_siteurl+'/myex/contact';
var fname=$('#fname').val();
var lname=$('#lname').val();
fdata='fname='+fname+'&lname='+lname;
res=$.ajax({
url: furl,
type: 'POST',
dataType: 'json',
data:fdata,
success: function(output) {
postsuccess(output);
}
});
});
}
$(document).ready(function() {
get_contact();
post_contact();
});
You have called your ajax function upon submission of form you can prevent refreshing of page in 2 ways:
(a) Use <input type="button" /> instead of submit call your ajax function on this button or
(b) Use return false; in your success function of ajax request.
You can redirect to any url in javascript using window.top.location = 'url-to-redirect';

Can I use my normal (html) form in Zend Framework?

Can I use my normal (html) form in Zend Framework ? How can I do that & How can I call action in IndexController file?
of course you can ... just use
<form action="/index/action" methode="POST">
to access post arguments use
$this->getRequest()->getParam('argument')
thats no problem, put your form code inside the view script for the associated action. Maybe:
formAction()
{
// check if post request
if ($this->getRequest()->isPost()) {
// read global $_POST array
$data = $this->getRequest()->getPost();
}
}
the associated view ist than form.phtml
Yes, definitely.. You just have to remove the isValid call in your controller since it won't be performing any validation and also remove the post request check if it will not contain any form. It's like creating a common view with simple links in it.
Yes, I have a module called 'contact', and an action addcontactAction() in the ContactController.php.
So I can use :
/view/scripts/contacts/addcontact.phtml
<form action="" method="post" name="frm_addcontact" />
<input name="cn_fname" type="text" class="textbox" id="cn_fname"/>
<input type="submit" class="button" id="save" value="Save" />
</form>
when this form is submitted, it calls addcontactAction() in the controller.
$cn_fname = $_REQUEST['cn_fname'];
Just to know this is not a good practice to implement, but to solve such problem do the following:
in the view file when you define the form
<form action = "<?php echo $this->url(array('action'=>'ACTIONAME')); ?>" ...>
................
</form>
in the corresponding action name
if($this->_request->isPost()){
foreach ($_POST as $var => $value) {
echo "$var = $value<br>";
}