Contact Form 7 : Not routing to new page - javascript

I am using Contact Form 7 and JS to load a new page upon successful form submission. However, upon the submission of the contact form, I am routed to the following url: https://example.com/#wpcf7-f95-p2-o1
My inline JS is as follows:
document.addEventListener( 'wpcf7mailsent', function( event ) {
alert("The form has been sent");
location = 'http://www.example.com/thank-you/';
}, false );
However, this redirect (to url/#wpcf7-f95-p2-o1) occurs on all browsers and devices, and the alert message never populates. There are no console errors or warnings pertaining to this script - which leads me to believe that this script is never being triggered.
Is there something that I could have done in order to prevent this function from opperating?

Try adding this code to functions.php:
add_filter('wpcf7_form_action_url', 'remove_unit_tag');
function remove_unit_tag($url){
$remove_unit_tag = explode('#',$url);
$new_url = $remove_unit_tag[0];
return $new_url;
}
this will remove the tag, also for redirecting, you can use something like this which gives more options

Related

page reloads on chrome extension message send?

So I'm running a data collection project by injecting a html form into a third party website, via a chrome extension, which instructs users to describe the data they see and submit it to my server.
For some bizarre reason, however, whenever the user clicks the "submit" button to send the form contents to the background page (and from thence to the server), the underlying page reloads, and, not only that, but it reloads with the contents of the form I injected showing up in the url after reload. Which is kind of bizarre behavior.
I don't know if this is something in my code, or even if it's something in the underlying web page's code (maybe it redefines chrome.runtime.sendMessage or something as some kind of anti-extension technique?!!?). I'd really like to stop this behavior if possible... does anyone have any ideas?
The relevant parts of my code, stripped down a little:
var cururl = window.location.href
var codestring= "[A HTML FORM TO INJECT]"
var raformvalues = {};
function codeValues() {
$.each($('#mainCoding').serializeArray(), function(i, field) {
raformvalues[field.name] = field.value;
});
}
function sendValues() {
let pageinfo = {"page": document.documentElement.outerHTML,
"url": cururl,
"title": document.title,
"timestamp": String(Date.now())};
let tosend = $.extend({"type": "doctype"}, pageinfo, raformvalues);
chrome.runtime.sendMessage(tosend);
chrome.storage.local.set({'lasturl': pageinfo.url});
$("#pgcodediv").empty();
location.href = cururl; // note: I added this line to try to stop the reloading and url/changing behavior. behavior is the same with and without it.
}
function appendCodingInfo() {
$("#headerID").append(codestring);
$( ":checkbox, :radio" ).click( codeValues );
$( ":text" ).change( codeValues );
$( "#codingsubmit" ).click(sendValues);
}
appendCodingInfo()
when the user hits the submit button (#codingsubmit, of course), the message gets passed and the background page handles it correctly, but the page refreshes unbidden, and the contents of raformvalues show up in the URL of the refreshed page (i.e., when I call window.location.href from the console the contents of that object show up as parameters to a get request, i.e., http://url?prop=value&prop2=value2 -- no clue why.
If you click a button with type="submit" in a form, by default browser will reload the page after the form is submitted.
To prevent the page reloaded, either replace type="submit" with type="button" or call e.preventDefault() inside sendValues handler.
Appendix:
According to MDN, the default value for button is submit.
type
The type 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, or if the attribute is dynamically changed to an empty or invalid value.
reset: The button resets all the controls to their initial values.
button: The button has no default behavior. It can have client-side scripts associated with the element's events, which are triggered when the events occur.
menu: The button opens a popup menu defined via its designated element.

jQuery Mobile Debug Page Redirection

I'm progmatically changing the page in my jQuery mobile application, on a click of button. This is the code I'm using:
$("#paymentConfrim").click(function() {
$( ".paymentDetailForm" ).submit(function( event ) {
if(!validatePaymentDetailForm()){ // if false comes from validation
return false;
}
else{
// I'm using changePage instead of jQuery pagecontainer widget as I'm using older version of jQuery mobile
$.mobile.changePage( "#submissionConfirmation", {} );
return true;
}
});
The page is getting changed successfully, but after a second or fraction of a second, the application is returned to homepage. As the application is big, with lot of legacy code, I'm unable to determine what code is causing that page change. As it happens after few milliseconds, I suspect there is some setTimeOut function that is causing that.
Strangely though the page is changed to homepage, the URL remains the same as of #submissionConfirmation page i.e. localhost/mypage.html#submissionConfirmation
How can I debug and know exactly what JavaScript code is causing that redirection?
The reload is caused by the form being submitted. You need to prevent the default form submission behaviour by calling event.preventDefault() as the first thing in your handler.
$(".paymentDetailForm").submit(function(event) {
event.preventDefault();
});

Contact Form 7 AJAX Callback

Been searching around on this for a while and can't come up with any documentation to outline what i want to achieve.
I'm using wordpress and the Contact Form 7 plugin, all is working perfectly, what i want to achieve is to run some particular javascript upon form submit, i know we can use "on_sent_ok:" in the additional settings, but this only performs if the form is actually submitted.
What i'd like to do is to do some other javascript when the form doesn't submit ok, which throws the user back to the section which didn't validate.
I can use the following code to run after 1.7s of the form submit being clicked, however it's a bit sloppy as if the user was running with a slow connection, there's potential this could run before the form is submitted properly.
$('.wpcf7-submit').click(function() {
setTimeout(function() {
if ($('.fs1 input,.fs1 textarea').hasClass('wpcf7-not-valid')) {
$('.pop-up-form').removeClass('pustep2').removeClass('pu-closing');
$('.form-step').hide();
$('.fs1').show();
}
if ($('.fs2 *').hasClass('wpcf7-not-valid')) {
alert('error on page 2 - take user back to the area with issues')
}
}, 1700);
});
Is there any particular function or hook i can use to run JS when the form AJAX has completed?
Thanks!
In version 3.3 new jQuery custom event triggers were introduced:
New: Introduce 5 new jQuery custom event triggers
wpcf7:invalid
wpcf7:spam
wpcf7:mailsent
wpcf7:mailfailed
wpcf7:submit
You can use wpcf7:invalid like the example below:
$(".wpcf7").on('wpcf7:invalid', function(event){
// Your code here
});
Given the variety of responses on this topic the plugin developer seems to change their mind about how this should work every 5 minutes. Currently (Q1 2017) this is the working method:
document.addEventListener( 'wpcf7mailsent', function( event ) {
alert( "Fire!" );
}, false );
And the valid events are:
wpcf7invalid — Fires when an Ajax form submission has completed
successfully, but mail hasn’t been sent because there are fields with
invalid input.
wpcf7spam — Fires when an Ajax form submission has
completed successfully, but mail hasn’t been sent because a possible
spam activity has been detected.
wpcf7mailsent — Fires when an Ajax
form submission has completed successfully, and mail has been sent.
wpcf7mailfailed — Fires when an Ajax form submission has completed
successfully, but it has failed in sending mail.
wpcf7submit — Fires
when an Ajax form submission has completed successfully, regardless
of other incidents.
Sauce: https://contactform7.com/dom-events/
Sometimes it may not work, as Martin Klasson pointed out, only 'submit' event works, most probable because it's triggered by a form and bubbles up to the selected object. Also as I can understand, now events have other names, like "invalid.wpcf7", "mailsent.wpcf7", etc. In short, this should work:
jQuery('.wpcf7').on('invalid.wpcf7', function(e) {
// your code here
});
More detailed explanation here: How to add additional settings on error in Contact form 7?
This code works since 5.8.x version:
$('.wpcf7').on('wpcf7invalid wpcf7spam wpcf7mailsent wpcf7mailfailed', function () {
// your code here
});
I had quite a go at this, and I found that when only the Submit event works, it means that there is a js problem / conflict in your theme.
If it's a custom theme you built, make sure jQuery and jQuery migrate are both loaded, in this order, and that the Contact form 7 js is also loaded in the footer.
Make sure you have wp_head, and wp_footer in your php templates.
For DOM events to work, your form must be in Ajax mode. If the page reloads upon submission, forget about DOM events. If you have the form ID showing up in the URL, same thing. My form was initially not in Ajax mode because the Contact Form JS was not loaded, and jQuery Migrate either.
The form must behave exactly like shown on this page for the DOM events to be fired properly. Once you have that, it should be working.
I've tested this with jQuery 3.3.1 and Migrate 3.0.1 and the following event listener worked:
document.addEventListener( 'wpcf7mailsent', function( event ) {
console.log('mail sent OK');
// Stuff
}, false );
To check if your theme is the culprit, test your form using Wordpress' default theme, if it works, you know the issue is on your end and not so much in the dev's doc!
I tried to implement the dom event behavior in wordpress contact form 7 plugin as described here, but after trying numerous methods which are given as fixes in different forums I implemented a method of my own.
I m describing the method here below. The method involves some steps which are listed below:
Creating the contact form
Scripting for the contact form to capture event triggers and form data
Loading the script
1. Creating the contact form
<label> Your name
[text* cform7-name id:cform7-name autocomplete:name] </label>
<label> Your Number
[tel* cform7-contact id:cform7-contact] </label>
<label> Course You are interested (Press Ctrl + Select to select Mutiple)
[select* cform7-courses id:cform7-courses multiple "JAVA" "Python" "C#" "Others"] </label>
<label> Your message (optional)
[textarea cform7-submit id:cform7-message] </label>
[submit id:cform7Submit "Submit"]
Above is a sample script with ids so that we can easily retreive those elements from DOM tree using JS. [You can modify the field ids as your need]
2. Scripting for the contact form to capture event triggers and form data
document.addEventListener('DOMContentLoaded', function() {
var frmButton = document.getElementById('cform7Submit');
frmButton.addEventListener( 'click', function( event ) {
var data = {
name: document.getElementById('cform7-name').value,
contact: document.getElementById('cform7-contact').value,
courses: document.getElementById('cform7-courses').value,
comment: document.getElementById('cform7-message').value
};
event.preventDefault();
console.log('Event Data ', event);
console.log('Data ', data);
}, false );
}, false);
Save the above script in wordpress deployment directoty. In my case I placed the script in the root deployment directory itself(<worpress-root-directory>) and saved the file as cform7.js.
Ex: /var/www/wordpress-site/cform7.js
After finishing this we need to load the script.
3. Loading the script
function cform7_script() {
wp_enqueue_script( 'cform7-js', '/cform7.js');
}
add_action('wp_enqueue_scripts', 'cform7_script');
Place the above code in the <worpress-root-directory>/wp-includes/functions.php file
That's done! On clicking the form submit button(cform7-submit) you must see the data logged in the console.

Contact Form 7 - Redirect page to specific URL based on drop-down selection

I have read several forums on this topic, but have not been able to get any of the fixes to work for me. That is due partially to the fact that I am not familiar with JS and may not be understanding some of the values suggested.
My form needs to open a PDF on submit, but which PDF would be determined by one of the dropdown selections.
The form is here: http://www.hinesbending.com/production/index.php/request-info-form/
The dropdown is Download Document.
Upon clicking Send, I would like the page to open the PDF in a new window if possible, and still show the message under the form that "Your message was sent successfully. Thanks."
If that is not possible, simply redirecting to the appropriate PDF would suffice.
Can anyone tell me how to do this, please?
These worked for me:
on_sent_ok: "var Iso = $("select[name=your-selection-name]").val() ;
if(Iso == 'your-value-1' ){
location = 'your-website1-url';
}
if(Iso == 'your-value-2' ){
location = 'your-website2-url';
}
if(Iso == 'your-value-3' ){
location = 'your-website3-url';
}"
Just replace your-selection-name, your-values and your-websites
The question is getting old and Contact Form 7 will abolish the on_sent_ok hook:
Note: The method using on_sent_ok hook is no longer recommended. This function is scheduled to be abolished by the end of 2017. (https://contactform7.com/redirecting-to-another-url-after-submissions/)
Thats why we need a different approach with DOM events (https://contactform7.com/dom-events/)
Contact Form 7 gives an example for the redirect:
document.addEventListener( 'wpcf7mailsent', function( event ) {
location = 'https://www.example.com';
}, false );
I would also be interested in how we can combine the dom redirect with a dropdown option

Greasemonkey doesn't execute again after form prints result

I'm using greasemonkey to manipulate a form on an existing web page. (autofill)
The action attribute of the form is itself, once submitted it prints a success message above the submit button.
What I'm trying to do is, once the form is submitted - I want to redirect the browser to another page. But this doesnt work with greasemonkey. Nothing happens.
I wrote a code to detect when the page is submitted, but doesnt work after the form is submitted.
getData("goingback"); //pulls the goingback data from database using ajax
if (goingback == "yes") {
window.location = "index.php";
} else {
//business as usual
// manipulate the form and get it ready for submission
sendPost("goback","yes"); // this function sends data to a php to be handled via ajax
//ajax stores the data in database
//the form is submitted using a timer and .click();
var submission = Math.floor(Math.random() * 10000) + 5000;
setTimeout(function() {
$('button[value="submit"]:first').click();
}, submission);
}
How can I achieve this?
Thanks in advance
The question is not clear; we might need to see the actual page itself. But, it sounds like the page is submitting the form via AJAX, and not a full post.
In that case, your script won't refire. Instead, monitor the page for the success message. Here's one way:
Suppose the success message is like this:
<div id="post_status">
<h2>Some one set us up the (data) bomb!</h2>
</div>
where the <h2> is added after the form posts.
Then this code will redirect after the post happens:
var postChkTimer = setInterval (checkForPostDoneNode, 200);
function checkForPostDoneNode () {
var postDoneNode = $("#post_status h2");
if (postDoneNode.length) {
window.location.assign ("index.php");
}
}
There is no need for that getData("goingback") or
sendPost("goback","yes"). Also that looks like it's setting goback but checking goingback -- which could be a problem. Although it is not the problem causing the behavior as described in the question.

Categories