Prevent Multiple Submitting in one button laravel - php

Before i make this question i use javascript method to prevent multiple submit on my blade template. But i know it's client side that still possible to get attack by.
This is my javascript code
<script>
function submitForm(btn) {
// disable the button
btn.disabled = true;
// submit the form
btn.form.submit();
}
</script>
<input id="submitButton" type="button" value="Submit" onclick="submitForm(this);" />
my question is, is there another way to prevent without client side in laravel?

The most straightforward way to guarantee the uniqueness of a form submission (In the sense of stopping someone mashing submit twice) is to generate a random token and storing it in a session AND a hidden field.
If it doesn't match, reject the form, if it does match, accept the form and nuke the session key.
OR
Force Laravel to regenerate a new session token after each time a token is verified correctly. (Easy Way Out)
To achieve this, create a new function tokensMatch() in app/Http/Middleware/VerfiyCsrfToken.php (which will overwrite the inherited one). Something like this:
protected function tokensMatch($request)
{
$tokensMatch = parent::tokensMatch($request);
if ($tokensMatch) {
$request->session()->regenerateToken();
}
return $tokensMatch;
}
In case you validate the form and the validation fails, the old data will be passed back to the form. So you need to make sure not to pass back the old token by adding _token to the $dontFlash array in app/Exceptions/Handler.php
protected $dontFlash = ['password', 'password_confirmation', '_token'];

Step 1: write a class name in the form tag Exp: "from-prevent-multiple-submits"
<form class="pt-4 from-prevent-multiple-submits" action="{{ route('messages.store') }}" method="POST">
#csrf
Step 2:
Write a class in button section
<button type="submit" id="submit" class="btn btn-primary from-prevent-multiple-submits">{{ translate('Send') }}</button>
Step 3:
write this script code
<script type="text/javascript">
(function(){
$('.from-prevent-multiple-submits').on('submit', function(){
$('.from-prevent-multiple-submits').attr('disabled','true');
})
})();
</script>

give id to submit button
<input class="main-btn" id="register" type="submit" value="Make Appointment">
give id to form
<form id="appointment_form" method="post" action="{{route('appointment')}}">
in your js add these
$('#appointment_form').on('submit', function () {
$('#register').attr('disabled', 'true');
});

Step 1: give id to form
<form action="{{ route('web.reports.store') }}" method="POST" enctype="multipart/form-data" id="kt_stepper_form">
Step 2: give id or add class to submit button
<button type="submit" class="btn btn-primary submit-btn" data-kt-stepper-action="submit">
<span class="indicator-label">
Submit
</span>
<span class="indicator-progress">
Please wait... <span
class="spinner-border spinner-border-sm align-middle ms-2"></span>
</span>
</button>
Step 3: and then, you can add some jquery script like this
$('#kt_stepper_form').on('submit', function(){
$('.submit-btn').attr('disabled', true);
$('.indicator-label').hide();
$('.indicator-progress').show();
});
with code above, button will be disabled and show indicator progress when user clicked the button

Related

Copy / Paste Data in Ajax Live Search

I'm working with Ehsan Abbasi's Ajax Live Search (ALS)
https://github.com/iranianpep/ajax-live-search
http://ajaxlivesearch.com/
which invokes MySQL, PHP & jQuery to search and display search suggestion results as you type (similarly to popular search engines).
I'm struggling with the following:
When the user copies data and pastes it into the form, thereby rendering the live search pointless, what is the syntax to pass that data into the submitted form?
What does "onResultEnter" refer to? The user hits the enter button?
What does "onAjaxComplete" refer to? The user clicks a submit button?
Here's my relevant work to put these issues into context.
First, we initialize some variables and connect to our database via PHP:
# Live search initialization.
# --
file_exists($_SERVER['DOCUMENT_ROOT'].'/als/core/Handler.php') ? require_once $_SERVER['DOCUMENT_ROOT'].'/als/core/Handler.php' : die('Handler.php not found');
file_exists($_SERVER['DOCUMENT_ROOT'].'/als/core/Config.php') ? require_once $_SERVER['DOCUMENT_ROOT'].'/als/core/Config.php' : die('Config.php not found');
use AjaxLiveSearch\core\Config;
use AjaxLiveSearch\core\Handler;
if (session_id() == '') {
session_start();
}
$handler = new Handler();
$handler->getJavascriptAntiBot();
# Connect to database.
# --
require_once($_SERVER["DOCUMENT_ROOT"]."/connect.php");
global $dbc;
# Initialize required CSS and JavaScript files to be included.
# --
$additional_css = "<link href=\"/als/css/ajaxlivesearch.css\" rel=\"stylesheet\" type=\"text/css\" />";
$additional_js = "<script type=\"text/javascript\" src=\"/als/js/ajaxlivesearch.js\"></script>";
We next include two distinct forms to execute unrelated searches:
<!-- Model number search form -->
<form role="form" id="productsSearch" action="search-models.php" method="get" class="search-form">
<div class="input-group">
<input type="text" name="model_number" id="models" class="form-control modelSearch" placeholder="Enter your model number">
<input type="hidden" name="model_number" id="model_number">
<span class="input-group-btn">
<button type="submit" class="btn btn-default" onclick="return model_validator();">Go</button>
</span>
</div>
</form>
<!-- Part number search form -->
<form onsubmit="return part_validator();" action="search-parts.php" role="form" method="get">
<div class="input-group">
<input type="text" name="part_number" id="parts" class="form-control partSearch" placeholder="Enter your part number">
<input type="hidden" name="part_number" id="part_number">
<span class="input-group-btn">
<button type="submit" class="btn btn-default">Go</button>
</span>
</div>
</form>
Note here that the model search form involves an onclick event to validate model numbers. Similarly, the part number search form invokes an onsubmit event to validate part numbers. Both of these events were in our custom code before ALS entered the picture.
In addition, we have included a hidden field in each form to contain the value selected by the user in the ALS to be passed into the form when submitted to the action scripts.
These hidden field values are set in ALS functions associated with each of these input forms:
<!-- Model search: ALS functions -->
<script>
jQuery(document).ready(function() {
jQuery(".modelSearch").ajaxlivesearch({
onResultClick: function(e, data) {
// Get the index 0 (first column) value.
var selectedOne = jQuery(data.selected).find('td').eq('0').text();
// Set the input value.
jQuery('#models').val(selectedOne);
// Hide the result.
jQuery("#models").trigger('ajaxlivesearch:hide_result');
// Set the hidden field value.
$('input[name=model_number]').val(selectedOne);
},
onResultEnter: function(e, data) {
// What does this refer to? The user hits the enter button?
},
onAjaxComplete: function(e, data) {
// What does this refer to? The user clicks a submit button?
}
});
})
</script>
<!-- Part search: ALS functions -->
<script>
jQuery(document).ready(function() {
jQuery(".partSearch").ajaxlivesearch({
onResultClick: function(e, data) {
// Get the index 0 (first column) value.
var selectedOne = jQuery(data.selected).find('td').eq('0').text();
// Set the input value.
jQuery('#parts').val(selectedOne);
// Hide the result.
jQuery("#parts").trigger('ajaxlivesearch:hide_result');
// Set the hidden field value.
$('input[name=part_number]').val(selectedOne);
},
onResultEnter: function(e, data) {
// What does this refer to? The user hits the enter button?
},
onAjaxComplete: function(e, data) {
// What does this refer to? The user clicks a submit button?
}
});
})
</script>
I'd very much appreciate any help troubleshooting the syntax to get data that's copied by users from unknown sources & pasted into either of these forms and passed into the form action search scripts. Any light that could be shed on the onResultEnter and onAjaxComplete functions would likewise be welcomed.
If there's any additional information I can pass along to assist troubleshooting, do please let me know!
Best,
Allison

Angularjs: how to Call method in Controller while submitting the Form

Actually In my form page of Angularjs, have two submit buttons i.e In one field set i have one button for update and another button at the outside of all field sets for submission of whole page.
Code
<form ....... data-ng-submit="Register()">
<fieldset>
............
.............
<div data-ng-submit="update()">
<button type="submit" class="btn btn-success">Update Vehicle</button>
</div>
</fieldset>
<fieldset> .........</fieldset>
</form>
After submission of form to the ctrl
.ctrl(function(){
**we have two methods in it.......**
$scope.update=function(){
}
$scope.register=function(){
}
}
While updating the fieldset it goes to register method and its executes the logic in it.
how to format the data-ng-submit="update()", such that it will call the update() method in Controller

Codeigniter: Change form_open action value with javascript

Working on a Login/Signup form which has the same Email and Password fields. I have to buttons at the end of the form:
<input class="loginButton" type="submit" name="submit" value="Login">
<input class="loginButton" type="submit" name="submit" style="display:none;" value="Sign Up">
Based on the user selection I will keep show/hibe between these two buttons.
Is there way I can toggle between action url of create_user and login.
I am using ion_auth as login framework.
When you show/hide buttons depending on user's selection you can also change the action of your form, using something like this, (it's an idea but your case is different)
$('form > input:button').on('click', function(){
var action = $('form').attr('action') == 'myAction.php' ? 'someAction.php' : 'myAction.php' ;
$('#myForm').attr('action', action);
});
DEMO.
This will change the action to someAction.php if it's action is set to myAction.php, and it'll set the action to myAction.php when it's set to someAction.php.
But, in your case, I think, you should use, something like this (pseudo code)
if(login button is visible){
// set action to login
}
else {
// set action to create_user
}

Change a form in order to use jQuery and avoid the page refresh

I'm trying to change the form tag below in order to use jQuery. Already, clicking the buttons changes the display from rows to columns and vice-versa but I want to avoid the page refresh. I'm really new at jQuery and can't honestly say what my mistakes are when trying to change it myself.
<form id="rowsToColumns" action="index.php?main_page=specials&disp_order=1" method="POST">
<input type="hidden" name="style_changer" value="columns"/>
<button type="submit" class="btn btn-large btn-primary" type="button">Change to Column</button>
</form>
<form id="columnsToRows" action="index.php?main_page=specials&disp_order=1" method="POST">
<input type="hidden" name="style_changer" value="rows"/>
<button type="submit" class="btn btn-large btn-primary" type="button">Change to Rows</button>
</form>
I'm also trying for the buttons to call a different stylesheet upon click. This stylesheet is not needed for the display to change from/to rows/columns as I mentioned above. The actual page is written using php as shown below:
<?php $this_page = zen_href_link($_GET['main_page'], zen_get_all_get_params()); ?>
<div id="style_changer">
<?php if($current_listing_style == 'rows') {?>
<form id="rowsToColumns" action="<?php echo $this_page;?>" method="POST">
<input type="hidden" name="style_changer" value="columns"/>
<button type="submit" class="btn btn-large btn-primary" type="button">Change to Column</button>
</form>
<?php } else { ?>
<form id="columnsToRows" action="<?php echo $this_page;?>" method="POST">
<input type="hidden" name="style_changer" value="rows"/>
<button type="submit" class="btn btn-large btn-primary" type="button">Change to Rows</button>
</form>
<?php } ?>
</div>
If the question is "how to change a form in order to use jQuery and avoid the page refresh", then the jquery form plugin is your friend, as it turns any html form into an ajax-powered one.
Simply follow their instructions and you'll get it working in no time (provided your form already works as is).
You can prevent the Default form Submission by preventing the default action on the submit button..
$('button[type=submit]').submit( function(e){
e.preventDefault(); // Stops the form from submitting
});
Well, for a very vague method you can use $.ajax and take advantage of reading the <form>'s pre-existing attributes to decide on submission method and read the elements' values as submissiong data:
$('form').on('submit',function(e){
var $form = $(this);
// submit the form, but use the AJAX equiv. instead of a full page refresh
$.ajax({
'url' : $form.attr('action'),
'method' : $form.attr('type'),
'data' : $form.serialize(),
'success' : function(response){
// process response (make CSS changes or whatever it is
// a form submission would normally do)
}
});
// prevent the normal submit and reload behavior as AJAX is now
// handling the submission
e.preventDefault();
});
However, for this to work you'll need some variation of a stripped-down PHP response just for the purpose of the AJAX request (avoid resending headers, script tags, etc. and just return the raw data that jQuery can use to make a UI decision).

form submits before validation in php

I have a form which I want to submit, so when I click on submit it goes to the selectorpage.php and finds the selected function type e.g. login in this, which further calls the controller to execute the function. Issue I have is that there is a function called validateForm() in js, as soon as I click the submit button, it goes to the selectorPage.php. I wanted to stop the form submission, perform validation through js and then submit the form from there, I used onsubmit = return false; in form tag but it just blocks the form of doing anything further. And I also don't know how to redirect the form to the selectorPage if it somehow works in js. So anybody would like to give me an idea how to submit form from js and then redirect that page to selectorPage.php. Thanks
<form method="post" action="selector.php?type=login" id="login" id="loginForm">
<div class="row">
<div class="offset1 span1">
<div class="lbel">
<label class="control-label" for "loginName">
Username/Email
</label>
</div>
<div class="lbl_inpuCnt">
<input type="text" class="input-xlarge" id="loginName"
name="loginName" maxlength="50"/>
</div>
<div id="usernameError"> </div>
<div class="lbel">
<label class="control-label" for="loginPassword">
Password
</label>
</div>
<div class="controls">
<input type="password" class="input-xlarge"
id="loginPassword" name="loginPassword"
maxlength="50"/>
</div>
<div id="passwordError"> </div><br/>
</div>
</div>
<div style="margin-left: 55px;">
<input class="btn" style="width: 80px;" type="reset"
name="reset" value="Reset"/>
<input class="btn" style="width: 80px;" type="submit"
name="submit" value="Login" onclick="validateForm();"/>
</div>
</form>
this is the javascript according to the code above
function validateForm(){
form = document.forms['loginForm'];
if(document.getElementById('loginName').value == "")
document.getElementById('usernameError').innerHTML = 'Invalid username or email';
else{
document.getElementById('usernameError').innerHTML = "&nbsp";
form.submit();
}
} //suppose it for the email validation only for the time being
you could try
<form ... onsubmit="return validateForm();"
in the validateForm() function use
return true / false
depending if errors are found.
Here is the canonical way using inline event handling - see further down how it could be made unobtrusive. Also only have ONE id on the form tag, also NEVER call anything submit in a form it is a reserved word and will block submitting by script (which is what you tried to do)
<form id="loginform" ... onsubmit="return validate(this)">
<div style="margin-left: 55px;">
<input class="btn" style="width: 80px;" type="reset" name="reset" value="Reset" onclick="clearFields()"/>
<input class="btn" style="width: 80px;" type="submit" value="Login" />
</div>
</form>
this is the javascript
function validateForm(form){ // passing form object
document.getElementById('usernameError').innerHTML = ""; // reset
if (form.loginName.value == "") {
document.getElementById('usernameError').innerHTML = "Invalid username";
return false;
}
return true;// allow submission
}
Alternative
<form id="loginform" ..... No event handler here ...>
Script:
window.onload=function() {
document.getElementById("loginform").onsubmit=function() {
document.getElementById('usernameError').innerHTML = ""; // reset
if (this.loginName.value == "") { // notice the "this"
document.getElementById('usernameError').innerHTML = "Invalid username";
return false;
}
return true;// allow submission
}
}
I've had similar issues to this in the past myself.
When you click the 'Login' button of your form, you are triggering two separate events - Calling of the 'validateForm();' javascript function, and submission of the form itself. The problem here, is that submitting the form involves the browser sending an outbound request back to the form target, and to my knowledge, there is no way, using javascript, to kill a request event once it has been triggered.
Using 'onsubmit=return false;', likely, is doing exactly what it is supposed to do - Exiting the current javascript scope (and therefore preventing further javascript associated to that particular event from executing). However, unfortunately, the submission of the form itself, while possible to trigger and control via javascript, is not actually handled by javascript and is not a javascript function itself.
What I've found, in my experiences, to be the best solution, is to use the 'button' type input instead of the 'submit' type input - Both 'submit' and 'button' appear as buttons, but 'button' doesn't actually have any default inherent associated event action (therefore, doesn't actually do anything when you click on it) - What this means, is that, via event handlers (such as 'onclick', as you've done), you are able to entirely control what happens when a user clicks on a 'button'.
You haven't included your 'validateForm();' javascript function here, so I don't know what it contains, but, if it doesn't already do so, I'd include code to submit the form via that javascript function, submitting the form once validation has been successful (or returning some sort of human readable error if validation fails) - That combined with using 'button' instead of 'submit' should solve your problem.
Hope this helps. :)
Edit: Thought of this shortly after making my initial reply. Some browsers will process events handlers such as 'onclick' prior to submitting forms via the submit input type; However, I've found that certain older browsers do not do this currently (thus context of my above post). For newer browsers that honour the results of event handlers processed prior to form submission, it should be possible to prevent the second event (form submission) from occurring at all if validation fails; However, not all browsers honour these results, and I've found that some will continue to submit the form regardless of those results.
well thanks u all, so finally I found the solution by your ideas here is what I have done
rather putting return formvalidate(); function I put it in submit onclick event and it run like charm... thanks
<div style="margin-left: 55px;">
<input class="btn" style="width: 80px;" type="reset" name="reset" value="Reset" onclick="clearFields()"/>
<input class="btn" style="width: 80px;" type="submit" name="submit" value="Login" onclick="return validateForm();"/>
</div>
this is the javascript
function validateForm(){
var form = document.forms['loginForm'];
if(document.getElementById('loginName').value == "")
document.getElementById('usernameError').innerHTML = 'Invalid username or email';
else{
form.submit();
}
return false;
}

Categories