I am very new to jQuery and I'm looking for an explanation as to why this code does not seem to work. I think it is something with the "action" not sure. Can someone help me understand my mistake here. thanks
<script src="/jquery.validationEngine.js"></script>
<script>
$("#contact_body").submit(function(e) {
e.preventDefault(); // Prevents the page from refreshing
var $this = $(this); // `this` refers to the current form element
if ($("#contact_body").validationEngine('validate')) {
//Post Data to Node Server
$.post(
$this.attr("action"), // Gets the URL to sent the post to
$this.serialize(), // Serializes form data in standard format
function(data) { /** code to handle response **/ },
"json" // The format the response should be in
);
//Notify User That the Email Was Sent to the Server & Thanks!
//$('#contactThanksModal').modal('show');
$('#contactModal').modal('hide');
alert("success");
}
else {
//handle Invalid Email Format Error
alert("error");
}
});
</script>
<!--pop up contact form -->
<div id="contact" class="modal hide fade in" style="display: none;">
<div class="modal-header">
<a class="close" data-dismiss="modal">x</a>
<h3>Send us a message</h3>
</div>
<div class="modal-body">
<form id="contact_body"class="contact_body" name="contact_body" action="/contact">
<label class="label" for="form_name">Your Name</label><br>
<input type="text" name="form_name" id="form_name" class="input-xlarge"><br>
<label class="label" for="form_email">Your E-mail</label><br>
<input type="form_email" name="form_email" class="input-xlarge"><br>
<label class="label" for="form_msg">Enter a Message</label><br>
<textarea name="form_msg" class="input-xlarge"></textarea>
</form>
</div>
<div class="modal-footer">
<input class="btn btn-success" type="submit" value="Send!" id="submit">
Nah.
</div>
<!-- <div id="thanks"><p><a data-toggle="modal" href="#contact" class="btn btn-primary btn-large">Modal powers, activate!</a></p></div> -->
You need to wrap your JQuery scripts in a
$(document).ready(function() {
...your_code_here...
});
This will then wait for the whole document to load before trying to attach events to objects.
Without this you may be trying to bind events to objects that have yet to be "created".
You need to put your code in a document ready handler:
<script src="/jquery.validationEngine.js"></script>
<script>
$(function() {
$("#contact_body").submit(function(e) {
// your code...
});
});
</script>
Your code is currently trying to add the submit() handler before the element exists in the DOM.
Related
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
I have form containing a button, when clicked it displays a modal window with another form containing an input and a send / cancel button.
I want to serialize the data in this modal form and send it to a remote server via AJAX.
For some reason when I look the the console I can't see the serialized data, I can only see Email=
Can someone look at my code and tell me where I'm going wrong please? Should this work?
HTML
<form id="feedbackForm">
<input class="button" id="bad" src="bad.png" type="image">
</form>
<div aria-hidden="true" class="modal" id="modal" role="dialog" tabindex="-1">
<form id="emailForm">
<div class="form-group">
<input class="form-control" name="Email" type="text">
</div>
<div class="modal-footer">
<button class="btn" type="submit">Send</button>
<button class="btn" data-dismiss="modal" id="closeModal" type="button">Cancel</button>
</div>
</form>
</div>
AJAX
<script>
$(document).ready(function() {
var request;
$("#feedbackForm").on("touchstart, click", function(e) {
e.preventDefault();
var serializedData = $("#emailForm").serialize();
$('#modal').modal('toggle');
$("#emailForm").on("submit", function(e) {
e.preventDefault();
request = $.ajax({
url: "MyURL",
type: "post",
data: serializedData
});
request.done(function(response, textStatus, jqXHR) {
console.log(serializedData); // displays Email=
});
});
});
});
</script>
If I understand correctly when the user clicks the touchstart
You serialize the form
You open the modal containing the form
You overwrite the submit event to send your ajax
The thing is that your variable has already been given the values of the form before it is populated with the user data. (If he is opening the modal for the first time)
Just get your data from a function of ajax submit at the correct moment like this:
data: getSerializedData()
and the function
function getSerializedData(){
return $("#emailForm").serialize();
}
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!
I have a really strange problem. My Jquery based form appears to be submitting its self twice.
It only happens when I use the following code to submit my form:
<button class="btn dark"><i id="transfer-spin" class="fa fa-cog"></i> Transfer...</button>
When I use the following, I do not get the double submit:
<input type="submit" value="Transfer" class="btn btn-success dark" id="transfer-button"/>
Here is the code in context:
FORM:
<form class="form-horizontal hidden" id="transfer-form" novalidate>
<fieldset>
<div class="control-group">
<div> </div>
<div class="controls">
<button class="btn dark"><i id="transfer-spin" class="fa fa-cog"></i> Transfer...</button>
</div>
</div>
</fieldset>
</form>
And the JQuery code:
$('#transfer-form').submit(function()
{
event.preventDefault();
//run some error checks
if (messageArray.length !== 0)
{
//Return errors
} else {
$('#transfer-button').prop('disabled', true);
$('#transfer-spin').addClass('fa-spin');
var url ='/api/transfer';
$.ajax({
//Do the ajax call...
You need to pass the event as parameter in submit:
$('#transfer-form').submit(function(event)
Your submit function needs to receive the event object
function (event) {
...
I believe you have to specify the event variable in the function, with that you can prevent default behavior.
$('#transfer-form').submit(function(event)
{
event.preventDefault();
...
}
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
});