Two different submit buttons in CodeIgniter form without Javascript [duplicate] - php

This question already has answers here:
How to submit a form to two different pages depending on the button clicked, without javascript
(5 answers)
Closed 9 years ago.
I have a form where I can add a new category item.
<form method="POST" action="backend/categories/form">
<input type="text" name="title" value="" />
<button type="submit">Save</button>
<button type="submit">Save and add new</button>
</form>
What I want to do, is that if i click on Save button, it will process a function in controller and redirect me automatically into the previous page (list of categories page), but whenever I click on Save and add new, it should process the function but reload the same page without redirecting to the page which is defined in controller's function.
Controller:
function form($id){
// Process the form
// ...
// Redirect to the category list page
redirect($this->config->item('backend_folder').'/categories');
}
Any tips to achieve it without using the Javascript ?

Use this HTML:
<form method="POST" action="backend/categories/form">
<input type="text" name="title" value="" />
<button type="submit" name="submitForm" value="formSave">SAVE</button>
<button type="submit" name="submitForm" value="formSaveNew">SAVE AND ADD NEW</button>
</form>
Then check the POST data like this:
$formSubmit = $this->input->post('submitForm');
if( $formSubmit == 'formSaveNew' )
redirect($this->config->item('backend_folder').'/categories/form');
else
redirect($this->config->item('backend_folder').'/categories');
Disclaimer: I didn't try that.

This might be helpful for you:
Use this in your save function in your controller. Immediate after Insert/Update code:
$task = $_POST['submit'];
//echo $task //Save or SaveNew depending on pressed button
switch ($task)
{
case 'Save':
$this->session->set_flashdata('message',$this->lang->line('changes_has_been_saved_successfully'));
$link = redirect('cashdrawer/cashdrawerform/12'); //Link after save button with id
break;
case 'SaveNew':
$this->session->set_flashdata('message',$this->lang->line('this_order_has_been_saved_successfully'));
$link = redirect('cashdrawer/cashdrawerform'); //Link after save and new
//echo $link;
}
redirect($link);
And Change your button as:
<button type="submit">Save</button>
<button type="submit">SaveNew</button>

Related

(empty($_POST['submit'])) not working while I can see there is a value in debugger

I have a website where I want to prevent that the user gets to a specific page trough the url. So I only want it to make accessible when they pressed on the submit button on the first page.
The problem is that with this code I automatically go to the index.php?page=home, while $_POST is not empty. If $_POST is not empty I want the user to get on the other page.
This is my html:
<form action="index.php?page=cart" method="post">
<input type="hidden" name = "submit" value = "submit" />
<button type="submit"
name="action"
value="details"
class="btn btn--big btn--big-2 btn--dark">
your details ->
</button>
</form>
This the code I use in the controller:
public function detail() {
if(empty($_POST['submit'])) {
header('Location: index.php?page=home');
exit();
}else {
//Rest of code..
}
When I look in the debugger, there is a $_POST with the value submit, thus this is why I find it so strange.

Prevent Multiple Submitting in one button laravel

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

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;
}

jQuery popup dialog on PHP form that confirms and refreshes page - not working

I have seen what seems like a hundred ways to do what I want but I can't seem to get a single one to work. I have a test page here : http://upcycledonline.com/test/Site/defaultUpCyc.php
What I want to happen is when the user clicks submit a pop window appears saying "Thanks! Your email has been added". When they click 'ok' the pop will close and the page refreshes. Right now I have the pop up going but after clicking the ok button it goes to my PHP page.
FYI: I am new to PHP and Javascript
Here is the form code and Javascript
<div id="signUp">
<script>
function confirmSubmit() {
if (confirm("Are you sure you want to submit the form?")) {
document.getElementById("FORM_ID").submit();
}
return false;
}
</script>
<?php
//if the validation falls back to php, then print the validation error
if (isset($error_message)) echo $error_message;
?>
<form method="post" action="process-form.php" id="emailForm" name="emailForm" target="_self">
<h4>Sign up to be notified when we go live!</h4>
<!--value="<?php if (isset($_POST['email'])) echo $_POST['email'];?>"-->
<label for="email">E-mail</label>
<input type="text" name="email" id="email" />
<!-- onSubmit="alert('Thank you. Your email has been added.')"-->
<input type="submit" name="submit" id="submit" value="Submit" onclick="return confirm('Are you sure?');">
<p>emails will not be shared with third parties</p>
</form>
<script>
<?php echo $validation_js_code;?>
</script>
</div>
You could do a couple things:
move your form processing logic to defaultUpCyc.php, submit the form to that URI and then have defaultUpCyc.php both process the form and reload the page.
Use AJAX, and post the data to process-form.php, this wouldn't require any refresh at all.
Do a redirect in process-form.php to defaultUpCyc.php.

Categories