Skip to content

Instantly share code, notes, and snippets.

@coccoinomane
Last active November 26, 2019 19:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coccoinomane/c8a06a556028a66b7337da2eb9fe5d4f to your computer and use it in GitHub Desktop.
Save coccoinomane/c8a06a556028a66b7337da2eb9fe5d4f to your computer and use it in GitHub Desktop.
MailUp subscription via Javascript
/**
* Subscribe user in MailUp upon form completion, using MailUp
* HTTP API.
*
* To hook into the form submission we use button click rather than
* actual submission, because the latter approach (using $('form').submit)
* does not seem to work.
*
* The MailUp API specifications can be found here:
* http://help.mailup.com/display/mailupapi/HTTP+API+Specifications
*
* Created by Guido Walter Pettinari on 22/05/2016
*/
jQuery(document).ready(function() {
$('.submit-button').click(function(event) {
/* Prevent the form from being submitted. We shall trigger the submission
below depending on the outcome of the Mailup subscription. */
event.preventDefault();
/* true => print debug messages to console */
debug = true;
/* Time required to to receive a response from MailUp */
var default_timeout = 700;
/* The button used to submit the form */
var button = jQuery('.submit-button');
/* Prevent the user from clicking again on the button until the
request has gone through. Make sure the delay here is smaller
than the delay used to submit the form. */
button.prop('disabled', true);
setTimeout(function() {
button.prop('disabled', false);
}, 0.99*default_timeout);
/* Prevent double click on the button */
button.dblclick(function(event){
event.preventDefault();
});
/* Subscribe the user to MailUp. This function will also take care
of submitting the form. */
mailup_subscribe_user();
/**
* Subscribe the user to MailUp and submit the form.
*/
function mailup_subscribe_user () {
// =========================================================================
// = Customize here =
// =========================================================================
/* Mailup list ID */
var list = '44';
var listGuid = '08f8786b-680c-4a53-bc33-a738f36243fe';
/* Mailup console URL */
var url_subscribe = "http://h1e4.s05.it/frontend/xmlSubscribe.aspx";
var url_check = "http://h1e4.s05.it/frontend/xmlChkSubscriber.aspx";
/* Mailup field for the club */
var clubField = 'campo18';
/* Extract form values */
var firstLast = $('input').filter("[type='text'][id$=-0]").val();
var email = $('input').filter("[type='email'][id$=-1]").val();
var sms = $('input').filter("[type='text'][id$=-2]").val();
var club = $('select').filter("[id$=-3]").val();
/* Extract form values (using exact id's) */
// var base = '#5dd390fbfb351e6557baf3f9da1272dd-';
// var firstLast = $(base + '0').val();
// var email = $(base + '1').val();
// var sms = $(base + '2').val();
// var club = $(base + '3').val();
// =========================================================================
// = Check form input =
// =========================================================================
/* Check that the form values were read correctly */
var form_read = true;
if (firstLast === undefined) {
console.warn("Mailup: Undefined name");
form_read = false;
}
if (email === undefined) {
console.warn("Mailup: Undefined email");
form_read = false;
}
if (sms === undefined) {
console.warn("Mailup: Undefined sms");
form_read = false;
}
if (club === undefined) {
console.warn("Mailup: Undefined club");
form_read = false;
}
/* If the values were not read, issue a warning and just submit the form
without subscribing the user */
if (!form_read) {
console.warn("Mailup: Couldn't read some values, will submit the form without subscribing the user.");
submit_form();
return(false);
}
/* Debug: show user's entry */
if (debug) {
console.log ('name = ' + firstLast);
console.log ('email = ' + email);
console.log ('sms = ' + sms);
console.log ('club = ' + club);
}
/* Extract first & last name */
var first_name = firstLast.split(' ')[0];
var last_name = firstLast.split(' ').slice(1,firstLast.split(' ').length).join(' ');
// =========================================================================
// = Subscribe user =
// =========================================================================
/* Build parameter list. We pass the club as the 18th field in MailUp; make
sure that you have created this field in MailUp in your console options */
var subscribeParams = {
list : list,
email : email,
sms : sms,
confirm : 'false',
csvFldNames : 'campo1;campo2;' + clubField,
csvFldValues : first_name + ';' + last_name + ';' + club,
retCode : 1,
};
if (debug) {
console.log("Request parameters");
console.log(JSON.stringify(subscribeParams, null, 2));
}
/* Subscribe the user to the Mailup list. The request
returns the following codes:
0 Operation completed successfully / Either email address or mobile number has been changed
1 Generic error
2 Invalid email address or mobile number
3 Recipient already subscribed
-1011 IP not registered
See http://help.mailup.com/display/mailupapi/HTTP+API+Specifications for
further details */
$.post(url_subscribe, subscribeParams)
.fail(function(data, textStatus, jqXHR) {
if (debug) {
console.log("MailUp: Server returned failure:");
console.log("-->" + JSON.stringify(jqXHR, null, 2));
}
ga('send', 'event', 'TwentyDabliu', 'Mailup | Server returned failure', email);
/* Submit the form anyway, so that the user can complete the process even
if we couldn't register its email. */
submit_form();
})
.done(function(data, textStatus, jqXHR) {
/* Debug: print request's result */
if (debug) {
console.log("SUBSCRIBE RESULT");
console.log(JSON.stringify(data, null, 2));
console.log(JSON.stringify(textStatus, null, 2));
console.log(JSON.stringify(jqXHR, null, 2));
}
/* Check subscription outcome. */
switch(data) {
case '0\r\n':
if (debug)
console.log ("MailUp: Operation completed successfully");
ga('send', 'event', 'TwentyDabliu', 'Mailup | Email registrata correttamente', email);
submit_form();
break;
case '1\r\n':
if (debug)
console.log ("MailUp: Generic error");
ga('send', 'event', 'TwentyDabliu', 'Mailup | Errore generico', email);
submit_form();
break;
case '2\r\n':
if (debug)
console.log ("MailUp: Invalid email address or mobile number");
ga('send', 'event', 'TwentyDabliu', 'Mailup | Invalid input', email);
alert ("L'email o il numero non sembrano essere nel formato corretto.");
break;
/* Either the email address or the mobile phone number are already registered in
MailUp. In these cases, the API will update rather than create the record */
case '3\r\n':
if (debug)
console.log ("MailUp: Recipient already subscribed");
ga('send', 'event', 'TwentyDabliu', 'Mailup | Utente già inserito', email);
alert ("La tua email o il tuo numero sono già stati registrati nel sistema.");
break;
case '-1011\r\n':
if (debug)
console.log ("MailUp: IP not registered");
ga('send', 'event', 'TwentyDabliu', 'Mailup | IP not registered', email);
submit_form();
break;
/* By default, subscribe the user */
default:
if (debug)
console.log ("MailUp: Codice restituito sconosciuto");
ga('send', 'event', 'TwentyDabliu', 'Mailup | Codice restituito sconosciuto', email);
submit_form();
} // end of switch
});
} // end of mailup_subscribe_user
/**
* Function that submits the form after a delay.
*
* The delay allows MailUp & Google Analytics to process the data. 350ms
* might be a good value (see http://stackoverflow.com/a/19461995/2972183=
*/
function submit_form (delay) {
if (delay === undefined)
delay = default_timeout;
/* Prevent event recursion */
button.unbind('click');
/* Submit the form after a delay */
setTimeout(function(){
button.click();
}, delay);
}
}); // click on submit
}); // document ready
@jackcoral89
Copy link

Ciao ti risulta che funzioni questo codice ?

@coccoinomane
Copy link
Author

Ciao! Ai tempi funzionava, dovrebbe funzionare anche oggi a meno che MailUp non abbia cambiato le API nel frattempo.
Devi configurare la sezione Customize here e, se desideri passare a MailUp anche dei campi anagrafici, i valori csvFldNames e csvFldValues.

@jackcoral89
Copy link

Ho provato a modificarlo un pò ma non sono riuscito a farlo funzionare, alla fine sono passato per PHP ed è andata. Grazie comunque !

@coccoinomane
Copy link
Author

Ok perfetto! Anche io dovendo scegliere oggi propenderei per l'approccio backend... sia per sicurezza che per affidabilità.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment