I'm trying to write JavaScript (jQuery in this case) to handle the form submission of an already existing form. I do not have a ton of control over the form itself. It's built in a third-party landing page software with limited options.
What I'm trying to accomplish: Submit the form twice. The first time with all of the original values. The second time with a few of the values remapped.
What I've come up with so far is as follows:
jQuery(document).ready(function() {
jQuery("form").submit(function(e) { // fires when the original form is submitted
e.preventDefault(); // stops the form submitting / refreshing
// save the values for our first AJAX call
var formData = {
your_first_name: jQuery("#your_first_name").val(),
your_last_name: jQuery("#your_last_name").val(),
your_company_name: jQuery("#your_company_name").val(),
your_work_email: jQuery("#your_work_email").val(),
your_referrals_first_name: jQuery("#your_referrals_first_name").val(),
your_referrals_last_name: jQuery("#your_referrals_last_name").val(),
your_referrals_company_name: jQuery("#your_referrals_company_name").val(),
your_referrals_email_address: jQuery("#your_referrals_email_address").val(),
your_referrals_phone_Number: jQuery("#your_referrals_phone_number").val(),
how_did_you_hear_about_electrics_referral_program: jQuery("#how_did_you_hear_about_electrics_referral_program").val(),
}
// remaps values for second AJAX call
var repostData = {
your_first_name: jQuery("#your_referrals_first_name").val(),
your_last_name: jQuery("#your_referrals_last_name").val(),
your_company_name: jQuery("#your_referrals_company_name").val(),
your_work_email: jQuery("#your_referrals_email_address").val(),
your_referrals_first_name: '',
your_referrals_last_name: '',
your_referrals_company_name: '',
your_referrals_email_address: '',
your_referrals_phone_Number: '',
how_did_you_hear_about_electrics_referral_program: jQuery("#how_did_you_hear_about_electrics_referral_program").val(),
}
// submits the form with all of the original data
jQuery.ajax ({
type: 'POST',
data: formData,
dataType: 'json',
success: function (data) {
console.log("Form 1 submitted successfully!");
// submits the form again with new data, only if the first post was successful
jQuery.ajax ({
type: 'POST',
data: repostData,
dataType: 'json',
success: function (data) {
console.log("Form 2 submitted successfully!");
},
error: function (data) {
console.log("An error has occured on form 2");
}
});
},
error: function (data) {
console.log("An error has occured on form 1");
}
});
});
});
And I have a JSFiddle built here with an html form built out for testing: https://jsfiddle.net/wca18ekq/
I have tried various different methods. Some with and without AJAX. I ultimately think AJAX is the right approach here since I would like to post data more than once without refreshing.
Can anyone lend a hand here?
This is the workaround approach, this would require the user to allow popups, and they would need to close the tabs after, because it would set the form target to _blank, to make it submit in a tab, then submit one time, remove the fields you dont want, then submit another time
https://jsfiddle.net/04jnfytg/
//won't work in the fiddle, because it doesn't submit correctly to a tab
Related
I have a web form that is part of a CMS, therefore I am not able to alter the input field of the submit button. The form is already being validated by JS, so I need to add a line to the existing code below that will clear the fields.
Currently, the page redirects to a Thank you page on submit. I want it to continue doing that. But, currently, if the user hits the back button on their browser, the data is still there. I need it to submit the data, clear the fields, then redirect to the thank you page.
$('form').submit(function(event)
{
if (validateForm())
return true;
event.preventDefault();
});
Have you tried adding document.querySelector('form').reset() above the return statement? In jquery that might just be $(this).reset(), I'm not sure.
if (data.status) {
$(this).find('input').val('');
// code to redirect to success page here
}
If form is successfully sent, then set the value of all inputs in the sent form to a string with the length of 0.
$('form').submit(function(event) {
event.preventDefault();
if (!validateForm()) {
return false;
} else {
formSubmit($(this));
}
}
);
function formSubmit(form) {
var url = form.attr('action');
var method = form.attr('method');
var data = form.serialize();
$.ajax({
method: method
, url: url
, data: data
})
.done(function (data) {
try {
$(this).find('input').val('');
// code to redirect to success page here
} catch (e) {
console.log(e);
}
});
}
FE validation is bad practice in my honest opinion, just good for lowering the amount of HTTP requests to the server. The hard form data validation should happen on the BE.
Cannot resubmit the form without clicking twice when an error is returned from my api (like 'unknown user'). I want the user to be able to resubmit data but the form won't submit unless clicked twice. The firs click removes the error alert and the second click resubmits the form. FYI: Using jquery.validate.js
var validator = $('#form1').validate({
submitHandler: function (form) {
$('#login').attr('disabled', 'disabled');
$.ajax({
xhrFields: {withCredentials: true},
type: "POST",
dataType: "json",
data: {
login: 1,
UserName: $('#UserName').val(),
Password: $('#Password').val()
},
url: apiBase + 'login.php',
success: function (resp) {
window.location.replace("index.php");
},
error: function (resp) {
err = JSON.parse(resp.responseText);
$('#err').toggleClass('hidden').text(err.alert);
$('#login').removeAttr('disabled');
}
});
}
});
Firstly, to disable the submit button of the form, you can use the
onsubmit: false option of the validator ( $("#form1").validate({
onsubmit: false
}); )
. Secondly, why are you passing a new validator to the "validator" variable?
Thirdly, the submitHandler function triggers after the form has been validated and also replaces the default submit button, which makes me think that $('#login').attr('disabled', 'disabled'); is a bit of an overkill.
Also, in respect to the fact that you are clicking the button twice to get it to work, it might be a case of "too much recursion". Please refer to: https://jqueryvalidation.org/documentation/ too much recursion.
Lastly, I think that you should not be writing your own ajax call, instead use the $(form).ajaxSubmit(); function with a callback option object for handling responses. Please refer to: http://malsup.com/jquery/form/#options-object for more info.
This question already has answers here:
Submit form without page reloading
(19 answers)
Closed 7 years ago.
I want to submit a form information to another php script without leaving the page and show the output in that same page.
Here's my ajax function to load php output in html without leaving the page. It doesn't do that if my form has a submit button. It only works with a normal clickable button.
$('#btnLoad').click(function(){
$.ajax({
type: 'POST',
url: 'page1.php',
success: function(data){
if(data != null) $('#content').text(data);
}
});
});
The problem is that I need to send POST variables to my PHP script but when I do, it goes to my PHP script page. I just want the script to receive the POST variables, run the script and then show the output in my HTML page.
Here's the script that doesn't go to PHP script page. I don't know if the PHP script runs with this function.
$(function() {
$('form#myForm').on('submit', function(e) {
$.post('page1.php', $(this).serialize(), function (data) {
}).error(function() {
});
e.preventDefault();
});
});
How can I combine these two scripts into one, to submit my variables via POST, run the script and show the output in my HTML page?
Combining both Ajax
$("#btnLoad").click(function (e) {
e.preventDefault()
$.ajax({
type: "POST",
url: "page1.php",
data: $('#myForm').serialize(),
success: function (msg) {
$("#thanks").html(msg);
},
error: function (msg) {
$("#error").html(msg);
}
});
});
HTML to show success message
<div id="thanks"></div>
HTML to show error message
<div id="error"></div>
PHP Server Side
<?php
if (isset($_POST['submit'])) { //assuming you have input with name="submit"
//Do what ever you like to do next
//If everything good
echo "<strong>Success!</strong> This Is Success Thanks Message. If everything go exactly as Planned.";
} else {
echo "<strong>Error!</strong> This Is Error Message. If anything goes south.</div>";
}
?>
Edited: OP asked to show messages in jQuery modal dialog
In Ajax after success call, try like this
success: function(msg) {
$("#thanks").html(msg);
$("#modalId").dialog({
autoOpen:true,
width:500,
title:"Your Error Message",
},
And same for error function
Note: I haven't test this so not sure it will work out of the box or need any debugging.
Why do you not replace the submit buttons with normal buttons then?
What you could do in jQuery is:
$(formSelector).on('submit',function (e) {
e.preventDefault()
//Place your ajax here.
})
you can do something like
$('#btnLoad').click(function(){
$.ajax(url,
{
data: { variable1: $("#variable1").val(), variable2: $("#variable2").val() },
type: "POST",
success: function(data) {
if(data != null) $('#content').text(data);
}
});
});
And normally I don't use a form if I need to send data via ajax, I use just JS.
I am using Contact Form 7 with Wordpress 3.5.
Currently, when a user submits the message, they are redirected to a success page by using the following in the "Additional Settings" field:
on_sent_ok: 'location.replace("http://www.example.org/success-page");'
I want to be able to customise the output of the success-page by using the input from a field, for example:
on_sent_ok: 'location.replace("http://www.example.org/success-page?name=yourname");'
I hoped that by dropping the usual Contact Form 7 shortcodes into the Additional settings, it may have sent the field value with it, but that's not the case.
Can anyone suggest how I can get the field values from contact form 7 into the url, or alternatively send as a $_POST parameter? It may require some javascript to do this, I guess.
This is possible but you need the save the posted data from the contact form to the session and show it there.
Add this to your functions.php
add_action('wpcf7_mail_sent', 'save_cf7_data');
function save_cf7_data($cf)
{
if(session_id() == '') {
session_start();
}
$current_submission = WPCF7_Submission::get_instance();
$_SESSION['cf7_submission'] = $current_submission->get_posted_data();
}
And your success page you just need to print the session var, like:
echo $_SESSION['cf7_submission']['name'];
That's all.
Another option is to use jQuery or Javascript and catch the form on submit.
After the form is caught you can serialize the params and pass them to a custom page to catch them and do things with them.
Example for jQuery:
jQuery(document).ready(function($) {
$('.wpcf7-form').each(function () {
$(this).on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'POST', // Can also choose GET instead
url: 'forms/getParams',
data: $(this).serialize(),
dataType: "json",
success: function (data) {
$(this)[0].reset(); // Optional in case you want to clear the form on success
},
error: function (data, errorThrown) {
console.log(errorThrown);
}
});
});
});
});
the 'additional settings' code is javascript and thus is running in the context of the browser. this means you can easily access the form data using normal javascript code
e.g. on_sent_ok: 'location.replace("http://www.example.org/success-page?name=" + jQuery("input[name=name]").val());'
i think you should use $_REQUEST['name']; for fetching your post variable on success page.
The server is written in web2py, and hosted on google app engine. I can visit my index.html by entering domain.com/index and I can send form by entering domain.com/register where "register" is a function defined by default.py
However, in html, where I would like to send form to the server and get a response, I use ajax which has cross domain issues. So I use "register" as URL, and it does not work. Help?
$("#signup").click(function() {
$.ajax({
type: "POST",
url: "register",
data: $("#formsignup").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data);
}
});
return false; // avoid to execute the actual submit of the form.
});
By typing domain.com/register, I can totally trigger the function. What is the problem here? And the form is sent to domain.com... In browser it appears as htt[://domain.com/?email=ada#ad.com&password=adsa
Its very possible register is looking for GET instead of POST
try changing the type in ajax
$("#signup").click(function() {
$.ajax({
type: "GET",
url: "register",
data: $("#formsignup").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data);
}
});
return false; // avoid to execute the actual submit of the form.
});