Mailchimp Multiple Subscription Forms for one list - javascript

I embedded three different customized mailchimp forms in an html page that point to one list (each form has two similar fields and one different hidden field).
Everything works excluding one thing. The responses messages (success or error) are displayed in the same page in the div #mce-response only for the first form. In the other two the responses are loaded and displayed in another blank page. I'd like to have the reponses displayed in the same page for all the three forms.
I'm not a Java Script user but after a bit of research I found that this deals with the external script:
<script type='text/javascript' src='http://s3.amazonaws.com/downloads.mailchimp.com/js/mc-validate.js'></script>
Is there any solution through mailchimp settings or we have to use JavaScript file?
I understood that this script is valid only for the first form.
Any idea how to do this?
Thanks

Apparently using iframes works.
Please refer to this article/video.
Text from the article for explanation:
Instead of pasting the code from the Signup Form Embed Code page into your site, paste it into a text document (using NotePad (PC) or TextEdit (Mac)) and call it “signup-form.html” or something like that. You may want to wrap the form in a div for styling and add some inline styles. So the HTML document will look something like this:
<style type="text/css">
<!--
lots of CSS to make your form look pretty
//-->
</style>
<div id="sign-up">
at least 50 lines of code copied from MailChimp goes here
</div>
Then upload this HTML document (“signup-form.html” or whatever you called it) to somewhere on your server.
Then in order to embed the code on the page (as many times as you want) you call the HTML in with an iframe like this:
<iframe src="http://your-site.com/mailchimp-form.html" frameborder="0" width="654" height="200">
Anchor text saying "click here to sign up" or something like that for people whose browsers can't read iframes
</iframe>

Use Ajax Chimp. This will (1) prevent redirecting your subscribers away from your page and (2) allow multiple forms.
https://github.com/scdoshi/jquery-ajaxchimp

If you wrap each mailchimp form in a ...., then run this script on the page, it will re-assign all IDs of the non-focused form, and re-bind the submit event. A bit hacky, but it works if you're in a bind.
// only execute if confirmed more than 1 mailchimp form on this page
$(document).ready(function() {
if ( $('.mc-form-instance').length > 1 ) {
$('.mc-field-group > .required').on('focus', function() {
var thisField = $(this);
// backup all mc-form ids on this page
$('.mc-form-instance [id]').each(function() {
var currentID = $(this).attr('id');
if ( currentID.indexOf('-bak') == -1 ) {
$(this).attr('id', currentID + '-bak');
}
});
// change the current form ids back to original state
var thisForm = thisField.closest('.mc-form-instance');
thisForm.find('[id]').each(function() {
var currentID = $(this).attr('id');
if ( currentID.indexOf('-bak') != -1 ) {
$(this).attr('id', currentID.replace('-bak', ''));
}
});
});
// re-bind
$.getScript('//s3.amazonaws.com/downloads.mailchimp.com/js/mc-validate.js');
}
});

Related

Use jQuery to submit ajax form after all ajax calls are complete

I am using this WordPress plugin as a store locator on my website. On pages that do not have the interactive map, I have a form that that acts as a map search form.
In other words, I have a form with a location field. The user enters the location in the field and clicks the search button. When they click the search button, the page redirects to the page with the map and the location field is filled with the location entered on the previous page:
/* This is the search form on the page that does not have the interactive map */
$('#searchonly #wpsl-search-wrap form').submit(function(e){
e.preventDefault();
var loc = $('#searchonly #wpsl-search-wrap form #wpsl-search-input').val();
localStorage.setItem("loc",loc);
window.location.href = "http://localhost/inform/find-a-doc/";
});
/* This is the page with the interactive map */
jQuery(document).ready(function( $ ) {
var loc = localStorage.getItem("loc");
$('#wpsl-search-wrap form #wpsl-search-input').val(loc);
});
I now need the the search button on the page with the interactive map to automatically be clicked (or the form submitted) on page load.
There are a couple of roadblocks. The first is that I am using a WordPress plugin so editing the actual plugin files isn't an option. The second (this might not be a roadblock, I am not sure) is that the plugin is already running some ajax calls on page load. I would assume this means that the form submit button shouldn't be programatically clicked until the initial ajax is complete.
Here are the individual solutions I have tried. Each line break represents a different solution I have tried:
/* #wpsl-search-btn is the submit button for the form */
$(document).ajaxSuccess(function() {
$("#wpsl-search-btn").submit();
});
$(document).ajaxComplete(function() {
$("#wpsl-search-btn").submit();
});
$("#wpsl-search-btn").submit();
$("#wpsl-search-btn").trigger('submit');
None of those solutions are working and I am receiving no js errors in Chrome's inspector.
I'm not sure if this will help but here is the plugin's main js file.
Take a look at $.Deferred()
https://api.jquery.com/category/deferred-object/
You can bind promises that are executed after a request is processed.
I was able to answer my own question. This is the code that solved my problem:
var loc = localStorage.getItem("loc");
$('#wpsl-search-wrap form #wpsl-search-input').val(loc);
function clickBtn() {
$("#wpsl-search-btn").trigger('click');
}
$(document).one('ajaxComplete', function() {
clickBtn();
});

Dynamic Follow Up Page with Marketo Forms

We are using a script that allows us to to change the follow up URLS of a form dynamically so we can use the same form across multiple assets but have different follow up pages.
The issue is that script only works when it loads the form itself rather than bringing it in via the visual editor. If we adjust the code as per the instructions on the developer site to make it work with the visual editor, it stops working.
We need to bring the form in via the editor because we have another script that only works on forms that are loaded in that manner. This script opens the follow up page in the parent window rather than the iframe.
Can you provide any suggestions?
Here's the code for the script:
Dynamic follow up URL:
<script type="text/javascript">// <![CDATA[
MktoForms2.whenReady(function(form){
//Add an onSuccess handler
form.onSuccess(function(values, followUpUrl){
//Take the lead to a different page on successful submit, ignoring the form's configured followUpUrl.
location.href = "http://solutions.healthcaresource.com/2346-staff-assessment-thank-you.html";
//return false to prevent the submission handler continuing with its own processing
return false;
});
});// ]]>
Use document.getElementById('iframe_id').src (given an iframe with an id of 'iframe_id'):
location.href = "http://solutions.healthcaresource.com/2346-staff-assessment-thank-you.html";
To this
document.getElementById('iframe_id').src = "http://solutions.healthcaresource.com/2346-staff-assessment-thank-you.html";
You can add Marketo variable to be able to give dynamic followup link.
Add following meta for variable, and use it in script. Code will be like this in your landing page.
<meta class="mktoString" id="ThankyouPage" mktoName="Follow-up Page" default="Add dynamic followup page here" allowHtml="false">
<script>
MktoForms2.whenReady(function (form) {
form.onSuccess(function(values, followUpUrl) {
location.href = ${ThankyouPage};
return false;
});
});
</script>

Dynamically loaded javascript doesn't work second time loaded

I am working on a webpage that uses a JQuery UI dialog (in modal mode) to display a form that is dynamically generated using Django. The basic flow is:
the user clicks a button
jquery (using AJAX) issues a get request that returns the html for the form which is then used to fill the dialog
The html contains a script tag that handles some UI on the form which loads fine and works as expected
the user than fills out the form and clicks "Done" and the form is submitted.
The issue comes in when the user makes an error on the form. The server responds to the post request (that submits the form) with the original form (including the script) modified to show the errors. This second time the script is loaded it gets a "Uncaught ReferenceError: $ is not defined (anonymous function)" The script is exactly the same as before when it worked fine. To be clear throughout this entire process the page is never refreshed.
Here is the gist of the javascript that takes care of the modal:
var add_container = $("#add_container");
add_container.dialog({...})
function show_form(form,response_func) {
add_container.html(form);
add_container.dialog("open");
$("#add_form").submit(function (event) {
return submit_form($(this),response_func);
});
}
function submit_form(form,response_func) {
add_container.append('<p>Adding...</p>');
//this is a trick to upload a file without reloading the page
form.attr('target','upload_target');
$('#upload_target').load(function() {
var response = $('#upload_target').contents().find('body').html();
add_container.dialog("close");
resp_obj = $(response)
if (resp_obj.is('form')) {
//***this is what reloads the form when there is an error
show_form(response,response_func);
} else {
response_func(resp_obj);
}
});
}
$('#add_link').click(add_link);
function add_link() {
$.get('/add_link', function(data) {
function add_response(response) {
//handle successful submission
}
show_form(data,add_response);
});
}
//...more stuff that is not important
This is the gist of the html returned from /add_link
<script type="text/javascript" src="/scripts/add_form.js" ></script>
<form id="add_form" enctype="multipart/form-data" action="/add_link/" method="post">
<!-- Dynamically generated form here !-->
</form>
The add_form.js is a pretty standard javascript file that uses jQuery. Its starts with $(document).ready(function () {...} ) and the first $ is where the ReferenceError occurs
The form needs to be dynamically generated based on what is clicked so I can't just put everything statically on the page. The script is not dynamically generated so it doesn't necessarily need to be dynamically loaded but I wasn't sure how to keep it in its own file, and also only have it run when the form is loaded. I am open to suggestions of alternative ways to accomplish the same effect.
Your form action is pointing to a different relative path to the one containing the jQuery framework script, etc.
<script type="text/javascript" src="/scripts/add_form.js" ></script>
<!-- src="/scripts" -->
<form id="add_form" enctype="multipart/form-data" action="/add_link/" method="post">
<!-- action="/add_link" -->
To make sure it's loading the framework after the form submission, just use something like the developer tools on your browser and check the head tag for the jQuery script src. Is it still there?
Thanks to MelanciaUK I realized that when I submitted my form to the iFrame the response was getting sent first to there where the script would run and error because the iFrame is treated as its own page and doesn't have access to jQuery loaded on the main page.
I decided to solve the problem by eliminating the dynamic loading of the add_form script and simply load it when the page loads just like all my other scripts. I created a custom jQuery event (using .trigger) in order to only have the script run when the add form is opened. This worked exactly the way I wanted it to.
Hope this helps anyone with a similar problem. If you have any questions feel free to ask!

How to realize screens / views with JavaScript / Jquery easily?

I'm sure I'm missing something pretty basic, but I have just started to get myself up to speed on jQuery and Javascript programming. Previously I was doing server side programming with PHP.
I'm now in the middle of creating a prototype for HTML5 webapp, where I would like to have different screens. Now with PHP that was pretty easy, I could just used server side templates like Smarty and be done with it.
However to make my app more webapp like, I would like to dynamically change between screens without having to reload the window.
I have looked into several options that might be anwsers to my question, but I'm not sure whether I'm on the right track.
I have checked for example JsRender, JsViews or even the pure jquery load command.
But what I'm not sure is whether these things would allow me to have something like this:
HEADER_PART
MAIN_CONTENT
FOOTER_PART (also contains links to common JS files that I use)
I would like to dynamically update the MAIN_CONTENT part. Currently my application is only one page, and all my custom logic that belongs to that page is in one JS file. In this JS file, I use a simple $(function() { ... to load my page, so whenever it gets loaded, parts of my page get updated asyncronously. This is fine, since all my blocks in this certain page would have to be loaded when that one page gets loaded.
But what if I have a link, like main.html#otherscreen, and when I click that screen, I would like to change my MAIN_CONTENT and also run another page load specific JS that handles blocks on that other screen, not the first page?
I know I could still use probably server side templating and load my pages using AJAX requrests, but again, not sure whether that is the right approach.
Could you please enlighten me? :)
Thanks & best regards,
Bence
Check out jQuery.load(). Using this function you can dynamically load content into a div on the page, which is what I think you want to do. Just find the div on the page you want to load content into and call
$('#mydiv').load(url, data, function(response){
//do something once it's done.
});
Per your comments...
This is actually very easy. .load() should replace the content in the div (I think. If not, just call .empty() first). Of course you could get fancy and add effects, like
function changePages(url) {
$('#mydiv').fadeOut('fast', function() {
$(this).load(url, function(response){
$('#mydiv').fadeIn('fast');
});
});
}
To handle things like the hash in the URL, in your click event you have to make sure you first call e.preventDefault():
$('#mylink').click(function(e){
e.preventDefault(); //e is a jquery event object
var link = $(this);
var hash = link.attr('href'); // get the hashtag if the href is '#something'
changePages(someUrl + hash);
});
For dynamic loading of data into the page without changing your header and footer you should use jQuery's AJAX function. It allows you to post requests to the server and receive data back without reloading the page. A simple example would be something like:
<html>
<head>
<title>Example</title>
<!-- Assuming jQuery is already referenced -->
<script type="text/javascript">
$('span.buttonish').click(function(){
$.ajax({
// The URL can be a file or a PHP script of your choosing
// it can also be pure HTML without the <html> tags as they
// are already in your file
url: 'path/to/the/file/that/return/data',
success: function(receivedData) {
// The received data is the content of the file or the return
// data of the script and you can use it as you would with any data
$('#content').html(receivedData);
}
});
});
</script>
</head>
<body>
<div id="header">
<!-- Something -->
</div>
<div id="content">
<span class="buttonish">Click me to change the text... </span>
</div>
</div id="footer">
<!-- Something -->
</div>
</body>
<html>

jQuery code repeating problem

I have a piece of code in jQuery that I use to get the contents of an iFrame after you click a link and once the content is completed loading. It works, but I have a problem with it repeating - at least I think that is what it is doing, but I can't figure out why or how.
jQuery JS:
$(".pageSaveButton").bind("click",function(){
var theID = $(this).attr("rel");
$("#fileuploadframe").load(function(){
var response = $("#fileuploadframe").contents().find("html").html();
$.post("siteCreator.script.php",
{action:"savePage",html:response, id: theID},
function(data){
alert(data);
});
});
});
HTML Links ( one of many ):
<a href="templates/1000/files/index.php?pg=0&preview=false"
target="fileuploadframe" class="pageSaveButton" rel="0">Home</a>
So when you click the link, the page that is linked to is opened into the iframe, then the JS fires and waits for the content to finish loading and then grabs the iframe's content and sends it to a PHP script to save to a file. I have a problem where when you click multiple links in a row to save multiple files, the content of all the previous files are overwritten with the current file you have clicked on. I have checked my PHP and am pretty positive the fault is with the JS.
I have noticed that - since I have the PHP's return value alerted - that I get multiple alert boxes. If it is the first link you have clicked on since the main page loaded - then it is fine, but when you click on a second link you get the alert for each of the previous pages you clicked on in addition to the expected alert for the current page.
I hope I have explained well, please let me know if I need to explain better - I really need help resolving this. :) (and if you think the php script is relevant, I can post it - but it only prints out the $_POST variables to let me know what page info is being sent for debugging purposes.)
Thanks ahead of time,
Key
From jQuery .load() documentation I think you need to change your script to:
$(".pageSaveButton").bind("click",function(){
var theID = $(this).attr("rel");
var lnk = $(this).attr("href");//LINK TO LOAD
$("#fileuploadframe").load(lnk,
function(){
//EXECUTE AFTER LOAD IS COMPLETE
var response = $("#fileuploadframe").contents().find("html").html();
$.post("siteCreator.script.php",
{
action:"savePage",
html:response,
id: theID
},
function(data){alert(data);}
);
});
});
As for the multiple responses, you can use something like blockui to disable any further clicks till the .post call returns.
This is because the line
$("#fileuploadframe").load(function(){
Gets executed every time you press a link. Only add the loadhandler to the iframe on document.ready.
If a user has the ability via your UI to click multiple links that trigger this function, then you are going to run into this problem no matter what since you use the single iframe. I would suggest creating an iframe per save process, that why the rendering of one will not affect the other.

Categories

Resources