jQuery/JS/PHP - Disable Form and Submit button only after submit - javascript

I have a form that I would like to disable the submit button and form itself after it has submitted. The form currently submits to itself and all the solutions I've tried so far either disable the form and submit button, but the form is never submitted or the form is submitted but the button/form are not disabled.
PHP:
<?php
if(isset($_POST['send'])){
if(!isset($_SESSION))
{
session_start();
session_regenerate_id();
}
if($_SESSION['user_login_status']==false)
{header('Location:../index.php');}
$Firstname = $_POST["firstname"];
$Lastname = $_POST["lastname"];
$EmpID = $_POST["employeeid"];
$Ticket = $_POST["ticket"];
$Office = $_POST["office"];
$Division = $_POST["division"];
$Device = $_POST["device"];
$Secure = $_POST["secure"];
$Zendesk = $_POST["zendesk"];
$Agent = $_SESSION['user'];
$psPath = 'c:\\Windows\\System32\WindowsPowerShell\v1.0\\powershell.exe -version 5';
$psDIR = "d:\\wamp64\\www\\includes\\";
$psScript = "NewHire.ps1";
$runCMD = $psPath. ' -ExecutionPolicy RemoteSigned '.$psDIR.$psScript.' -Firstname ' .$Firstname. ' -Lastname '.$Lastname. ' -EmpID ' .$EmpID. ' -Ticket ' .$Ticket. ' -Office ' .$Office. ' -Division ' .$Division. ' -Device ' .$Device. ' -Secure ' .$Secure. ' -Zendesk ' .$Zendesk. ' -Agent ' .$Agent;
$createuser = exec($runCMD, $out);
}
?>
Trimmed down HTML:
<form class="rnd5" method="post" id="frm">
<div class="form-input clear">
<label class="one_third" for="firstname">Firstname <span class="required"><font color="red">*</font></span>
<input type="text" name="firstname" id="firstname" autofocus required>
</label>
</div>
<!-- ################################################################################################ -->
<div class="form-input clear">
<label class="one_third" for="lastname">Lastname <span class="required"><font color="red">*</font></span>
<input type="text" name="lastname" id="lastname" required>
</label>
</div>
<p>
<input type="submit" name="send" value="Submit">
<input type="reset" value="Reset">
</p>
</form>
</div>
<!-- ################################################################################################ -->
<div class="clear"></div>
</div>
</div>
<!-- Footer -->
<?php include('../footer.php'); ?>
</body>
</html>
I have tried different functions such as:
$(function () {
$(".send").click(function () {
$(".send").attr("disabled", true);
$('#frm').submit();
});
});
and
$('input:submit').click(function(){
$('input:submit').attr("disabled", true);
});
Nothing so far appears to be working. Anyone have ideas?

I can see two fundamental problems with your code. Firstly your jQuery selectors.
In the first function: The . selector (as in $(".send") works on the class attribute, not the name attribute. I would suggest you either change your Inputs to have class = send or you change the selector to $("[name=send]").
In the second function. I'm pretty sure $('input:submit') isn't a valid selector, and I'm not sure what is meant by it.
Check out: http://www.w3schools.com/jquery/jquery_ref_selectors.asp
The second problem is that you are submitting the form and thus triggering a page reload. I take it that this isn't the desired behaviour if you want to disable the form buttons? In which case you should disable the default behaviour of the button (There are many ways of doing that: Stop form refreshing page on submit ) and POST the data to the server yourself.
This would leave you with something like the following:
$(function () {
$("[name='send']").click(function () {
$(this).attr("disabled", true);
$("#frm").submit();
});
$("#frm").on("submit",function() {
$.post("http://example.com/your_php_file.php",$(this).serialize());
$(this).preventDefault();
});
});
I haven't been able to test this myself because I don't have much time nor a handy web server, but this should give you a good start.

Related

php $POST[] empty after Ajax call from jquery

Form :
<form method="post" id="loginForm">
<div class="form-group">
<label for="email-signin">Email address:</label>
<input type="email" class="form-control" id="email-signin" name="email-signin">
</div>
<div class="form-group">
<label for="pwd-signin">Password:</label>
<input type="password" class="form-control" id="pwd-signin" name="pwd-signin">
</div>
<div class="checkbox">
<label>
<input type="checkbox"> Remember me</label>
</div>
<button type="submit" class="btn btn-default" id="signIn" name="signIn">Sign In</button>
<div id="error">
<!-- error will be shown here ! -->
</div>
</form>
jquery :
$("#signIn").on("click", function(e) {
e.preventDefault();
var values = $("#loginForm").serialize();
console.log( values );
$.ajax({
type: "POST",
url: "../php/BusinessLayer/User.php",
data: values,
beforeSend: function() { $("#error").fadeOut() },
success : function(response)
{
console.log("Success");
if(response=="ok"){
}
else{
$("#error").fadeIn(1000, function(){
$("#error").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span> '+response+' !</div>');
});
}
}
});
php:
<?php
session_start();
include ("../DataLayer/VO/UserVO.php");
include ("../DataLayer/DAO/UserDAO.php");
// Database Execution for User Related Request
$userDAO = new UserDAO();
print_r($_POST);
if(isset($_POST['signIn']))
{
echo 'test2';
$user = new UserVO();
$user->setEmail(trim($_POST['email-signin']));
$user->setPassword(trim($_POST['pwd-signin']));
// Request signin
$userDAO->signIn($user);
}
Using this code, my if(isset($_REQUEST['signIn'])) in my php file never returns true. I have tried multiple things, and nothing seems to work.
PS : I am using Jquery 1.12.4
Also, my print_r($_POST); returns an empty Array.
jQuery's serialize function does not encode the values of buttons. Taken from here
NOTE: This answer was originally posted by slashingweapon
jQuery's serialize() is pretty explicit about NOT encoding buttons or submit inputs, because they aren't considered to be "successful controls". This is because the serialize() method has no way of knowing what button (if any!) was clicked.
I managed to get around the problem by catching the button click, serializing the form, and then tacking on the encoded name and value of the clicked button to the result.
$("button.positive").click(function (evt) {
evt.preventDefault();
var button = $(evt.target);
var result = button.parents('form').serialize()
+ '&'
+ encodeURIComponent(button.attr('name'))
+ '='
+ encodeURIComponent(button.attr('value'))
;
console.log(result);
});
As far as the var dump being empty on the PHP side, try using jQuery's .click instead of the .on event.
$('#signIn').click(function(){});
Also, remove the method from your form. It looks like the form may be submitting as soon as you click the button. Also, remove
e.preventDefault();
and place
return false;
at the VERY END of the on click function. return false does 3 things
e.preventDefault()
e.stopPropigation();
return immdediatly

Retrieving data from div element and submitting it with post using JQUERY

I am new to Jquery and struggling to retrieve date values from my 'span' element in my jquery code and want to post it along with my form using java script.The reason i need to use this approach is that I am trying to use date range picker provided at http://www.dangrossman.info/2012/08/20/a-date-range-picker-for-twitter-bootstrap/
I have no idea how can i embed my span element value to my form and post it other page along with other form data.
Javscript
<script type="text/javascript">
document.getElementById("btnsubmit").addEventListener("click", function () {
var s;
s=jQuery.data($('aname'),s);
alert(s);
document.form.submit();
});
</script>
FORM:
-
<b class="caret"></b>
<span><?php echo date("F j, Y", strtotime('-30 day')); ?> - <?php echo date("F j, Y"); ?> </span>
</div>
<button id="btnsubmit" onclick="document.getElementById('frmdate').submit();">submit</button>
</form>
All i want to retrieve value of date from span element and post it along with form to retrieve it on next page to filter records from database based on this value.I would appreciate if anybody could help me in this regard.Thanks
As i suggested in the fiddle:
<form action="#">
<b class="caret"></b>
<span>14-10-2014</span>
<input type="hidden" name="tt" value="10-10-2014" />
<input id="tt2"/>
<input type="submit"/>
submit
<form>
And for the java script:
$(document).on('click', '#submit', function(event) {
event.preventDefault();
alert($("input[name='tt']").val()+" - Method 1");
$("#tt2").val($("span").text());
});
$(document).on('submit', 'form', function(event) {
event.preventDefault();
alert($("input[name='tt']").val() + " - Method 2");
$("#tt2").val($("span").text());
});
Don't forget to add the Jquery script.
(In the edit i've included the copy from the span)
Best regards
I think you haven't followed your tutorial properly.
Here is some code from the tutorial, and you will notice it puts the data into an INPUT field which will then be automatically sent as the form data, no added jQuery needed.
<form id="frmdate">
<div class="form-group">
<label for="reservation">Reservation dates:</label>
<div class="controls">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-calendar"></i></span>
<input type="text" name="reservation" id="reservation" />
</div>
</div>
</div>
</form>
<script type="text/javascript">
$(document).ready(function() {
$('#reservation').daterangepicker();
});
</script>
Also in your code you've mixed jQuery and standard javascript badly.
For one you're listening for a click of the button rather than the submit of the form, this means your code will never execute if a enter hits Enter key and it submits the form without clicking the button. Moreover this is bad practice for that reasons alone (and many other reasons)
Here is a cleaned up version of your code:
<form id="frmdate">
...
<b class="caret"></b>
<span id="aname"><?php echo date("F j, Y", strtotime('-30 day')); ?> - <?php echo date("F j, Y"); ?></span>
<button id="btnsubmit" type="sumbit">Submit</button>
</form>
<script type="text/javascript">
$(document).ready(function() {
$('#frmdate').submit(function(){
// Do some code here.
});
});
</script>

How to Login by filling the form in CasperJs

Following is the hlml of the login form that I have
<div class="login_area_user">
<form method="post" action="https://www.tradus.com/login?dest_url=https://www.tradus.com/cart/select-address" id="user-login">
<input type="hidden" value="1" name="form_submit">
<h3 style="display:inline-block;">Already a Member</h3>
<p id="login-main-center-right-descp">You can use tradus login id and password</p>
<div class="login-row">
<label class="colorBlack">Email / Login*</label>
<input class="login-field" type="text" name="name" id="edit-namepopup">
</div> <!-- [/login-row] -->
<div class="login-row">
<label>Password</label>
<input class="login-field" type="password" id="edit-passpopup" name="pass">
</div> <!-- [/login-row] -->
<div class="login-row">
<a class="forgotPassword" href="/forgot_password">Forgot your password?</a>
<!--input type="checkbox" name="remember" /><span>Remember me</span-->
</div>
<div class="login-row">
<input class="login-button" value="Login" type="submit">
</div>
<input type="hidden" name="op" value="Log in">
</form>
</div>
Am using the following code to login :
this.fill('form#user-login', {
'form_submit': 1,
'name': 'abc#gmail.com',
'pass': 'pwd',
'op': 'Log in'
}, true);
But I dont thing its doing the thing for me.
casper.waitForSelector("form input[name='name']", function() {
this.fillSelectors('form#user-login', {
'input[name = name ]' : 'abc#gmail.com',
'input[name = pass ]' : 'pwd'
}, true);
});
Simply use this (see waitForSelector docs).
Firstly, wait for the form to be loaded.
Then fill the form using the selectors.
casper.waitForSelector('form', function(){
this.fill('form', {
'name': 'abc#gmail.com',
'pass': 'pwd'}, true);
});
<!-- wait until a form tag disappears -->
casper.waitWhileSelector('form', function(){
this.echo('selector is no more!');
});
casper.then(function(){
this.echo(this.getTitle());
});
In case anyone else finds this.. I used some combination of these answers - my login form was also in an iframe which added some difficulty, but basically the issue I saw (cookie-based login) is that casper was going to the next step before the server could respond and set the cookie. I added some .wait() callbacks to ensure enough time to get that cookie. It may not be foolproof, but I have yet to have an issue with it
Mind you, the cookie needs to be set EVERY CRAWL
casper.start(config.loginUrl, function() {
console.log("Checking login status # " + config.loginUrl);
// set a wait condition to make sure the page is loaded (particularly iframe in my case)
this.wait(5000,function(){
// switch to iframe (won't be necessary for most)
this.page.switchToChildFrame('login');
// fill out the form
this.fillSelectors("form[name='loginForm']",{
'input#txtUsername' : config.username,
'input#txtPassword' : config.password
});
// click the login button
console.log("Logging In...")
this.click('input.button.login');
// ** give my crappy dev server 5 seconds to respond
this.wait(5000,function(){
console.log('Starting to spider ' + dataObj.start)
// do yo dance
spider(dataObj.start);
});
Hmmm.. Follow that with:
casper.then(function () {
this.evaluate(function () {
$('form#user-login').submit();
});
});

Onclick Redirect Not Firing

I'm trying to redirect a user to another page after clicking on a form submit button.
I'm trying to fire a few events which fill in certain parts of the form automatically then submit the form & finally redirect the user to another page.
Everything works expect the redirect. I have tried a few things but havent gotten the redirect to work after the form submits.
I also don't want to user to be redirected before the form has been successfully submitted.
Here is my code:
<form id="usp_form" method="post" enctype="multipart/form-data" action="">
<input class="usp_input" type="text" name="user-submitted-title" id="user-submitted-title" value="" />
<input class="usp_input" type="text" name="user-submitted-url" id="user-submitted-url" value="">
<input class="usp_input" type="text" name="user-submitted-tags" id="user-submitted-tags" value="">
<input class="usp_input" type="text" name="user-submitted-category" id="user-submitted-category" value="">
<textarea class="usp_textarea" name="user-submitted-content" id="user-submitted-content" rows="5"></textarea>
<input class="hidden" type="hidden" name="user-submitted-name" value="<?php echo $current_user->user_login; ?>">
<input onClick="copyText();copyText2();copyText3();handleClick();" class="usp_input" type="submit" name="user-submitted-post" id="user-submitted-post" value="Submit Post">
</form>
<script language="javascript" type="text/javascript">
function copyText3() {
var output1 = document.getElementById("edit1").innerHTML;
var output2 = document.getElementById("edit2").innerHTML;
document.getElementById("user-submitted-title").value = output1 + ', ' + output2;
}
</script>
<script language="javascript" type="text/javascript">
function copyText2() {
var output1 = document.getElementById("edit1").innerHTML;
var output2 = document.getElementById("edit2").innerHTML;
var output3 = document.getElementById("template").innerHTML;
document.getElementById("user-submitted-tags").value = output1 + ', ' + output2 + ', ' + output3;
}
</script>
<script language="javascript" type="text/javascript">
function copyText() {
var output = document.getElementById("templatebody").innerHTML;
document.getElementById("user-submitted-content").value = output;
}
</script>
<script language="javascript" type="text/javascript">
function handleClick() {
window.location.href='http://website.com/';
}
</script>
The submit button will launch a request, but you are also defining a redirecting request on the button press, so one will override the other (I'm not sure which one, it may depend on the browser).
You may want to fire an Ajax request instead of the standard submit, and do the redirection only when you get the response from the Ajax request so you are sure no information was lost.
You should not code like is but register your functions on the event, outside de HTML (it's always better to separate your HTML, JS and CSS).
You can understand about events bubling here : http://javascript.info/tutorial/bubbling-and-capturing
If you just want to see your code working and don't validate your form, just add "return false ;" at the end of your onclick attribute.
Edit : Oups sorry, you want submit your form, then redirect. You can do this with ajax requests (see http://www.w3schools.com/xml/xml_http.asp) : you submit your form in ajax, then you redirect.
But IMO, It's a serverside behaviour : you probably have a dynamic language (Python, PHP, ASP... ?) which process your form submission. It's here you have to redirect after the process.

Put javascript data into a form

I have the following javascript code:
game.bind('gameover', function(seconds) {
setTimeout(function() {
var rank = game.getRank(seconds);
scorecard.find('.time').text(seconds + ' sec');
scorecard.find('.rank').text(rank[0]);
scorecard.find('.byline').text(rank[1]);
...more code
In the following div this data is displayed (so the js script is working):
<div class="inner">
<h3>Nice job! Your time:</h3>
<h1 class="wobble time"><!-- 15 seconds --></h1>
<h2 class="rank"><!-- Friendly Mallard --></h2>
<h3 class="byline"><!-- (That's pretty good) --></h3>
</div>
Now I want to put the results also in a form so I can post it to the a database (mysql). So I've added a form and put it in the same div:
<form id="form" action="updatescore.php" method="post">
<input type="text" id="time" name="time" value="" />
<input type="text" id="rank" name="rank" value="" />
<input type="text" id="byline" name="byline" value="" />
</form>
Now in the JS I've copied the lines (e.g. scorecard.find('.time').text(seconds + ' sec');) and changed it to look for the id, so . becomes # and passed it in the js like:
scorecard.find('.time').text(seconds + ' sec');
scorecard.find('#time').text(seconds + ' sec');
etc
So this should work I think, but the form inputs stay empty. What am I doing wrong?
Kind regards,
Maurice
If you are just looking to move js variables into your database via updatescore.php you don't need to use a form at all! You can do it with AJAX.
var scoreData = {
time : time,
rank : rank[0],
byline : rank[1]
};
$.post('updatescore.php', scoreData); //done!
Use val() instead of text() for setting the values

Categories