Javascript form resubmission - javascript

I have a simple HTML/Javascript form which upon submission checks the username and pass with Parse(.com) and shows the right page according to the specific user.
When first submitting the form everything runs great. But when submitting and then returning to the form page (using the browser back button) the submission event is not fired anymore (not even the console.log()). not by pressing the submit button and not by pressing Enter.
Here are some code snippets:
Head:
$(document).ready(function() {
$("#form_login").submit(function(e) {
console.log("In form submit login")
init();
var name = $("#inp_user").val();
var pass = $("#inp_pass").val();
console.log("Name: " + name + " User: " + pass)
login(name, pass);
})
})
Body:
<body>
<div data-role="page" id="page_login" data-theme="a">
<div data-role="header">
<h1>Login Screen</h1>
</div>
<div data-role="content">
<div class="div-widget">
<h3>Login details</h3>
<form id="form_login">
<div data-role="fieldcontain">
<label for="inp_user">User name:</label> <input type="email"
id="inp_user">
</div>
<div data-role="fieldcontain">
<label for="inp_pass">Password</label> <input type="password"
id="inp_pass">
</div>
<input type="submit" id="btn_login" value="Login"></input>
</form>
</div>
<div class="div-widget">
<span id="out_res"></span>
</div>
</div>
</div>
//More div data-role="page" here....
</body>

According to given information I did a new example on jsFiddle. So you forgot mention that you are using jquery-mobile. Furthermore using a <form> does cause behaviour described!
<body>
<div data-role="page" id="page_login" data-theme="a">
<div data-role="header">
<h1>Login Screen</h1>
</div>
<div data-role="content">
<div class="div-widget">
<h3>Login details</h3>
<!-- removed form - as you do not really need it-->
<!-- you may keep it, but you MAY NOT submit the form! -->
<div data-role="fieldcontain">
<label for="inp_user">User name:</label>
<input type="email"
id="inp_user">
</div>
<div data-role="fieldcontain">
<label for="inp_pass">Password</label>
<input type="password"
id="inp_pass">
</div>
<!-- <input type="submit" id="btn_login" value="Login"></input>-->
<!-- instead, make use of button -->
<a id="btn_login" href="#page_2" data-role="button">Login</a>
</div>
<div class="div-widget">
<span id="out_res"></span>
</div>
</div>
</div>
<div data-role="page" id="page_2" data-theme="a">Page 2</div>
<!-- More div data-role="page" here.... -->
</body>
Instead of submitting a form - which causes the problem when hitting "back" within the browser, I decided to use a href - data-role="button". Bound a click handler and prevent-Default if login fails (commented out right now)
$(document).ready(function() {
$("#btn_login").click(function(e) {
console.log("clicked href")
//init(); // commented out as not provided within your question
var name = $("#inp_user").val();
var pass = $("#inp_pass").val();
console.log("Name: " + name + " User: " + pass)
//login(name, pass); // commented out as not provided within your question
/*if (LOGIN_FAILED)
{
console.log("login failed");
e.preventDefault();
}*/
})
})

Related

keep properties after jquery.load

I'm learning javascript/jquery on the go, I'm trying to reload a form but keeping its js properties (required and masked inputs), code and pictures attached.
First image: Masked inputs works like a charm
Second image: The form its fully filled, still working
Third image: The form it reloaded, but no properties applied
The html form (minmized, just the first field)
<div class="card-body" id="clientsAddFormContainer">
<form method="post" action="main/clients/addController.php">
<div class="form-group row" id="clientRutDiv">
<div class="col-lg-6">
<div class="form-group" id="clientRutInnerDiv">
<label class="col-form-label" for="clientRut">RUT <span class="required">*</span></label>
<input type="text" name="clientRut" id="clientRut" class="form-control" placeholder="Ej. 11.111.111-1" required="" data-plugin-masked-input="" data-input-mask="99.999.999-*" autofocus>
</div>
</div>
</div>
</div>
</form>
<footer class="card-footer">
<div class="switch switch-sm switch-primary">
<input type="checkbox" name="wannaStay" id="wannaStay" data-plugin-ios-switch checked="checked" />
</div> Mantenerme en esta página
<button type="button" style="float: right;" class="btn btn-primary" onclick="realizaProceso();">Enviar</button>
</footer>
The JS for realizaProceso()
function realizaProceso(){
var validator =0;
validator += validateRequiredField('clientRut');
if(validator == 0){
var parametros = {
"clientRut" : document.getElementById('clientRut').value,
"tableName" : 'clients'
};
$.ajax({
data: parametros,
url: 'route/to/addController.php',
type: 'post',
success: function (respText) {
if(respText == 1){
if(document.getElementById('wannaStay').checked){
$("#clientsAddFormContainer").load(location.href + " #clientsAddFormContainer");
}else{
window.location = "linkToOtherLocation";
}
}else{
showNotyErrorMsg();
}
},
error: function () {
showNotyErrorMsg();
}
});
}else{
showNotyValidationErrorMsg();
}
}
So my JS check all fields are validated, then prepare the array, and wait for the php binary response, 1 means the data has been inserted to db, if wannaStay is checked reload the div "clientsAddFormContainer" but as I said, it loose the properties.
Please sorry for my grammar or any other related english trouble, not a native english speaker.
Ps. I've removed some code so it could go different than the images.
Thanks in advance!
EDIT!
The original code is
<div class="card-body" id="clientsAddFormContainer">
<form method="post" action="main/clients/addController.php">
</form>
</div>
one the js exec I got
<div class="card-body" id="clientsAddFormContainer">
<div class="card-body" id="clientsAddFormContainer">
<form method="post" action="main/clients/addController.php">
</form>
</div>
</div>
2nd EDIT
I found the answer in other stackoverflow question

AJAX form submission not reloading content

I have seen quite a few questions and answers on here but none seem to fix my issue. I have a form which is loaded from a ajax load call into a div class called dynamic-content. Basically if the form submit button is pressed I want it to reload this form in ajax so that it does the php form validation. My issue is that when the submit occurs I call the ajax load to reload via javascript but it is not triggering and instead its just going back to the current index page. My JS is as follows:
$(document).ready(function () {
//Handle AJAX request from sidebar buttons
var trigger = $('.submit-btn'),
container = $('.dynamic-content');
$(".add-customer-form-btn").submit(function() {
// do something...
alert('test');
container.load('customers/customersaddform.php',$("form").serializeArray());
return false;
});
});
my html form in customersaddform.php which is loaded into dynamic-content div in located main index file.
<?php
//FORM VALIDATION CHECKS
?>
<form action="" method="post">
<div class="form-field add-customer-form">
<div class="container-fluid">
<!-- Stack the columns on mobile by making one full-width and the other half-width -->
<h4>Account Information</h4>
<div class="row">
<div class="col-md-6 label-container">
<div class="input-group input-group-icon">
<input type="text" placeholder="First Name" name="first-name" required/>
<div class="input-icon"><i class="fa fa-user"></i></div>
<div class="input-error-msg"><?php echo $first_name_err;?></div>
</div>
</div>
<div class="row">
<div class=col-md-12 label-container">
<input type="submit" class="add-customer-form-btn submit-btn" value="Submit">
</div>
</div>
</div>
</div>
</form>

Ajax form not submitting form rails

I'm using a super basic google form on my website. I'm using this website to extract the HTML to display it on my website - http://stefano.brilli.me/google-forms-html-exporter/
Once I hit submit, nothing happens. The page is just locked. I'm trying to resubmit it to another page. Here is my code
<div class="row">
<form action="https://docs.google.com/forms/d/e/1FAIpQLSfJQ9EkDN8aggSL9AEB2PK4BGiZgBzLDbS1IPppfSkU1zy-oA/formResponse"target="_self" id="bootstrapForm" method="POST">
<div class="col-sm-6 col-md-3">
<input id="679075295" type="text" name="entry.679075295" class="form-control" >
</div>
<div class="col-sm-6 col-md-3">
<input id="897968244" type="text" name="entry.897968244" class="form-control" >
</div>
<div class="col-sm-6 col-md-3">
<input id="685661947" type="text" name="entry.685661947" class="form-control" >
</div>
<input id="503500083" type="hidden" name="entry.503500083" value="<%= #investment.id %>" >
<div class="col-sm-6 col-md-3">
<button type="submit" value"submit" class="btn btn--primary type--uppercase" >Get Started</button>
</div>
</form>
Here is the ajax script
<script>
$('#bootstrapForm').submit(function (event) {
event.preventDefault()
var extraData = {}
$('#bootstrapForm').ajaxSubmit({
data: extraData,
dataType: 'jsonp', // This won't really work. It's just to use a GET instead of a POST to allow cookies from different domain.
error: function () {
// Submit of form should be successful but JSONP callback will fail because Google Forms
// does not support it, so this is handled as a failure.
alert('Form Submitted. Thanks.')
// You can also redirect the user to a custom thank-you page:
window.location = 'http://reif.com.au/thankyou'
}
})
})
</script>
</div>
Feeling a little silly on this one. Essentially i didn't copy over all of the scripts. I was rushing through.. ALWAYS number 1 error!
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.2.2/jquery.form.min.js" integrity="sha256-2Pjr1OlpZMY6qesJM68t2v39t+lMLvxwpa8QlRjJroA=" crossorigin="anonymous"></script>
This is what i needed to add, it now successfully submits and redirects!

My other forms do not get submitted

So I have created a page to print out a div for every chat in the database and each chat has a form attched to it. When I click on the form, the form gets submitted with the displayed none input and it's value sent to php to do other things. Now the problem is that only the first div's form gets submitted even though the code is the same.The form is right on the div and it is displayed absolute. The two forms are the same but I need both to work and to get to the same php code. Code: HTML
<div class="chaty">
<form method="post" action="index.php" name="chat_lox" id="chat_loc">
<input type="text" name="chat_locy"
value="5e2dbe2be3b5927c588509edb1c46f7d">
</form>
<div class="chatDesc" id="84281145">
<div class="tit">Creator: </div>
<div class="iriss"><i id="close_chatn" onclick="closeChat(84281145)"
class="material-icons">close</i></div>
<form action="mypage.php" method="post">
<div class="authr_name"><button value="John Brown" name="userlink"
class="subm_as_text">Hitsuji</button></div>
</form>
<div class="titd"><h3>Description</h3></div>
<div class="description_chat">jaames</div>
</div>
<span onclick="openChat(84281145)">☰</span>
<div class="chatname"><h3>james</h3></div>
<div class="chatback"></div>
<div class="underlie"><p>Users: 1</p><p> Created: 2017/07/28 07:09:40pm</p>
</div>
</div>
<!-- one that doesn't work -->
<div class="chaty">
<form method="post" action="index.php" name="chat_lox" id="chat_loc">
<input type="text" name="chat_locy"
value="9503e253936e716f18d9c57b4f97d618">
</form>
<div class="chatDesc" id="6179276">
<div class="tit">Creator: </div>
<div class="iriss"><i id="close_chatn" onclick="closeChat(6179276)"
class="material-icons">close</i></div>
<form action="mypage.php" method="post">
<div class="authr_name"><button value="Hitsuji" name="userlink"
class="subm_as_text">Hitsuji</button></div>
</form>
<div class="titd"><h3>Description</h3></div>
<div class="description_chat">The Army of JOhn</div>
</div>
<span onclick="openChat(6179276)">☰</span>
<div class="chatname"><h3>John Army</h3></div>
<div class="chatback"></div>
<div class="underlie"><p>Users: 2</p><p> Created: 2017/07/23 11:31:06am</p>
</div>
</div>
JS
$("#chat_loc").on("click",function() {
$(this).submit();
alert("submitted");
});
PHP
if(isset($_POST['chat_locy']) ? $_POST['chat_locy'] : null){echo "it
worked";}
You can only submit only one form at a time. Try changing the id to a class such that all forms have same class like 'chat_loc'.
For example, change the JavaScript to this:
$(".chat_loc").on("submit", function() {
$(this).submit();
alert("submitted");
});

Trying to perform AJAX with jQuery doesn't work

I'm trying to use AJAX with jquery… this is what I'm trying to do :
<div class="form">
<form name="contact" class="js-form-contact" action="contact.php" method="post">
<div class="clearfix">
<label>Mail</label>
<div class="input">
<input type="text" size="44" name="mail"/>
</div>
<div class="clearfix">
<label>Message</label>
<div class="input">
<textarea rows="6" name="message"></textarea>
</div>
</div>
<!-- recaptcha -->
<br/>
<div class="submit">
<input type="submit" class="btn primary" value="Enviar"/>
</div>
<div id="quote">
<p> :D </p>
</div>
</div>
</form>
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("btn primary").click(function(){
$.ajax({
type: "post",
url: "contact.php",
data: $('.js-form-contact').serialize(),
success: function(data) {
$('.js-form-contact .btn primary').attr("disabled", true);
$('#quote').html("Rock!!");
// $('.column:first-child .box').after('<p class="msg">' + data + '</p>');
}
});
});
});
</script>
the contact.php is just doing "echo "Hello";" for now. When I click the submit button, the browser goes to contact.php and it echoes "Hello"...
What's the problem here? , I'm quite new with JS and jQuery so please bare with my noobishness :)
Your jQuery selector is wrong. It should be $(".btn.primary"). The . denotes that it's a class of the element you're looking for. No whitespace between classes means the element should have all those classes to match.
Furthermore, you should probably use event.preventDefault() to prevent the click-event bubbling up to the organic submit handler.
To put the money where my mouth is...
// Note the parameter in the click-handler declaration
$(".btn.primary").click(function (event) {
event.preventDefault();
// Do ajax magic here
});

Categories

Resources