AJAX Form is submitting to itself? - javascript

I don't know what is going on here tonight, but I can't seem to get AJAX working. When the form is submitted, it refreshes the page with the values in the URL. I'm using a validate plugin that has a submit handler, but it still refreshes. I've used this method before and have had no problems. Take a look at the page here and let me know what you think:
http://www.jacobsmits.com/demos/jquery_ajax.html?firstName=&lastName=&email=&message=&contactSubmit=
<div class="demo_content" style="display:none">
<form id="contact_form">
<span class="inputSpan">
<input value="" class="input input1" title="First name" id="firstName" name="firstName" type="text" />
</span>
<span class="inputSpan">
<input value="" class="input input2" title="Last name" id="lastName" name="lastName" type="text" />
</span>
<span class="inputSpan">
<input value="" class="input input2" title="Email" id="email" name="email" type="text" />
</span>
<span class="inputSpan">
<textarea type="text" id="message" name="message" title="Message" class="input textArea" ></textarea>
</span>
<span class="inputSpan">
<input type="submit" name="submit" class="button" id="submit_btn" value="Send" />
</span>
<div id="contact_ajax_wrap">
<div id="contact_ajax_gif" style="display:none;"><img src="http://www.jacobsmits.com/images/main/ajax-loader-black.gif" width="32" height="32" /></div>
<div id="contact_ajax_success" style="display:none">Thanks! I'll get back to you shortly.</div>
</div>
</form>
<script type="text/javascript">
//This script will handle the email form
$(window).load(function() {
$('#contact_form').placeholderRX({textColor: '#999', hoverColor: '#FBFBFB', addClass: 'yourFormInputText'});
});
$(".button").click(function() {
var dataString = "fname=" + $("#firstName").val();
alert(dataString);
$.ajax({
type: "POST",
url: "http://www.jacobsmits.com/demos/scripts/contact_form.php",
data: dataString,
success: function(result) {
if(result == "Success"){
alert("Success");
}else{
alert("Fail");
}
}
});
});
</script>

You need to cancel the default behaviour of the submit button(submit the form not ajax).
It can be done with preverntDefault() on the event object or with return false;
$(".button").click(function(e) {
var dataString = "fname=" + $("#firstName").val();
alert(dataString);
$.ajax({
type: "POST",
url: "http://www.jacobsmits.com/demos/scripts/contact_form.php",
data: dataString,
success: function(result) {
if(result == "Success"){
alert("Success");
}else{
alert("Fail");
}
}
});
return false; /// <=== that was missing.
e.preventDefault(); /// Or this.
});
There is a submit event, so better listen to this event instead of the click button:
$("#contact_form").submit(function(e) {
var dataString = "fname=" + $("#firstName").val();
alert(dataString);
$.ajax({
type: "POST",
url: "http://www.jacobsmits.com/demos/scripts/contact_form.php",
data: dataString,
success: function(result) {
if(result == "Success"){
alert("Success");
}else{
alert("Fail");
}
}
});
return false; /// <=== that was missing.
e.preventDefault(); /// Or this.
});

you need to cancel the default behaviour of submit button
$(".button").click(function(e) {
e.preventDefault();
//rest of your code here
var dataString = "fname=" + $("#firstName").val();
alert(dataString);
$.ajax({

Related

How to submit form using AJAX without having to leave the page HTML Formsubmit

I'm using Formsubmit to send contact us form to my email and so far it's working.
But I would like when user send the form it does not redirect it to the source thank you page instead I'd like to display just thank you text on the same page. I'd like to use my own.
So I followed the documentation and I came up with the following :
Unfortunately when I try validate the form button it does not work
<form id="contactForm" action="https://formsubmit.co/el/myemail" method="POST">
<input type="text" name="name">
<input type="phone" name="phone" inputmode="tel">
<input type="hidden" name="_subject" value="Partenaires">
<input type="email" name="email" >
<input type="text" name="message" >
<button class="btn btn-primary border rounded-0 shadow-lg d-lg-flex justify-content-lg-center"
type="submit" name="sendData">Send</button>
<!-- <input type="hidden" name="_next" value="thanks.html">-->
<script type="text/javascript">
var frm = $('#contactForm');
var msg_res ='';
frm.submit(function (e) {
e.preventDefault();
$.ajax({
type: frm.attr('method'),
method: "POST",
url: "https://formsubmit.co/el/vupawa",
dataType: 'html',
accepts: 'application/json',
data: frm.serialize(),
success: function (response) {
$("#message").html(response);
if(response != msg_res){
msg_res = response; //store new response
alert('New message received');
}
},
error: function (response) {
console.log('An error occurred.');
console.log(response);
}
complete: function(response){
setTimeout(ajax,1000);
}
});
});
});
</script>
Note : that uncommenting this line <input type="hidden" name="_next" value="thanks.html"> will take validate the form and go through another page which is not what I want here.
Any ideas ?
To Prevent Submission You should return false in
frm.submit(function (e) {
return false;
})
Or in form tag
<form onSubmit="return false">
var frm = $('#contactForm');
var msg_res ='';
frm.submit(function (e) {
e.preventDefault();
$.ajax({
type: frm.attr('method'),
method: "POST",
url: "https://formsubmit.co/el/vupawa",
dataType: 'html',
accepts: 'application/json',
data: frm.serialize(),
success: function (response) {
$("#message").html(response);
if(response != msg_res){
msg_res = response; //store new response
alert('New message received');
}
},
error: function (data) {
console.log('An error occurred.');
console.log(data);
}
});
return false; // here a change
});
<form id="contactForm" action="https://formsubmit.co/el/myemail" method="POST">
<input type="text" name="name">
<input type="phone" name="phone" inputmode="tel">
<input type="hidden" name="_subject" value="Partenaires">
<input type="email" name="email" >
<input type="text" name="message" >
<button class="btn btn-primary border rounded-0 shadow-lg d-lg-flex justify-content-lg-center"
type="submit" name="sendData">Send</button>
<!-- <input type="hidden" name="_next" value="thanks.html">-->

Unable to get email address onclick function [duplicate]

This question already has answers here:
Get value of input in jQuery
(5 answers)
Closed 6 years ago.
<div id="divForm" class="fancybox" style="display:none;">
<form id="frm_step1" action="download1.php" method="post">
<label>Enter Email</label>
<input type="email" name="email" id="email" value="" required />
<input type="button" name="submit" id="submit" value="Submit" class="form-submit" target-form="frm_step1" onclick="test();" />
</form>
</div>
function test() {
var email = $('#email').text();
alert(email);
$.ajax({
type: "POST",
dataType: "json",
url: 'download1.php?email' + email,
data: { 'email': email },
success: function(data) {
window.location.href = 'download.php#file';
},
error: function(e) {
alert('Error: ' + e);
}
});
}
I am not able to get email from this. When I put alert it returns blank.
And I always use jQuery/AJAX like this but this time it does not alert email address.
Use .val() instead of .text(). The .val() method is primarily used to get the values of form elements such as input, select and textarea.
$('#email').val();
function test() {
var email = $('#email').val();
alert(email);
$.ajax({
type: "POST",
dataType: "json",
url: 'download1.php?email' + email,
data: { 'email': email },
success: function(data) {
window.location.href = 'download.php#file';
},
error: function(e) {
alert('Error: ' + e);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divForm" class="fancybox">
<form id="frm_step1" action="download1.php" method="post">
<label>Enter Email</label>
<input type="email" name="email" id="email" value="" required />
<input type="button" name="submit" id="submit" value="Submit" class="form-submit" target-form="frm_step1" onclick="test();" />
</form>
</div>

Avoid Refreshing page submiting the form

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.

Submit multiple forms same jquery script

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>

Submitting two form with a submit button with Ajax

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/

Categories