diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3e345d0 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +test/creds.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 41ede2b..52958ba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,10 @@ # ajaxChimp Changelog +### 2.0.0 - 10/June/2015 + +- +- + ### 1.3.0 - 8/May/2014 - Transalations for success message now work diff --git a/MINIFY.md b/MINIFY.md deleted file mode 100644 index 68b447a..0000000 --- a/MINIFY.md +++ /dev/null @@ -1,10 +0,0 @@ -Here for easy reference - -``` -npm install uglify-js -g -``` - -```js -uglifyjs jquery.ajaxchimp.js -o jquery.ajaxchimp.min.js -uglifyjs jquery.ajaxchimp.langs.js -o jquery.ajaxchimp.langs.min.js -``` \ No newline at end of file diff --git a/README.md b/README.md index c6fea5e..72c4347 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ AjaxChimp is a jQuery plugin that lets you ajaxify your mailchimp form. Use this if you hate the jarring transition to the mailchimp website upon submitting an email address to mailchimp. -**Note**: This relies on an undocumented feature at mailchimp that uses JSONP to allow cross-domain ajax to work. You have been warned. (It has however, been around for at least 3 years that I know of, and probably more.) +**Note**: This relies on an undocumented feature at mailchimp that uses JSONP to allow cross-domain ajax to work. You have been warned. (It has however, been around for at least 4 years that I know of, and probably more.) ## Install @@ -15,18 +15,18 @@ Just add the script to your webpage (along with jQuery ofcourse). Get it here: curl -O https://raw.githubusercontent.com/scdoshi/jquery-ajaxchimp/master/jquery.ajaxchimp.js ``` -#### bower +##### or via bower ``` bower install ajaxchimp ``` - ## Requirements * jQuery -**Note**: Developed with 1.9.1, but it should work with earlier versions. If it does or does not work with a particular version, please open an issue on github. +**Note**: Developed with 2.1.4, but it should work with earlier versions. If it does or does not work with a particular version, please open an issue on github. + ## Use @@ -36,7 +36,7 @@ bower install ajaxchimp $('form-selector').ajaxChimp(); ``` -## Label +## Error / Success messages If a label element is included in the form for the email input, then the success or error message will be displayed in it. A `valid` or `error` class will also be added accordingly. @@ -59,25 +59,30 @@ $('#mc-form').ajaxChimp({ ## Options -### Callback +### Callbacks + +Optionally, you can specify a callback with either method to run after the ajax query to mailchimp succeeds or fails. -Optionally, you can specify a callback with either method to run after the -ajax query to mailchimp succeeds or fails. +The form element that triggered the ajax call is also passed in to the callbacks as the last argument. ```js -$('form-selector').ajaxChimp({ +var formAjaxChimp = $('form-selector').ajaxChimp({ callback: callbackFunction }); -``` -The JSONP response from mailchimp will be passed to the callback function +formAjaxChimp.done(function (data, textStatus, jqXHR, form) { + // success callback code here +}); + +formAjaxChimp.fail(function (jqXHR, textStatus, errorThrown, form) { + // failure callback code here +}); + +formAjaxChimp.always(function () { + var form = arguments[3]; + // always callback code here +}); -```js -function callbackFunction (resp) { - if (resp.result === 'success') { - // Do stuff - } -} ``` ### URL @@ -96,14 +101,26 @@ The mailchimp post url will look like this: http://blahblah.us1.list-manage.com/subscribe/post?u=5afsdhfuhdsiufdba6f8802&id=4djhfdsh99f ``` -### Language Support +### Custom messages + +To display custom messages, override the default english translations. + +Notice the use of `$1`, `$2` etc. These are regular expression groups from the original messages for the parts that are dynamic, such as the email address. You can omit them if you want to use a constant message. -For success and error messages in different languages: +For e.g., to change the success message: + +```js +$.ajaxChimp.translations.en = { + success: 'Why not say this instead, for the email address $1', +} + +``` + +### Multiple language support - Specify the language as an option. - Include `jquery.ajaxchimp.langs.js` in the html file - ```js $('form-selector').ajaxChimp({ language: 'es' @@ -116,13 +133,17 @@ You can also add custom translations just for your website: ```js $.ajaxChimp.translations.es = { - 'submit': 'Grabación en curso...', - 0: 'Te hemos enviado un email de confirmación', - 1: 'Por favor, introduzca un valor', - 2: 'Una dirección de correo electrónico debe contener una sola @', - 3: 'La parte de dominio de la dirección de correo electrónico no es válida (la parte después de la @:)', - 4: 'La parte de usuario de la dirección de correo electrónico no es válida (la parte antes de la @:)', - 5: 'Esta dirección de correo electrónico se ve falso o no válido. Por favor, introduce una dirección de correo electrónico real' + submit: 'Grabación en curso...', + success: 'Te hemos enviado un email de confirmación $1', + error: { + 1: 'Por favor, introduzca un valor', + 2: 'Una dirección de correo electrónico debe contener una sola @', + 3: 'La parte de dominio de la dirección de correo electrónico no es válida (la parte después de la @: $1)', + 4: 'La parte de usuario de la dirección de correo electrónico no es válida (la parte antes de la @: $1)', + 5: 'Esta dirección de correo electrónico se ve falso o no válido. Por favor, introduce una dirección de correo electrónico real', + 6: 'blah blah', + 7: 'blah', + } } ``` @@ -130,15 +151,21 @@ The mapping to english for mailchimp responses and the submit message are as fol ```js // Submit Message - // 'submit': 'Submitting...' - - // Mailchimp Responses - // 0: 'We have sent you a confirmation email' - // 1: 'Please enter a value' - // 2: 'An email address must contain a single @' - // 3: 'The domain portion of the email address is invalid (the portion after the @: )' - // 4: 'The username portion of the email address is invalid (the portion before the @: )' - // 5: 'This email address looks fake or invalid. Please enter a real email address' + // submit: 'Submitting...' + + // Success Message + // success: 'Please confirm by clicking on the link we just sent to $1.' + + // Error Messages + // errors: { + // 1: 'Please enter a value', + // 2: 'An email address must contain a single @', + // 3: 'The domain portion of the email address is invalid (the portion after the @: $1 )', + // 4: 'The username portion of the email address is invalid (the portion before the @: $1 )', + // 5: 'This email address looks fake or invalid. Please enter a real email address', + // 6: 'Too many subscribe attempts for this email address. Please try again in about 5 minutes.', + // 7: '$1 is already subscribed to list $2' + // } ``` diff --git a/ajaxchimp.jquery.json b/ajaxchimp.jquery.json index 6771bcd..228c78f 100644 --- a/ajaxchimp.jquery.json +++ b/ajaxchimp.jquery.json @@ -2,7 +2,7 @@ "name": "ajaxchimp", "title": "jQuery ajaxChimp for MailChimp", "description": "Ajaxify your mailchimp form.", - "version": "1.3.0", + "version": "2.0.0", "main": "./jquery.ajaxchimp.js", "author": { "name": "Siddharth Doshi", @@ -16,7 +16,7 @@ "licenses": [ { "type": "MIT", - "url": "https://raw.github.com/scdoshi/jquery-ajaxchimp/master/LICENSE" + "url": "https://raw.githubusercontent.com/scdoshi/jquery-ajaxchimp/master/LICENSE" } ], "dependencies": { diff --git a/bower.json b/bower.json index 12f6cb8..5c45788 100644 --- a/bower.json +++ b/bower.json @@ -1,6 +1,6 @@ { "name": "ajaxchimp", - "version": "1.3.0", + "version": "2.0.0", "main": "./jquery.ajaxchimp.js", "dependencies": { "jquery": ">=1.9.0" @@ -8,6 +8,6 @@ "ignore": [ "**/.*", "./ajaxchimp.jquery.json", - "./MINIFY.md" + "./src" ] } diff --git a/dist/jquery.ajaxchimp.langs.min.js b/dist/jquery.ajaxchimp.langs.min.js new file mode 100644 index 0000000..2e0eb6e --- /dev/null +++ b/dist/jquery.ajaxchimp.langs.min.js @@ -0,0 +1 @@ +(function($){"use strict";$.ajaxChimp.translations={it:{submit:"Registrazione in corso...",success:"Ti abbiamo inviato una mail di conferma",errors:{1:"Per favore inserisci una mail",2:"Un indirizzo valido contiene una sola @",3:"Il dominio della tua mail non è valido (la porzione dopo la @: $1 )",4:"Il nome della mail non è valido (la porzione prima della @: $1 )",5:"L'indirizzo email sembra finto o non valido: per favore inseriscine uno reale",6:"gflyuigiug"}},de:{submit:"Senden...",success:"Wir haben Ihnen eine Bestätigungs-E-Mail geschickt",errors:{1:"Bitte geben Sie Ihre E-Mail-Adresse ein",2:"Eine E-Mail-Adresse muss ein @ enthalten",3:"Der Domain-Teil der E-Mail-Adresse ist ungültig (der Teil nach dem @: $1)",4:"Der Benutzername der E-Mail-Adresse ist ungültig (der Teil vor dem @: $1)",5:"Diese E-Mail-Adresse scheint gefälscht oder ungültig zu sein. Bitte geben Sie eine echte E-Mail-Adresse an!"}},pl:{submit:"Wysyłanie...",success:"Email z potwierdzeniem został wysłany",errors:{1:"Proszę podać adres email",2:"Adres email musi zawierać jeden znak @",3:"Część adresu z domeną jest niepoprawna (część po znaku @: $1)",4:"Część adresu z użytkownikiem jest niepoprawna (część przed znakiem @: $1)",5:"Ten adres wygląda na nieprawdziwy lub niepoprawny. Proszę podać prawdziwy adres email."}},es:{submit:"Grabación en curso...",success:"Te hemos enviado un email de confirmación",errors:{1:"Por favor, introduzca un valor",2:"Una dirección de correo electrónico debe contener una sola @",3:"La parte de dominio de la dirección de correo electrónico no es válida (la parte después de la @: $1)",4:"La parte de usuario de la dirección de correo electrónico no es válida (la parte antes de la @: $1)",5:"Esta dirección de correo electrónico se ve falso o no válido. Por favor, introduce una dirección de correo electrónico real"}},fr:{submit:"Enregistrement en cours...",success:"Nous vous avons envoyé un e-mail de confirmation",errors:{1:"S'il vous plaît entrer une valeur",2:"Une adresse e-mail doit contenir un seul @",3:"La partie domaine de l'adresse e-mail n'est pas valide (la partie après le @: $1)",4:"La partie nom d'utilisateur de l'adresse email n'est pas valide (la partie avant le signe @: $1)",5:"Cette adresse e-mail semble faux ou non valides. S'il vous plaît entrer une adresse email valide"}}}})(jQuery); \ No newline at end of file diff --git a/dist/jquery.ajaxchimp.min.js b/dist/jquery.ajaxchimp.min.js new file mode 100644 index 0000000..fe1c748 --- /dev/null +++ b/dist/jquery.ajaxchimp.min.js @@ -0,0 +1 @@ +(function($){"use strict";$.ajaxChimp={regexPatterns:{success:/Please confirm by clicking on the link we just sent to (.+@.+)/,submit:/Submitting.../,error:{1:/Please enter a value/,2:/An email address must contain a single @/,3:/The domain portion of the email address is invalid (the portion after the @:(.+))/,4:/The username portion of the email address is invalid (the portion before the @:(.+))/,5:/This email address looks fake or invalid. Please enter a real email address/,6:/.+\#6592.+/,7:/(.+@.+) is already subscribed to list (.+)\..+/}},defaultTranslations:{en:{success:"Please confirm by clicking on the link we just sent to $1",submit:"Submitting...",error:{1:"Please enter a value",2:"An email address must contain a single @",3:"The domain portion of the email address is invalid (the portion after the @: $1)",4:"The username portion of the email address is invalid (the portion before the @: $1)",5:"This email address looks fake or invalid. Please enter a real email address",6:"Too many subscribe attempts for this email address. Please try again in about 5 minutes.",7:"$1 is already subscribed to list $2"}}},translations:{},defaultOptions:{language:"en",errorDiv:"#mce-error-response",successDiv:"#mce-success-response"},successMessage:"Please confirm by clicking on the link we just sent to ",submitMessage:"Submitting...",init:function(selector,options){$(selector).ajaxChimp(options)}};$.ajaxChimp.getTranslation=function(str,language,string_key){if($.ajaxChimp.all_translations[language]&&$.ajaxChimp.all_translations[language][string_key]){var regexPattern=$.ajaxChimp.regexPatterns[string_key];var translation=$.ajaxChimp.all_translations[language][string_key];if($.type(regexPattern)==="regexp"){return str.replace(regexPattern,translation)}else{var matchedRegex,matchedTranslation;$.each(regexPattern,function(id,regex){if(translation[id]&&str.match(regex)!==null){matchedRegex=regex;matchedTranslation=translation[id];return false}});if(matchedRegex&&matchedTranslation){return str.replace(matchedRegex,matchedTranslation)}}}if(language!=="en"){return $.ajaxChimp.getTranslation(str,"en",string_key)}return str};$.fn.ajaxChimp=function(options){$.ajaxChimp.all_translations=$.extend({},$.ajaxChimp.defaultTranslations,$.ajaxChimp.translations);var deferreds=$(this).map(function(i,elem){var deferred=new $.Deferred;var form=$(elem);form.attr("novalidate","true");var settings=$.extend({url:form.attr("action")},$.ajaxChimp.defaultOptions,options);var email=form.find("input[type=email]");email.attr("name","EMAIL");var error_div=$(settings.errorDiv);var success_div=$(settings.successDiv);var url=settings.url.replace("/post?","/post-json?").concat("&c=?");form.on("submit",function(event){event.preventDefault();var msg;var request_data={};var dataArray=form.serializeArray();$.each(dataArray,function(index,item){request_data[item.name]=item.value});$.ajax({url:url,data:request_data,dataType:"jsonp"}).done(function(data,textStatus,jqXHR){if(data.result==="success"){email.removeClass("error").addClass("valid");msg=$.ajaxChimp.getTranslation($.ajaxChimp.successMessage+request_data.EMAIL,settings.language,"success");error_div.text("").hide();success_div.text(msg).show(500)}else{email.removeClass("valid").addClass("error");try{var parts=data.msg.split(" - ",2);if(parts[1]===undefined){msg=data.msg}else{msg=parts[1]}}catch(e){msg=data.msg}msg=$.ajaxChimp.getTranslation(msg,settings.language,"error");success_div.text("").hide();error_div.text(msg).show(500)}deferred.resolve(data,textStatus,jqXHR)}).fail(function(jqXHR,textStatus,errorThrown){console.log("mailchimp ajax submit error: "+errorThrown);deferred.reject(jqXHR,textStatus,errorThrown)});var submitMsg=$.ajaxChimp.getTranslation($.ajaxChimp.submitMessage,settings.language,"submit");error_div.text("").hide();success_div.text(submitMsg).show(500)});return deferred});if(deferreds.length===1){return deferreds[0]}return deferreds}})(jQuery); \ No newline at end of file diff --git a/jquery.ajaxchimp.js b/jquery.ajaxchimp.js deleted file mode 100644 index c803022..0000000 --- a/jquery.ajaxchimp.js +++ /dev/null @@ -1,147 +0,0 @@ -/*! -Mailchimp Ajax Submit -jQuery Plugin -Author: Siddharth Doshi - -Use: -=== -$('#form_id').ajaxchimp(options); - -- Form should have one element with attribute 'type=email' -- Form should have one label element with attribute 'for=email_input_id' (used to display error/success message) -- All options are optional. - -Options: -======= -options = { - language: 'en', - callback: callbackFunction, - url: 'http://blahblah.us1.list-manage.com/subscribe/post?u=5afsdhfuhdsiufdba6f8802&id=4djhfdsh99f' -} - -Notes: -===== -To get the mailchimp JSONP url (undocumented), change 'post?' to 'post-json?' and add '&c=?' to the end. -For e.g. 'http://blahblah.us1.list-manage.com/subscribe/post-json?u=5afsdhfuhdsiufdba6f8802&id=4djhfdsh99f&c=?', -*/ - -(function ($) { - 'use strict'; - - $.ajaxChimp = { - responses: { - 'We have sent you a confirmation email' : 0, - 'Please enter a value' : 1, - 'An email address must contain a single @' : 2, - 'The domain portion of the email address is invalid (the portion after the @: )' : 3, - 'The username portion of the email address is invalid (the portion before the @: )' : 4, - 'This email address looks fake or invalid. Please enter a real email address' : 5 - }, - translations: { - 'en': null - }, - init: function (selector, options) { - $(selector).ajaxChimp(options); - } - }; - - $.fn.ajaxChimp = function (options) { - $(this).each(function(i, elem) { - var form = $(elem); - var email = form.find('input[type=email]'); - var label = form.find('label[for=' + email.attr('id') + ']'); - - var settings = $.extend({ - 'url': form.attr('action'), - 'language': 'en' - }, options); - - var url = settings.url.replace('/post?', '/post-json?').concat('&c=?'); - - form.attr('novalidate', 'true'); - email.attr('name', 'EMAIL'); - - form.submit(function () { - var msg; - function successCallback(resp) { - if (resp.result === 'success') { - msg = 'We have sent you a confirmation email'; - label.removeClass('error').addClass('valid'); - email.removeClass('error').addClass('valid'); - } else { - email.removeClass('valid').addClass('error'); - label.removeClass('valid').addClass('error'); - var index = -1; - try { - var parts = resp.msg.split(' - ', 2); - if (parts[1] === undefined) { - msg = resp.msg; - } else { - var i = parseInt(parts[0], 10); - if (i.toString() === parts[0]) { - index = parts[0]; - msg = parts[1]; - } else { - index = -1; - msg = resp.msg; - } - } - } - catch (e) { - index = -1; - msg = resp.msg; - } - } - - // Translate and display message - if ( - settings.language !== 'en' - && $.ajaxChimp.responses[msg] !== undefined - && $.ajaxChimp.translations - && $.ajaxChimp.translations[settings.language] - && $.ajaxChimp.translations[settings.language][$.ajaxChimp.responses[msg]] - ) { - msg = $.ajaxChimp.translations[settings.language][$.ajaxChimp.responses[msg]]; - } - label.html(msg); - - label.show(2000); - if (settings.callback) { - settings.callback(resp); - } - } - - var data = {}; - var dataArray = form.serializeArray(); - $.each(dataArray, function (index, item) { - data[item.name] = item.value; - }); - - $.ajax({ - url: url, - data: data, - success: successCallback, - dataType: 'jsonp', - error: function (resp, text) { - console.log('mailchimp ajax submit error: ' + text); - } - }); - - // Translate and display submit message - var submitMsg = 'Submitting...'; - if( - settings.language !== 'en' - && $.ajaxChimp.translations - && $.ajaxChimp.translations[settings.language] - && $.ajaxChimp.translations[settings.language]['submit'] - ) { - submitMsg = $.ajaxChimp.translations[settings.language]['submit']; - } - label.html(submitMsg).show(2000); - - return false; - }); - }); - return this; - }; -})(jQuery); diff --git a/jquery.ajaxchimp.langs.js b/jquery.ajaxchimp.langs.js deleted file mode 100644 index f4120a9..0000000 --- a/jquery.ajaxchimp.langs.js +++ /dev/null @@ -1,69 +0,0 @@ -(function ($) { - 'use strict'; - - // ISO-693-1 Language codes: http://en.wikipedia.org/wiki/List_of_ISO_639-1_codes - - // Submit Message - // 'submit': 'Submitting...' - - // Mailchimp Responses - // 0: 'We have sent you a confirmation email' - // 1: 'Please enter a value' - // 2: 'An email address must contain a single @' - // 3: 'The domain portion of the email address is invalid (the portion after the @: )' - // 4: 'The username portion of the email address is invalid (the portion before the @: )' - // 5: 'This email address looks fake or invalid. Please enter a real email address' - - $.ajaxChimp.translations = { - // Translation via https://github.com/lifeisfoo - 'it': { - 'submit': 'Registrazione in corso...', - 0: 'Ti abbiamo inviato una mail di conferma', - 1: 'Per favore inserisci una mail', - 2: 'Un indirizzo valido contiene una sola @', - 3: 'Il dominio della tua mail non è valido (la porzione dopo la @: )', - 4: 'Il nome della mail non è valido (la porzione prima della @: )', - 5: 'L\'indirizzo email sembra finto o non valido: per favore inseriscine uno reale' - }, - // Translation via https://github.com/Cube42 - 'de': { - 'submit': 'Senden...', - 0: 'Wir haben Ihnen eine Bestätigungs-E-Mail geschickt', - 1: 'Bitte geben Sie Ihre E-Mail-Adresse ein', - 2: 'Eine E-Mail-Adresse muss ein @ enthalten', - 3: 'Der Domain-Teil der E-Mail-Adresse ist ungültig (der Teil nach dem @)', - 4: 'Der Benutzername der E-Mail-Adresse ist ungültig (der Teil vor dem @)', - 5: 'Diese E-Mail-Adresse scheint gefälscht oder ungültig zu sein. Bitte geben Sie eine echte E-Mail-Adresse an!' - }, - // Translation via https://github.com/designorant - 'pl': { - 'submit': 'Wysyłanie...', - 0: 'Email z potwierdzeniem został wysłany', - 1: 'Proszę podać adres email', - 2: 'Adres email musi zawierać jeden znak @', - 3: 'Część adresu z domeną jest niepoprawna (część po znaku @: )', - 4: 'Część adresu z użytkownikiem jest niepoprawna (część przed znakiem @: )', - 5: 'Ten adres wygląda na nieprawdziwy lub niepoprawny. Proszę podać prawdziwy adres email.' - }, - // The translations below are from google translate, and may not be accurate. - // Pull requests with translations for other languages as well as corrections are welcome. - 'es': { - 'submit': 'Grabación en curso...', - 0: 'Te hemos enviado un email de confirmación', - 1: 'Por favor, introduzca un valor', - 2: 'Una dirección de correo electrónico debe contener una sola @', - 3: 'La parte de dominio de la dirección de correo electrónico no es válida (la parte después de la @:)', - 4: 'La parte de usuario de la dirección de correo electrónico no es válida (la parte antes de la @:)', - 5: 'Esta dirección de correo electrónico se ve falso o no válido. Por favor, introduce una dirección de correo electrónico real' - }, - 'fr': { - 'submit': 'Enregistrement en cours...', - 0: 'Nous vous avons envoyé un e-mail de confirmation', - 1: 'S\'il vous plaît entrer une valeur', - 2: 'Une adresse e-mail doit contenir un seul @', - 3: 'La partie domaine de l\'adresse e-mail n\'est pas valide (la partie après le @:)', - 4: 'La partie nom d\'utilisateur de l\'adresse email n\'est pas valide (la partie avant le signe @:)', - 5: 'Cette adresse e-mail semble faux ou non valides. S\'il vous plaît entrer une adresse email valide' - } - }; -})(jQuery); diff --git a/jquery.ajaxchimp.langs.min.js b/jquery.ajaxchimp.langs.min.js deleted file mode 100644 index 0477c2d..0000000 --- a/jquery.ajaxchimp.langs.min.js +++ /dev/null @@ -1 +0,0 @@ -(function($){"use strict";$.ajaxChimp.translations={it:{submit:"Registrazione in corso...",0:"Ti abbiamo inviato una mail di conferma",1:"Per favore inserisci una mail",2:"Un indirizzo valido contiene una sola @",3:"Il dominio della tua mail non è valido (la porzione dopo la @: )",4:"Il nome della mail non è valido (la porzione prima della @: )",5:"L'indirizzo email sembra finto o non valido: per favore inseriscine uno reale"},de:{submit:"Senden...",0:"Wir haben Ihnen eine Bestätigungs-E-Mail geschickt",1:"Bitte geben Sie Ihre E-Mail-Adresse ein",2:"Eine E-Mail-Adresse muss ein @ enthalten",3:"Der Domain-Teil der E-Mail-Adresse ist ungültig (der Teil nach dem @)",4:"Der Benutzername der E-Mail-Adresse ist ungültig (der Teil vor dem @)",5:"Diese E-Mail-Adresse scheint gefälscht oder ungültig zu sein. Bitte geben Sie eine echte E-Mail-Adresse an!"},pl:{submit:"Wysyłanie...",0:"Email z potwierdzeniem został wysłany",1:"Proszę podać adres email",2:"Adres email musi zawierać jeden znak @",3:"Część adresu z domeną jest niepoprawna (część po znaku @: )",4:"Część adresu z użytkownikiem jest niepoprawna (część przed znakiem @: )",5:"Ten adres wygląda na nieprawdziwy lub niepoprawny. Proszę podać prawdziwy adres email."},es:{submit:"Grabación en curso...",0:"Te hemos enviado un email de confirmación",1:"Por favor, introduzca un valor",2:"Una dirección de correo electrónico debe contener una sola @",3:"La parte de dominio de la dirección de correo electrónico no es válida (la parte después de la @:)",4:"La parte de usuario de la dirección de correo electrónico no es válida (la parte antes de la @:)",5:"Esta dirección de correo electrónico se ve falso o no válido. Por favor, introduce una dirección de correo electrónico real"},fr:{submit:"Enregistrement en cours...",0:"Nous vous avons envoyé un e-mail de confirmation",1:"S'il vous plaît entrer une valeur",2:"Une adresse e-mail doit contenir un seul @",3:"La partie domaine de l'adresse e-mail n'est pas valide (la partie après le @:)",4:"La partie nom d'utilisateur de l'adresse email n'est pas valide (la partie avant le signe @:)",5:"Cette adresse e-mail semble faux ou non valides. S'il vous plaît entrer une adresse email valide"}}})(jQuery); \ No newline at end of file diff --git a/jquery.ajaxchimp.min.js b/jquery.ajaxchimp.min.js deleted file mode 100644 index 83b637d..0000000 --- a/jquery.ajaxchimp.min.js +++ /dev/null @@ -1 +0,0 @@ -(function($){"use strict";$.ajaxChimp={responses:{"We have sent you a confirmation email":0,"Please enter a value":1,"An email address must contain a single @":2,"The domain portion of the email address is invalid (the portion after the @: )":3,"The username portion of the email address is invalid (the portion before the @: )":4,"This email address looks fake or invalid. Please enter a real email address":5},translations:{en:null},init:function(selector,options){$(selector).ajaxChimp(options)}};$.fn.ajaxChimp=function(options){$(this).each(function(i,elem){var form=$(elem);var email=form.find("input[type=email]");var label=form.find("label[for="+email.attr("id")+"]");var settings=$.extend({url:form.attr("action"),language:"en"},options);var url=settings.url.replace("/post?","/post-json?").concat("&c=?");form.attr("novalidate","true");email.attr("name","EMAIL");form.submit(function(){var msg;function successCallback(resp){if(resp.result==="success"){msg="We have sent you a confirmation email";label.removeClass("error").addClass("valid");email.removeClass("error").addClass("valid")}else{email.removeClass("valid").addClass("error");label.removeClass("valid").addClass("error");var index=-1;try{var parts=resp.msg.split(" - ",2);if(parts[1]===undefined){msg=resp.msg}else{var i=parseInt(parts[0],10);if(i.toString()===parts[0]){index=parts[0];msg=parts[1]}else{index=-1;msg=resp.msg}}}catch(e){index=-1;msg=resp.msg}}if(settings.language!=="en"&&$.ajaxChimp.responses[msg]!==undefined&&$.ajaxChimp.translations&&$.ajaxChimp.translations[settings.language]&&$.ajaxChimp.translations[settings.language][$.ajaxChimp.responses[msg]]){msg=$.ajaxChimp.translations[settings.language][$.ajaxChimp.responses[msg]]}label.html(msg);label.show(2e3);if(settings.callback){settings.callback(resp)}}var data={};var dataArray=form.serializeArray();$.each(dataArray,function(index,item){data[item.name]=item.value});$.ajax({url:url,data:data,success:successCallback,dataType:"jsonp",error:function(resp,text){console.log("mailchimp ajax submit error: "+text)}});var submitMsg="Submitting...";if(settings.language!=="en"&&$.ajaxChimp.translations&&$.ajaxChimp.translations[settings.language]&&$.ajaxChimp.translations[settings.language]["submit"]){submitMsg=$.ajaxChimp.translations[settings.language]["submit"]}label.html(submitMsg).show(2e3);return false})});return this}})(jQuery); \ No newline at end of file diff --git a/minify.sh b/minify.sh new file mode 100755 index 0000000..23c1f37 --- /dev/null +++ b/minify.sh @@ -0,0 +1,8 @@ +#! /bin/bash + +# +# npm install uglify-js -g +# + +uglifyjs src/jquery.ajaxchimp.js -o dist/jquery.ajaxchimp.min.js +uglifyjs src/jquery.ajaxchimp.langs.js -o dist/jquery.ajaxchimp.langs.min.js diff --git a/src/jquery.ajaxchimp.js b/src/jquery.ajaxchimp.js new file mode 100644 index 0000000..7633eda --- /dev/null +++ b/src/jquery.ajaxchimp.js @@ -0,0 +1,244 @@ +/*! +Mailchimp Ajax Submit +jQuery Plugin +Author: Siddharth Doshi + +Use: +=== +$('#form_id').ajaxChimp(options); + +- Form should have one element with attribute 'type=email' +- Error and success messages will be displayed in elements within the form + found by errorSelector, successSelector respectively +- The init function returns a deferred object onto which callbacks can be + attached similar to the jqXhr object returned by $.ajax (done/fail/always) +- All options are optional :). + +Options: +======= +options = { + language: 'en', + errorSelector: '.error-message', + successSelector: '.success-message', + url: 'http://blahblah.us1.list-manage.com/subscribe/post?u=5afsdhfuhdsiufdba6f8802&id=4djhfdsh99f', + token: 'anti-bot token from mailchimp form' +} + +Notes: +===== +To get the mailchimp JSONP url (undocumented), change 'post?' to 'post-json?' and add '&c=?' to the end. +For e.g. 'http://blahblah.us1.list-manage.com/subscribe/post-json?u=5afsdhfuhdsiufdba6f8802&id=4djhfdsh99f&c=?', +*/ + +;(function (factory) { + if (typeof define === 'function' && define.amd) { + define(['jquery'], factory); + } else if (typeof exports === 'object') { + module.exports = factory(require('jquery')); + } else { + factory(jQuery); + } +}(function ($) { + 'use strict'; + + $.ajaxChimp = { + regexPatterns: { + success: /Please confirm by clicking on the link we just sent to (.+@.+)/, + submit: /Submitting.../, + error: { + 1: /Please enter a value/, + 2: /An email address must contain a single @/, + 3: /The domain portion of the email address is invalid \(the portion after the @: (.+)\)/, + 4: /The username portion of the email address is invalid \(the portion before the @: (.+)\)/, + 5: /This email address looks fake or invalid. Please enter a real email address/, + 6: /.+\#6592.+/, + 7: /(.+@.+) is already subscribed to list (.+)\..+', { + style: 'position: absolute; left: -5000px;', + }); + tokenDiv.append($('', { + type: 'text', + name: settings.token, + tabindex: '-1', + value: '' + })); + form.append(tokenDiv); + } else { + tokenInput.attr('name', settings.token); + } + } + + // Add hidden submit element if none present + if (form.find('input[type="submit"]').length === 0) { + var submitInput = $('', { + type: 'submit', + style: 'display: none;', + }); + form.append(submitInput); + } + + var error_div = form.find(settings.errorSelector); + var success_div = form.find(settings.successSelector); + + // Convert url to jsonp url + var url = settings.url.replace('/post?', '/post-json?').concat('&c=?'); + + form.on('submit', function (event) { + event.preventDefault(); + + var msg; + var request_data = {}; + $.each(form.serializeArray(), function (index, item) { + request_data[item.name] = item.value; + }); + + $.ajax({ + url: url, + data: request_data, + dataType: 'jsonp' + }).done(function (data, textStatus, jqXHR) { + if (data.result === 'success') { + email.removeClass('error').addClass('valid'); + if (success_div.length !== 0) { + msg = $.ajaxChimp.getTranslation( + ($.ajaxChimp.successMessage + request_data.EMAIL), + settings.language, + 'success' + ); + error_div.text('').hide(); + success_div.text(msg).show(500); + } + } else{ + email.removeClass('valid').addClass('error'); + if (error_div.length !== 0) { + try { + var parts = data.msg.split(' - ', 2); + if (parts[1] === undefined) { + msg = data.msg; + } else { + msg = parts[1]; + } + } + catch (e) { + msg = data.msg; + } + msg = $.ajaxChimp.getTranslation(msg, settings.language, 'error'); + success_div.text('').hide(); + error_div.text(msg).show(500); + } + } + deferred.resolve(data, textStatus, jqXHR, form); + }).fail(function (jqXHR, textStatus, errorThrown) { + deferred.reject(jqXHR, textStatus, errorThrown, form); + }); + + // Display submit message + email.removeClass('valid error'); + if (success_div.length !== 0) { + var submitMsg = $.ajaxChimp.getTranslation( + $.ajaxChimp.submitMessage, + settings.language, + 'submit' + ); + error_div.text('').hide(); + success_div.text(submitMsg).show(500); + } + }); + return deferred; + }); + if (deferreds.length === 1){ + return deferreds[0]; + } + return deferreds; + }; +})); diff --git a/src/jquery.ajaxchimp.langs.js b/src/jquery.ajaxchimp.langs.js new file mode 100644 index 0000000..9cb3b80 --- /dev/null +++ b/src/jquery.ajaxchimp.langs.js @@ -0,0 +1,91 @@ +(function ($) { + 'use strict'; + + // ISO-693-1 Language codes: http://en.wikipedia.org/wiki/List_of_ISO_639-1_codes + + // Submit Message + // submit: 'Submitting...' + + // Success Message + // success: 'Please confirm by clicking on the link we just sent to $1.' + + // Note: The actual success message sent by mailchimp is too long + // so it has been changed. The actual mesage is this: "Almost finished... We need + // to confirm your email address. To complete the subscription process, please + // click the link in the email we just sent you." + + // Error Messages + // errors: { + // 1: 'Please enter a value', + // 2: 'An email address must contain a single @', + // 3: 'The domain portion of the email address is invalid (the portion after the @: $1 )', + // 4: 'The username portion of the email address is invalid (the portion before the @: $1 )', + // 5: 'This email address looks fake or invalid. Please enter a real email address', + // 6: 'Too many subscribe attempts for this email address. Please try again in about 5 minutes.', + // 7: '$1 is already subscribed to list $2' + // } + + $.ajaxChimp.translations = { + // Translation via https://github.com/lifeisfoo + it: { + submit: 'Registrazione in corso...', + success: 'Ti abbiamo inviato una mail di conferma', + errors: { + 1: 'Per favore inserisci una mail', + 2: 'Un indirizzo valido contiene una sola @', + 3: 'Il dominio della tua mail non è valido (la porzione dopo la @: $1 )', + 4: 'Il nome della mail non è valido (la porzione prima della @: $1 )', + 5: 'L\'indirizzo email sembra finto o non valido: per favore inseriscine uno reale', + 6: 'gflyuigiug' + } + }, + // Translation via https://github.com/Cube42 + de: { + submit: 'Senden...', + success: 'Wir haben Ihnen eine Bestätigungs-E-Mail geschickt', + errors: { + 1: 'Bitte geben Sie Ihre E-Mail-Adresse ein', + 2: 'Eine E-Mail-Adresse muss ein @ enthalten', + 3: 'Der Domain-Teil der E-Mail-Adresse ist ungültig (der Teil nach dem @: $1)', + 4: 'Der Benutzername der E-Mail-Adresse ist ungültig (der Teil vor dem @: $1)', + 5: 'Diese E-Mail-Adresse scheint gefälscht oder ungültig zu sein. Bitte geben Sie eine echte E-Mail-Adresse an!' + } + }, + // Translation via https://github.com/designorant + pl: { + submit: 'Wysyłanie...', + success: 'Email z potwierdzeniem został wysłany', + errors: { + 1: 'Proszę podać adres email', + 2: 'Adres email musi zawierać jeden znak @', + 3: 'Część adresu z domeną jest niepoprawna (część po znaku @: $1)', + 4: 'Część adresu z użytkownikiem jest niepoprawna (część przed znakiem @: $1)', + 5: 'Ten adres wygląda na nieprawdziwy lub niepoprawny. Proszę podać prawdziwy adres email.' + } + }, + // The translations below are from google translate, and may not be accurate. + // Pull requests with translations for other languages as well as corrections are welcome. + es: { + submit: 'Grabación en curso...', + success: 'Te hemos enviado un email de confirmación', + errors: { + 1: 'Por favor, introduzca un valor', + 2: 'Una dirección de correo electrónico debe contener una sola @', + 3: 'La parte de dominio de la dirección de correo electrónico no es válida (la parte después de la @: $1)', + 4: 'La parte de usuario de la dirección de correo electrónico no es válida (la parte antes de la @: $1)', + 5: 'Esta dirección de correo electrónico se ve falso o no válido. Por favor, introduce una dirección de correo electrónico real' + } + }, + fr: { + submit: 'Enregistrement en cours...', + success: 'Nous vous avons envoyé un e-mail de confirmation', + errors: { + 1: 'S\'il vous plaît entrer une valeur', + 2: 'Une adresse e-mail doit contenir un seul @', + 3: 'La partie domaine de l\'adresse e-mail n\'est pas valide (la partie après le @: $1)', + 4: 'La partie nom d\'utilisateur de l\'adresse email n\'est pas valide (la partie avant le signe @: $1)', + 5: 'Cette adresse e-mail semble faux ou non valides. S\'il vous plaît entrer une adresse email valide' + } + } + }; +})(jQuery); diff --git a/test/test.html b/test/test.html new file mode 100644 index 0000000..a76dd60 --- /dev/null +++ b/test/test.html @@ -0,0 +1,42 @@ + + + + + + +
+ Form 1 + +
+ +
+
+ Form 2 + +
+ + + + + + + + diff --git a/test/test.js b/test/test.js new file mode 100644 index 0000000..699e3ae --- /dev/null +++ b/test/test.js @@ -0,0 +1,15 @@ +$(document).ready( function () { + $('.subscribe').attr('action', submit_url); + var a = $('.subscribe').ajaxChimp(); + a.done(function (data, textStatus, jqXhr, form) { + console.log(data); + }); + + $('.subscribe-2').ajaxChimp({ + language: 'it', + errorSelector: '#email-response', + successSelector: '#email-response', + url: submit_url, + token: 'b_88179bccb52af04eb42b11da2_0316d82e30' + }); +});