I have my form and my ajax laid out but I am not sure how to submit the form using the ajax. I've tried $('#testform').submit() but it didn't call my ajax when I wrapped it with the submit. I might of been doing it wrong. How do I get my form to submit through the ajax and not submit regularly?
<form id="testform" action="https://example.com/api/payments/" method="post">
Name<input type="text" name="name" id="name">
Card Number <input type="text" name="card_number" id="card_number" maxlength="16">
Exp Month <input type="text" name="exp_month" id="exp_month">
Exp Year <input type="text" name="exp_year" id="exp_year">
CVC <input type="text" name="cvc" id="cvc" maxlength="3">
Amount <input type="text" name="amount" id="amount">
<input type="submit" id="submit">
frm = $('#testform');
frm.submit(function(ev)
{
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
dataType: "html",
//Set the HTTP headers for authentication
beforeSend: function (xhr) {
xhr.setRequestHeader('api_key', 'tiyndhinzrkzti5ody0');
xhr.setRequestHeader('email', 'example#example.com');
},
//Serialize the data sent from the form inputs
data: frm.serialize(),
success: function(data) {
$('#return').append(data);
}
});
ev.preventDefault();
});
Instead of frm.submit(function(ev) try the following code
$("#testform").on('submit', function(ev) {
ev.preventDefault();
...
});
After clicking on the submit button you should see the ajax being posted in the console. The "magic" is to attach a handler to the submit event instead of invoking the event itself. Additionally, you had a typo in your previous code ($('testform') instead of $("#testform"))
Related
I have a headless WordPress site. I'm working on the event handler to submit the contact form. I'm using Contact Form 7. I've tried using vanilla JS, I'm using jQuery here because it seems like a better option, and I'm losing my mind.
Essentially, the form submits but the fields do not clear. I've tried form.reset() in JS, $('#formid')[0].reset() in jQuery, and the code below. I don't know why this isn't working and the result is really suboptimal. Any ideas?
I will fully admit that I am more comfortable working in javascript than jQuery so I might be missing something obvious.
If I don't have the iframe set as the form target, the page redirects to a white page with JSON data. Am I missing something about event.preventDefault()? It's not working the way it should, and has in my experience.
$(document).ready(function() {
$('#formElem').on('submit', function(event) {
event.preventDefault();
let request = $.ajax({
url: "https://api.chloemedranophotography.com/wp-json/contact-form-7/v1/contact-forms/54/feedback",
type: "post",
data: new FormData(this)
}).done(resetForm());
})
function resetForm($form) {
$form.find('input:text, input:tel, input:file, select, textarea').val('');
$('datePicker').val('').attr('type', 'text').attr('type', 'date');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="https://api.chloemedranophotography.com/wp-json/contact-form-7/v1/contact-forms/54/feedback" id="formElem" name="contactForm" method="post" class="contact__form" target="formtarget">
<h3 class="contact__form--heading">Contact</h3>
<p class="contact__form--paragraph">Currently operating out of Minot, North Dakota. Soon to be in South Korea!</p>
<input id="your-name" class="contact__form--input" type="text" name="your-name" placeholder="Name">
<input id="your-email" class="contact__form--input" type="text" name="your-email" placeholder="Email">
<input id="your-tel" class="contact__form--input" type="tel" name="your-tel" placeholder="Phone">
<input id="preferred-date" class="contact__form--input" placeholder="Select session date" type="date" name="preferred-date">
<textarea id="your-info" class="contact__form--input" placeholder="Tell me about yourself!" name="your-info"></textarea>
<textarea id="services" class="contact__form--input" placeholder="What services are you interested in booking?"></textarea>
<textarea id="how-heard" class="contact__form--input" placeholder="How did you hear about my business?" name="how-heard"></textarea>
<input id="btnSubmit" class="contact__form--input btn-contact" type="submit" name="submit">
<div id="messageArea"></div>
<iframe class="formtarget" name="formtarget"></iframe>
</form>
There's several separate issues:
.done(resetForm()) is incorrect as it immediately calls resetForm() and sets the returned value from that call as the event handler.
You need to send the $form argument in the resetForm() method call, so provide a full function block to the done() handler, including that argument
When sending a FormData object in a jQuery AJAX call you need to set processData and contentType to false so the data is encoded correctly.
jQuery does not have :tel and :file pseudo selectors. Instead you can use :input to select all input, textarea and select elements to reset their values.
Changing the type of the date control to text and then back to date is not necessary, even without the above point.
$(document).ready(function() {
const $form = $('#formElem').on('submit', function(e) {
e.preventDefault();
let data = new FormData(this);
let request = $.ajax({
url: "https://api.chloemedranophotography.com/wp-json/contact-form-7/v1/contact-forms/54/feedback",
type: "post",
data: data,
contentType: false,
processData: false
}).done(function() {
resetForm($form)
});
})
function resetForm($form) {
$form.find(':input').val('');
// alternatively to reset the form to original state, not wipe all fields use this
// $form.get(0).reset();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="https://api.chloemedranophotography.com/wp-json/contact-form-7/v1/contact-forms/54/feedback" id="formElem" name="contactForm" method="post" class="contact__form" target="formtarget">
<h3 class="contact__form--heading">Contact</h3>
<p class="contact__form--paragraph">Currently operating out of Minot, North Dakota. Soon to be in South Korea!</p>
<input id="your-name" class="contact__form--input" type="text" name="your-name" placeholder="Name">
<input id="your-email" class="contact__form--input" type="text" name="your-email" placeholder="Email">
<input id="your-tel" class="contact__form--input" type="tel" name="your-tel" placeholder="Phone">
<input id="preferred-date" class="contact__form--input" placeholder="Select session date" type="date" name="preferred-date">
<textarea id="your-info" class="contact__form--input" placeholder="Tell me about yourself!" name="your-info"></textarea>
<textarea id="services" class="contact__form--input" placeholder="What services are you interested in booking?"></textarea>
<textarea id="how-heard" class="contact__form--input" placeholder="How did you hear about my business?" name="how-heard"></textarea>
<input id="btnSubmit" class="contact__form--input btn-contact" type="submit" name="submit">
<div id="messageArea"></div>
<iframe class="formtarget" name="formtarget"></iframe>
</form>
In your code you are calling resetForm and assigning what it returns to the done event handler. It is not calling that function when done is called.
You also are not passing the form reference to the function. So you will have an error message in your console.
$(document).ready(function() {
$('#formElem').on('submit', function(event) {
var form = this;
event.preventDefault();
let request = $.ajax({
url: "https://api.chloemedranophotography.com/wp-json/contact-form-7/v1/contact-forms/54/feedback",
type: "post",
data: new FormData(form)
}).done(function () { resetForm(form); });
})
function resetForm($form) {
$form.find('input:text, input:tel, input:file, select, textarea').val('');
$('datePicker').val('').attr('type', 'text').attr('type', 'date');
}
});
So I'm comparing the value of the input field entered by the user to the value of the mysql DB (using an Ajax request to the checkAnswer.php file). The request itself works fine, it displays the correct "OK" or "WRONG" message, but then it does not submit the form if "OK". Should I put the .submit() somewhere else?
HTML code:
<form id="answerInput" action="index" method="post">
<div id="answer-warning"></div>
<div><input id="answer-input" name="answer" type="text"></div>
<input type="hidden" id="id" name="id" value="<?=$id?>">
<div><button type="submit" id="validate">Valider</button></div>
</form>
</div>
JS code
$("#validate").click(function(e){
e.preventDefault();
$.post(
'includes/checkAnswer.php',
{
answer : $('#answer-input').val(),
id : $('#id').val()
},
function(data){
if(data === '1'){
$("#answer-warning").html("OK");
$("#answerInput").submit();
}
else{
$("#answer-warning").html("WRONG");
}
},
'text'
);
});
I think it is because you set your button type as submit. Why?
When you do $("#validate").click(function(e){, you implicitly replace the default submit behavior of the form.
As you want to interfere in the middle of the process for extra stuff, I suggest you change the button type to button or simply remove the type attribute.
Then the $("#validate").click(function(e){ will alter behavior of click, not the submit of form.
<form id="answerInput" action="index" method="post">
<div id="answer-warning"></div>
<input id="answer-input" name="answer" type="text">
<input type="hidden" id="id" name="id" value="<?=$id?>">
<button onlcick="validate()">Valider</button>
</form>
/******** JS ************/
function validate(){
var post = {};
post['answer'] = $('#answer-input').val();
post['id'] = $('#id').val();
$.ajax({
url: 'includes/checkAnswer.php',
type: 'POST',
data: {data: post},
success:function (data) {
console.log('succsess');
},
error:function (jQXHR, textStatus, errorThrown) {
console.log('failure');
}
});
}
I'm sure my code is broken, can anyone tell where? I cannot use the same form.
I have tried several ways to send 2 POST forms to an action page. But when click the button, the page is reloaded with the updated address bar (click the yname button on the submission form and the address goes to example.com/?yname and not the do.php page)
Please consider the example:
$("#sub").click(function(){
$("form").each(function(){
var fd = new FormData($(this)[0]);
$.ajax({
type: "POST",
url: "do.php",
data: fd,
processData: false,
contentType: false,
success: function(data,status) {
//this will execute when form is submited without errors
},
error: function(data, status) {
//this will execute when get any error
},
});
});
});
<form id="form1">
<input type="tel" placeholder="Your Email" id="email" name="yemail" class="c">
<button id="sub"></button>
</form>
<form id="form2">
<input type="tel" placeholder="Your Name" id="name" name="yname" class="b">
<button id="sub"></button>
</form>
Result of tis code:
When click in a form the url address updates with ?yname
Why aren't triggering an action for a do.php page?
#id can not be repeated. Use a class instead.
And the line $(this).parent('form') gets the form of each .sub clicked.
The buttons should be type="button" 'couse by default it will be type="submit"
TYPEThe default behavior of the button. Possible values are: submit:
The button submits the form data to the server. This is the default if
the attribute is not specified for buttons associated with a ,
or if the attribute is an empty or invalid value.
reset: The button
resets all the controls to their initial values, like . (This behavior tends to annoy users.) button: The
button has no default behavior, and does nothing when pressed by
default. It can have client-side scripts listen to the element's
events, which are triggered when the events occur.
Documentation Button
EDITED: for sending all data in one form just delete the form2
$(".sub").click(function(){
//This line is searching the correct form from itself.
var fd = new FormData($(this).parent('form')[0]);
$.ajax({
type: "POST",
url: "do.php",
data: fd,
processData: false,
contentType: false,
success: function(data,status) {
//this will execute when form is submited without errors
},
error: function(data, status) {
//this will execute when get any error
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form1">
<input type="tel" placeholder="Your Email" id="email" name="yemail" class="c">
<button type="button" class="sub"></button>
<input type="tel" placeholder="Your Name" id="name" name="yname" class="b">
<button type="button" class="sub"></button>
</form>
I make it simple:
I work with google form as my database for now.
After I added reset ability to the submit button, the JS file it sends me again to the response page of google form.
Can you help ? Thanks
<form id="form" action="https://docs.google.com/forms/u/2/d/e/1FAIpQLSeBJHw1Q6YlwO_0s2OgMhuyQEj4PLvToM1N1G5BEYQRiZlCLQ/formResponse">
<label for="">It's FREE</label>
<input type="text" placeholder="Full Name" class="inputs" id="input1" name="entry.1045366435">
<input type="email" placeholder="Email" class="inputs" id="input2" name="entry.1398681060">
<textarea cols="30" rows="10" placeholder="Message" id="input3" name="entry.403219718"></textarea>
<input type="submit" id="submit" value="Send">
</form>
$('#form').submit(function(e) {
alert("Thanks for signing up. We will contact you as soon as we can.");
e.preventDefault();
$.ajax({
url: "https://docs.google.com/forms/u/2/d/e/1FAIpQLSeBJHw1Q6YlwO_0s2OgMhuyQEj4PLvToM1N1G5BEYQRiZlCLQ/formResponse",
data: $(this).serialize(),
type: "POST",
success: function(data) {
$('#form')[0].reset()
},
dataType: "xml",
success: function(data) {
console.log('Submission successful');
},
error: function(xhr, status, error) {
console.log('Submission failed: ' + error);
}
});
});
//Alert + Disable google form response page
First you should not have two different submit handlers, just use one. Second reset is on the form, not the inputs.
success: function(data) {
$('#form')[0].reset()
console.log('Submission successful');
},
reset() is a method against form.
Thus you will need to select the form instead.
document.getElementById("form").reset();
Javascript doesn't send any post data to php file
$(document).ready(function(){
function showComment(){
$.ajax({
type:"post",
url:"process.php",
data:"action=showcomment",
success:function(data){
$("#comment").html(data);
}
});
}
showComment();
$("#button").click(function(){
var name = $("#name").val();
var message = $("#message").val();
var dataString = "name="+name+"&message="+message+"&action=addcomment";
$.ajax({
type:"post",
url:"process.php",
data:dataString,
success:function(data){
showComment();
}
});
});
});
form:
<form action="" method="POST" enctype="multipart/form-data">
name : <input type="text" name="name" id="name"/>
</br>
message : <input type="text" name="message" id="message" />
</br>
<input type="submit" value="Post" name="submit" id="button">
<div id="info" />
<ul id="comment"></ul>
</form>
php
$action=$_POST["action"];
if($action=="addcomment"){
echo "Add comment WORKS!";
}
if($action=="showcomment"){
echo "default";
}
Tried to add such lines as if post addcomment than show some words, just for a test since sql request didn't but php doesn't show any response at all, like there was no post action at all.
ps. I'm really new ajax so if possible show me a solution to solve it.
You're using a submit button so it will be making the form submit and reload which will bypass your ajax, you can change your jQuery to listen for the form submit event instead like this:
$("form").on('submit', function(e){
// Stop form from submitting
e.preventDefault();
var name = $("#name").val();
var message = $("#message").val();
var dataString = "name="+name+"&message="+message+"&action=addcomment";
$.ajax({
type:"post",
url:"process.php",
data:dataString,
success:function(data){
showComment();
}
});
});
Or simply change the button from type="submit" to type="button" or replace it with a element.
You are using submit button as Dontfeedthecode mentioned. Your form does not have any action so it is self posting. I have added action and id to the html form and a hidden field to pass the action. Now javascript serialize the form and send it to the process.php.
$(function () {
$("#my-form").on("submit", function (e) {
$("#action").val("addcomment");
$.ajax(
{
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (data) {
showComment();
}
});
return false;
});
});
<form action="process.php" method="POST" id="my-form" enctype="multipart/form-data">
<input type="hidden" id="action" name="action" value="" />
name : <input type="text" name="name" id="name" />
</br>
message : <input type="text" name="message" id="message" />
</br>
<input type="submit" value="Post" name="submit" id="button">
<div id="info" />
<ul id="comment"></ul>
</form>