Can't put a delegate method to work - php

I;m using Ajax in a bootstrap PHP page, so i can't use functions inside onsubmit event, since the button didn't exist before, and so, i have to use delegate methods, i understand this.
But, as i don't know what i am doing wrong, im here to ask your help.
I have a <input><button> inside a table, which i feed via Ajax, and i want to validate it's data before submiting, i thought of using a delegate method to do that, the validation is very simple, just don't be empty.
my code is...
<label for="idmat" class="label label-default">mat:</label>
<input placeholder="mat" type="text" class="mat" id="idmat" name="sendmat" size="20" maxlenght="20" /><br />
<button class="btn btn-large btn-success" type="submit" class="btmat" id="btmat">Mat</button>
and my JS is:
$(function(){
$("#btmat").delegate("click",function(){
var matric = $("#idmat").val();
if(matric === ""){
alert("wrong!");
}
});
...etc
I tried changing this .delegate to .on, but it didn't do anything different than before.

You have to bind to the DOM element, and listen for the creation:
jQuery(document).on('click', '#btmat', function() {
var matric = $("#idmat").val();
if(matric === ""){
alert("wrong!");
}
});
Also, your button can't set class twice. You need to change it to this:
<button class="btn btn-large btn-success btmat" type="submit" id="btmat">Mat</button>

Related

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

PHP access name of javascript function that fired in AJAX onclick event

I have several buttons that the user may press to see results from a MySQL database. The onclick event on the button fires an AJAX call that goes out and retrieves the data that coincides with which button was pressed.
One of the following functions is called, depending on which button is pressed.
<script language="JavaScript">
function ChangeText1() {
$("#ajax_content").load("zone_code.php #zone_code1");}
function ChangeText2() {
$("#ajax_content").load("zone_code.php #zone_code2");}
function ChangeText3() {
$("#ajax_content").load("zone_code.php #zone_code3");}
</script>
Following are the buttons on zones.php:
<button type="button" class="active zone" name="z1" onclick="ChangeText1()">Zone 1</button>
<button type="button" class="active_zone" name="z2" onclick="ChangeText2()">Zone 2</button>
<button type="button" class="active_zone" name="z3" onclick="ChangeText3()">Zone 3</button>
Here is the php code that is retrieved from zone_code.php when a button is pressed:
<div id="zone_code1">
<?php echo '<p>' . $all_results[0]['zone_desc'] . '</p>'; ?>
</div>
<div id="zone_code2">
<?php echo '<p>' . $all_results[1]['zone_desc'] . '</p>'; ?>
</div>
<div id="zone_code3">
<?php echo '<p>' . $all_results[2]['zone_desc'] . '</p>'; ?>
</div>
And here is the div on zones.php that is populated by the ajax call:
<div id="ajax_content">
<p>Choose a zone</p>
</div>
Right now, the code works beautifully to call in the zone description for whichever button was pressed, either zone 1, zone 2, or zone 3. But I would also like to know which of the buttons was pressed, whether it was number 1, 2, or 3. There are more operations I would like to do with PHP, based on which of the buttons they pressed.
For various reasons, I cannot make the button into a submit button, or put it between form tags. Nor can I embed a link in the button. The reasons are too complicated to go into here. So I would like to be able to access either the name of the function that fired, or the name of the button that was clicked.
It may seem like a simple thing, but I am a javascript newbie, and am much more comfortable with php. I have tried various if statements in PHP, which of course didn't work, because javascript is client side and PHP is server side. I have been Googling this for a couple of hours, but haven't been able to find anything close enough to my situation to solve this. I'm not including those failed attempts here, for the sake of keeping this as short as I can. Suffice it to say I tried... I really tried.
I would very much appreciate help with this. Thank you, in advance, for your kindness and consideration.
<script language="JavaScript">
function ChangeText1() {
$("#ajax_content").load("zone_code.php?zone=1 #zone_code1");}
function ChangeText2() {
$("#ajax_content").load("zone_code.php?zone=2 #zone_code2");}
function ChangeText3() {
$("#ajax_content").load("zone_code.php?zone=3 #zone_code3");}
</script>
then it should be in zone_code.php's $_GET['zone'] , "1" or "2" or "3" ^^
You can simplify your code like this -
<script language="JavaScript">
function ChangeText(code) {
$("#ajax_content").load("zone_code.php?zoneCode="+code+" #zone_code"+code);
}
</script>
In the HTML now -
<button type="button" class="active zone" name="z1" onclick="ChangeText(1)">Zone 1</button>
<button type="button" class="active_zone" name="z2" onclick="ChangeText(2)">Zone 2</button>
<button type="button" class="active_zone" name="z3" onclick="ChangeText(3)">Zone 3</button>
In your PHP code, you can get the zoneCode as follows -
$zoneCode = $_GET["zoneCode"]
as we said before (see comment) i will do something like that, buttonName is then with post process:
<script language="JavaScript">
function ChangeText(value) {
$("#ajax_content").load("zone_code.php #zone_code"+value, {buttonName:"z"+value});
}
</script>
or like that, buttonName is then send with get process
<script language="JavaScript">
function ChangeText(value) {
$("#ajax_content").load("zone_code.php #zone_code"+value, "buttonName=z"+value);
}
</script>
in both of the upper code you can use $("#zone_code"+value).load("zone_code.php") instead of $("#ajax_content").load("zone_code.php #zone_code"+value)
there is another post about this here
and in your html
<button type="button" class="active zone" name="z1" onclick="ChangeText(1)">Zone 1</button>
<button type="button" class="active_zone" name="z2" onclick="ChangeText(2)">Zone 2</button>
<button type="button" class="active_zone" name="z3" onclick="ChangeText(3)">Zone 3</button>

No POST data after dynamically creating a form and submitting it

I am creating a little shop system for myself (learning purpose) using AngularJS and PHP, and I am stuck with the following problem:
I created a dynamic shopping cart and filled it on ng-click with some information of the clicked object in the list. I saved to a scope variable called scope.cartwhich is then shown by ng-repeat within the shopping cart table. I then also automatically created input fields which are hidden to pass them to the $_POST variable after submit. Because my POST is empty after submitting, I tried to use the ng-submit directive to create a json file out of the scope.cart array at the time the formula is sent, so I can then call it via PHP. But this doesn*t work either. Now I am stuck and have no clue what the problem could be.
However I think that the input field is empty even though the browser adds new fields dynamically in the source code, and when I hit submit there is the state of the empty cart.
Whats the best way to solve my problem and send the AngJS data to the server?
navApp.controller('MainCtrl', ['$scope', '$http', function (scope, http){
scope.submit = function() {
var time = Math.floor(Date.now() / 1000);
http.post('../dampfen/cfg/orders/cart_' + time + '.json', scope.cart).then(function(data) {
alert("Order successfully transferred!");
});
}
}]);
<div class="panel-body">
<table class="table table-hover">
<thead><tr><th colspan="4">Bestellung</th></thead><tbody>
<form name="orderForm" method="POST" ng-submit="submit()" action="index.php?checkout">
<tr ng-repeat="item in cart">
<input type="hidden" name="order[]" value="{{item.id}}" />
<td>1x</td><td><strong>{{item.name}}</strong></td><td>{{item.preis}} <span class="glyphicon glyphicon-euro"></span></td><td><button class="btn btn-xs btn-danger" ng-click="removeFromCart($index)"><span class="glyphicon glyphicon-remove"></span></button></td></tr>
</tbody>
</table>
</div>
<div class="panel-footer">
<p class="text-right"><strong>{{cart.sum}} <span class="glyphicon glyphicon-euro"></span></strong></p>
<p class="text-left"><button type="submit" class="btn btn-sm btn-success">Checkout</button> <button type="button" class="btn btn-sm btn-danger" ng-click="deleteCart()">Warenkorb löschen</button></p>
</form>
<form> elements cannot be child nodes of <tbody> elements.
You can have an entire table inside a form. You can have an entire form inside a table cell.
Anything else leads to browser error recovery that can dump the form outside the table leaving the inputs behind.
Use basic QA. Write valid HTML.

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