AJAX form submission not reloading content - javascript

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>

Related

Submitting form on same loaded page if the page is loaded via ajax

So i have a PHP page that is loaded via AJAX using the .load method.
This is then displayed on my page, however i need to be able to submit the form that is located on my second page that im loading using .load, submit this form and process the data on the same page without it reloading.
I'm very new to javascript and AJAX so i've no idea if i'm evening doing this correct using .load()
Any help would be appreciated.
page 1 is the following:
<button onclick="Test()" type="button">Load Content</button>
<div class="box" id="box" name="box">
</div>
<script>
function Test(id) {
$( "#box" ).load( "test.php?id=" + id );
}
</script>
The second page which is test.php houses the following
<form id="enrolemployee" action="" method="post">
<div class="form-group">
<label>Test</label>
<input type="text" class="form-control" id="Test" name="Test" placeholder="Test">
</div>
<input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
<button type="submit" class="btn btn-outline-custom">Submit</button>
</form>
Now to submit the form on test.php i use a custom token class to generate a random hash per form submit so i can validate the data on the same page and process it through my database.
is this possible to do? or do i need to have my form then post the data through a different page?
Basically i need the entire thing to stay on PAGE 1, process the form like it normally should whilst the persons page does not reload and is always static on page 1, this should never redirect to test.php
Thankyou.
You can do it like
index.php
<button onclick="Test('10')" type="button">Load Content</button>
<div class="box" id="box" name="box">
</div>
<script src="//code.jquery.com/jquery-latest.js"></script>
<script>
function Test(id) {
$("#box").load("test.php?id=" + id);
}
</script>
test.php
<form id="enrolemployee" action="" method="post">
<div class="form-group">
<label>Test</label>
<input type="text" class="form-control" id="Test" name="Test" placeholder="Test">
</div>
<input type="hidden" name="token" value="">
<button type="submit" class="btn btn-outline-custom">Submit</button>
</form>
<script>
$("#enrolemployee").on('click', e => {
// Avoid reloading page
e.preventDefault();
console.log(<?php echo $_GET['id']; ?>);
})
</script>

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

Javascript form resubmission

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();
}*/
})
})

Categories

Resources