Whenever using this form that I made (in Portuguese), refreshing removes all previously entered data from the page. Why does this happen, and how can I fix it? Thank you for your time.
<script type="text/javascript">
function submitForm(){
// Initiate Variables With Form Content
var nome = $("#nome").val();
var email = $("#email").val();
var telefone = $("#telefone").val();
var assunto = $("#assunto").val();
var mensagem = $("#mensagem").val();
$.ajax({
type: "POST",
url: "send-contact2.php",
data: "nome=" + nome + "&email=" + email + "&telefone=" + telefone + "&assunto=" + assunto + "&mensagem=" + mensagem,
cache:false,
success: function (data) {
alert(data);
}
});
}
</script>
<form id="myForm">
<div class="col col-md-6">
<input type="text" name="nome" id="nome" required value="" tabindex="1" placeholder="Nome">
<input type="text" name="email" id="email" required value="" tabindex="2" placeholder="E-mail">
<input type="text" name="telefone" id="telefone" required value="" tabindex="2" placeholder="Telefone">
<select id="assunto" name="assunto" required>
<option value="outros">Outros assuntos</option>
<option value="encomendas">Encomendas</option>
</select>
</div>
<div class="col col-md-6">
<textarea name="mensagem" id="mensagem" cols="29" rows="8" placeholder="Mensagem"></textarea>
</div>
<div class="col col-md-12 ">
<button name ="submit" type="submit" onclick="return submitForm();">Enviar</button>
</div>
</form>
Your function also needs to return false to stop the click event behaviour from submitting the form:
function submitForm(){
// your code...
return false;
}
Better still, hook to the submit event of the form directly and do away with the clunky onclick handlers, and use serialize() to gather the form data for you:
<button name="submit" type="submit">Enviar</button>
<script type="text/javascript">
$(function() {
$('#myForm').submit(function(e) {
e.preventDefault(); // stop form submission
$.ajax({
type: "POST",
url: "send-contact2.php",
data: $(this).serialize(),
cache: false,
success: function (data) {
alert(data);
}
});
}
});
</script>
Try to change onClick action to onSubmit and add return false after method. Like this:
<button name ="submit" type="submit" onsubmit="submitForm(); return false;">Enviar</button>
Good practice will be add method="POST" to your form attributes.
Related
I have a button for a form. When I click the button, the form is created. After being created, the form is not working with Ajax. My script codes are in here. My #testform is not wrong because it's working without creating form. Do you have any ideas?
function addDiv() {
var panel = document.querySelector(".add_new");
var div = document.createElement("div");
div.innerHTML = '<br> <form id="testform" method="POST"> <div class="row" style="padding-left:10rem;"> <div class="col-md-4"> <input type="text" class="form-control" value="" placeholder="Başlık" name="yeniBaslik" required></div> <div class="col-md-4"> <input type="text" placeholder="Açıklama" name="yeniAciklama" class="form-control" value="" name="" required> </div> <div class="col-md-2 text-left"> <button type="submit" class="btn btn-success btn-animated btn-wide addToDatabase">Add to the Database</button> </div> </row> </form> <br>';
panel.appendChild(div);
}
$("#testform").submit(function(e) {
e.preventDefault();
var formData = new FormData($("#testform").get(0));
$.ajax({
url: 'config.php',
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function() {
setTimeout(
function() {
$(".addToDatabase").html("Successfully.");
}, 1000);
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="addDiv()"> Create a form </button>
<div class="add_new"></div>
Since second statement is executed before "div" is created, submit event is not being listened to on the new <form>
function addDiv() {
/*...*/
panel.appendChild(div);
$("#testform").submit(function(e) { /*...*/ });
}
I have a form that I want to use the required attribute, which I believe is from html5 to make sure the user puts in a name before running the ajax to send and email and stays on this page (index.php). The form below works. My problem is that I can't figure out how to a a button called pay that submits the form to pay.php like a regular form submit so the user ends up on pay.php when they click "pay" and I want the form validation to still occur when they click pay and on pay.php I can grab the contactName from the post.
<form id="contactForm" method="post" class="tm-contact-form">
Name: <input type="text" id="contactName" name="contactName" class="form-control" placeholder="Name" required/>
<button type="submit" id="inquire-button" class="btn btn-primary">Inquire</button>
<div id="mail-status"> </div>
</form>
<script type="text/javascript">
$("inquire-button").on('click',function(e){
e.preventDefault();
});
$("#contactForm").on('submit',function(e){
sendContact();
e.preventDefault();
});
function sendContact() {
jQuery.ajax({
url: "mailer.php",
data:'contactName='+$("#contactName").val(),
type: "POST",
success:function(data){
$("#mail-status").html(data);
},
error:function (){}
});
}
</script>
EITHER don't use the click, but only the submit event
$("#contactForm").on('submit', function(e) {
const $btn = $(document.activeElement);
if ($btn.is("#inquire")) {
console.log("Inquire clicked")
e.preventDefault();
jQuery.ajax({
url: "mailer.php",
data: 'contactName=' + $("#contactName").val(),
type: "POST",
success: function(data) {
$("#mail-status").html(data);
},
error: function() {}
});
}
else console.log("Pay clicked")
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="contactForm" method="post" class="tm-contact-form">
Name: <input type="text" id="contactName" name="contactName" class="form-control" placeholder="Name" required/>
<button type="submit" id="inquire-button" class="btn btn-primary">Inquire</button>
<button type="submit" id="pay" class="btn btn-primary">Pay</button>
<div id="mail-status"> </div>
</form>
OR use a button
$("#contactForm").on('submit', function(e) {
console.log("Submitted (pay)")
})
$("#inquire-button").on("click", function() {
if (!this.form.checkValidity()) {
this.form.reportValidity()
return
}
console.log("Inquire clicked")
jQuery.ajax({
url: "mailer.php",
data: 'contactName=' + $("#contactName").val(),
type: "POST",
success: function(data) {
$("#mail-status").html(data);
},
error: function() {}
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="contactForm" method="post" class="tm-contact-form">
Name: <input type="text" id="contactName" name="contactName" class="form-control" placeholder="Name" required/>
<button type="button" id="inquire-button" class="btn btn-primary">Inquire</button>
<button type="submit" id="pay" class="btn btn-primary">Pay</button>
<div id="mail-status"> </div>
</form>
I have multiple forms and I want all of them to be processed by a single jquery script, of course I have php functions that work correctly, I tried them separately.
This is my script:
function proceso_form(type_form, id_div_error){
var url = "my_url.php?form="+type_form; //functions
var response = document.getElementById(id_div_error);
response.innerHTML="<img src='img/loader.gif' style='margin-right: 5px;'/>Loading ..."; //
response.style.display='block';
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(), //ID form
success: function(data)
{
if (data==1){
window.location.reload();
}else{
response.innerHTML=data; // show PHP response.
}
}
});
return false;
};
My form looks like this
<form id="contacto" name="contacto" method="post" onsubmit="proceso_form('contacto', 'cargando')">
<input type="text" name="name"class="form-control">
<input type="text" name="phone" class="form-control">
<input type="email" name="email" class="form-control">
<textarea style="height:100px;margin-bottom:0px" name="messaje" class="form-control"></textarea>
<input style="margin-top:5px" type="submit" class="btn btn-block" value="SEND">
</form>
I think my problem is that I can't put my script in the onsubmit, but honestly I have no idea.
Your html must look like
<form id="contacto" name="contacto" method="post" onsubmit="return proceso_form(this, 'cargando')">
...
</form>
And inside the function:
function proceso_form(form, id_div_error){
var $form = $(form);
var url = "my_url.php?form="+$form.attr('id'); //functions
var response = document.getElementById(id_div_error);
response.innerHTML="<img src='img/loader.gif' style='margin-right: 5px;'/>Loading ..."; //
response.style.display='block';
$.ajax({
type: "POST",
url: url,
data: $form.serialize(), //ID form
success: function(data)
{
if (data==1){
window.location.reload();
}else{
response.innerHTML=data; // show PHP response.
}
}
});
return false;
};
By passing this to the function you passing the whole form reference.
Hope it will help.
First, it should be:
<form id="contacto" name="contacto" method="post" onsubmit="return proceso_form('contacto', 'cargando')">
The return keyword there is important.
Next, data: $(this).serialize(), //ID form should be:
data: $('#'+type_form).serialize(), //ID form
So, your script should look like this:
<script type="text/javascript" src="/path/to/jquery.min.js"></script>
<form id="contacto" name="contacto" method="post" onsubmit="return proceso_form('contacto', 'cargando')">
<input type="text" name="name" class="form-control">
<input type="text" name="phone" class="form-control">
<input type="email" name="email" class="form-control">
<textarea style="height:100px;margin-bottom:0px" name="messaje" class="form-control"></textarea>
<input style="margin-top:5px" type="submit" class="btn btn-block" value="SEND">
</form>
<div id="cargando"></div>
<script>
function proceso_form(type_form, id_div_error){
var url = "my_url.php?form="+type_form; //functions
var response = document.getElementById(id_div_error);
response.innerHTML="<img src='img/loader.gif' style='margin-right: 5px;'/>Loading ..."; //
response.style.display='block';
$.ajax({
type: "POST",
url: url,
data: $('#'+type_form).serialize(), //ID form
success: function(data)
{
if (data==1){
window.location.reload();
}else{
response.innerHTML=data; // show PHP response.
}
}
});
return false;
};
</script>
Explanation :
Here's the situation goes . I'm searching a way to call another Ajax function when the data is success but I'm unable to do due to unknown circumstances.
Code:
---HTML Form :
<form accept-charset="utf-8" id="contactForm1" style="margin-top:;" action="" method="post">
<input class="wf-input wf-req wf-valid__email" type="text" name="email"
data-placeholder="yes" id="email" value="Enter Your Email Here" onfocus="
if (this.value == 'Enter Your Email Here')
{ this.value = ''; }" onblur="if (this.value == '')
{ this.value='Enter Your Email Here';} " style="margin-top:;">
</input>
<br />
<input type="submit" class="wf-button" name="submit1" value=" " style="display: inline !important; margin-top:-10px !important;"></input>
</form>
----Ajax Code :
$(function() {
$('.wf-button').click(function (e) {
e.preventDefault();
var email = $('#email').val();
var frm = this;
$.ajax({
type: 'POST',
dataType: 'JSON',
url: 'check.php',
data: {
email: email
},
success: function (data) {
if (data.status == 'success') {
// Need to place it here
frm.submit();
} else {
alert('The e-mail address entered is not valid.');
}
}
});
});
---Another form with HTML in the same page:-
<form method="post" id ="aweber" class="af-form-wrapper" action="http://www.aweber.com/scripts/addlead.pl" >
<div style="display: none;">
<input type="hidden" name="meta_web_form_id" value="947846900" />
<input type="hidden" name="meta_split_id" value="" />
<input type="hidden" name="listname" value="awlist3599001" />
<input type="hidden" name="redirect" value="http://www.aweber.com/thankyou.htm?m=default" id="redirect_37ecf313df3b6f27b92c34c2c00ef203" />
<input type="hidden" name="meta_adtracking" value="ibb_test" />
<input type="hidden" name="meta_message" value="1" />
<input type="hidden" name="meta_required" value="email" />
<input type="hidden" name="meta_tooltip" value="" />
</div>
<div id="af-form-947846900" class="af-form"><div id="af-body-947846900" class="af-body af-standards">
<div class="af-element">
<label class="previewLabel" for="awf_field-66127140">Email: </label>
<div class="af-textWrap"><input class="text" id="awf_field-66127140" type="text" name="email" value="" />
</div><div class="af-clear"></div>
</div>
<div class="af-element buttonContainer">
<<input name="submitaw" id="submitaw" class="wf-button" type="submit" value="Submit" tabindex="501" />
<div class="af-clear"></div>
</div>
</div>
</div>
<div style="display: none;"><img src="http://forms.aweber.com/form/displays.htm?id=nCzsHCxsnAwM" alt="" /></div>
</form>
Scenarion :
I would when the Ajax trigger when the user click the submit button for the ID ContactForm1.
Before submitting the form , I want the Ajax to send the same value to the other form in the same page and click submit .
How?
try this:
$('#aweber').submit(function (e) {
e.preventDefault();
var email = $('#email').val();
var frm = this;
$.ajax({
type: 'POST',
dataType: 'JSON',
url: 'check.php',
data: {
email: email
},
success: function (data) {alert('first form submitted');
if (data.status == 'success') {
frm.submit();
} else {
alert('The e-mail address entered is not valid.');
}
}
});
});
submit form if success always reload page.
Using ajax post to server.
You can try it:
$.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) ).then( myFunc, myFailure );
http://api.jquery.com/jquery.when/
Here is my form's markup
<form name="contactForm" id="contactForm" role="form">
<div style="width: 190px">
<div class="form-group">
<input type="text" placeholder="fullname" name="fullname" id="formFullname" class="form-control">
</div>
<div class="form-group">
<input type="email" placeholder="email" name="email" id="fromEmail" class="form-control">
</div>
<div class="form-group">
<input type="text" placeholder="company" name="company" id="fromCompany" class="form-control">
</div>
</div>
<div class="clear"></div>
<div class="form-group">
<textarea placeholder="message" name="message" id="formMessage" rows="3" class="form-control"></textarea>
</div>
<button class="btn btn-success" type="submit" name="submit" id="formSubmit">send</button>
</form>
Using jquery 1.10.2
And here is JS
var form = $('#contactForm');
form.submit(function () {
console.log("form ", $(this).serialize());
$.ajax({
type: "POST",
url: url + "ajax/sendmail",
data: $(this).serialize(),
success: function (response) {
console.log(response);
}
});
return false;
});
I know that function fires, tested with alert. But console.log doesnt return anything, and during ajax call I don't see anything in POST (Watching with firebug's XHR).
BTW: role="form" is because i'm using Twitter Bootstrap framework
What am I doing wrong?
UPDATE
data: $(form).serialize() didn't help also
If you try this :
form.submit(function () {
console.log("form ", $(this).serialize());
return false;
});
it works just fine. So I think the problem
form.on('submit',function () {
event.preventDefault();
console.log("form ", $(this).serialize());
$.ajax({
type: "POST",
url: url + "ajax/sendmail",
data: $("form").serialize(),
success: function (response) {
console.log(response);
}
});
return false;
});
Because $(this) in your code doesn't refer to the form but instead refers to jQuery on which the ajax method is called
Try the following code, but first modify your form HTML so that is has an "action" attribute. The nice thing about this code is that it can be used on any form which has a submit button and an action attribute. (i.e. it is not coupled to any specific IDs)
$(function() {
$('input[type="submit"]').click(function(event) {
event.preventDefault();
var form = $(this).closest('form');
var url = form.attr('action');
var data = form.serialize();
$.post(url, data)
.done(function() {
alert('Yay! your form was submitted');
})
.fail(function() {
alert('Uh oh, something went wrong. Please try again');
});
});
Cheers.