javascript 带有jQuery错误处理的Mailchimp Ajax表单

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 带有jQuery错误处理的Mailchimp Ajax表单相关的知识,希望对你有一定的参考价值。

<div id="mc_embed_signup">
<!-- Enter your list id in the action attribute. Make sure the -json? query string present. -->
	<form action="https://myfertilitycenter.us20.list-manage.com/subscribe/post-json?u=328cf2b90d10331e1423c824a&id=31310d343a&c=?" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" validate>
    <div id="mc_embed_signup_scroll">
	  <div class="indicates-required"><span class="asterisk">*</span> indicates required</div>

	<div class="mc-field-group size1of2">
		<label for="mce-FNAME">First Name* </label>
		<input type="text" value="" name="FNAME" required class="mcField" id="mce-FNAME"/>
	</div>
	<div class="mc-field-group size1of2">
		<label for="mce-LNAME">Last Name* </label>
		<input type="text" value="" name="LNAME" required class="mcField" id="mce-LNAME"/>
	</div>
	<div class="mc-field-group size1of2">
		<label for="mce-EMAIL">Email Address  <span class="asterisk">*</span>
	</label>
		<input type="email" value="" name="EMAIL" required class="required email mcField" id="mce-EMAIL"/>
	</div>

		<div class="mc-field-group size1of2">
			<label for="mce-PHONE">Phone Number* </label>
			<input type="text" name="PHONE" required class="mcField" value="" id="mce-PHONE"/>
		</div>

<!-- this is an example of a group/segment dropdown. Error handling for this is in the jQuery -->
<div class="mc-field-group size1of2">
	<label for="mce-group[617]">Services* </label>
	<span class="custom-dropdown">
		<select name="group[617]" required id="mce-group[617]" class="REQ_CSS required mcField">
    	<!-- error handling is based on value.-->
    	<option value=""></option>
    	<option value="256">General Inquiry</option>
    	<option value="1">IVF</option>
    	<option value="2">IUI</option>
    	<option value="4">Egg Donation</option>
    	<option value="8">Receiving Egg/Sperm</option>
    	<option value="16">Fertility Testing</option>
    	<option value="32">Tubal Reversal</option>
    	<option value="64">Hormone Therapy</option>
    	<option value="128">Fertility Preservation</option>
		</select>
</span>
</div>

	<div class="mc-field-group size1of1">
		<label for="mce-COMMENT">Comment </label>
		<textarea type="text" value="" name="COMMENT" class="mcField" id="mce-COMMENT"></textarea>
	</div>
	<!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
			<div style="position: absolute; left: -5000px;" aria-hidden="true"><input type="text" name="b_328cf2b90d10331e1423c824a_31310d343a" tabindex="-1" value=""></div>
			<div class="clear"><input type="submit" value="Submit" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
  <!-- Error and success messages appear here. -->
			<div id="subscribe-result">
				</div>

			</div>
	</form>
	</div>
	
	<!--End mc_embed_signup-->
				
$(document).ready(function () {
  //select the form here
  var $form = $('#mc-embedded-subscribe-form')
  if ($form.length > 0) {
    $('form input[type="submit"]').bind('click', function (event) {
      if (event) {
        event.preventDefault()
        //this is the example of group/segment error handling
        //we do this as soon as the form is submitted
        var serviceSelect = $('select[name="group[617]"]').val();
    		var selectedOption = $('#mce-group[617]').children('option:selected');

     if(serviceSelect === ''){
      $('.mcField').css('borderColor', '#e22929')
        $('#subscribe-result').css('color', '#e22929')
        $('#subscribe-result').html('<p>Please select a service.</p>')
        return false;
     } 
     else{
     // console.log(serviceSelect);
      register($form)
     }

      }
      
    })
  }
})

function register($form) {
  $('#mc-embedded-subscribe').val('Sending...');
  $.ajax({
    type: $form.attr('method'),
    url: $form.attr('action'),
    data: $form.serialize(),
    cache: false,
    dataType: 'json',
    contentType: 'application/json; charset=utf-8',
    error: function (err) { 
      alert('Could not connect to the registration server. Please try again later.') ;
    },
    success: function (data) {
      $('#mc-embedded-subscribe').val('subscribe');
      if (data.result === 'success') {
        // Yeahhhh Success
        $('.mcField').css('opacity', '0.5');
        $('.mcField').css('border-color', '#7F7D78');
        $('#subscribe-result').css('color', '#6C267F')
        $('#subscribe-result').html('<p>Thank you for your message. You\'ll hear from us soon!</p>')
        $('#mce-EMAIL').val('')
      } 
        else {
        	//this needs to be refactored
          function errorMsg(){
            var tooMany = 'too many';
            var alreadyEx = 'already';
            var invalidAt = 'single @';
            var invalidEmail = 'email address is invalid';
            var noFirst = '1 - Please enter a value';
            var noLast = '2 - Please enter a value';
            var noPhone = '4 - Please enter a value';
            var noEmail = '0 - Please enter a value';
            
            if(data.msg.indexOf(noFirst) != -1 || data.msg.indexOf(noLast) != -1){
              return 'Please enter your name';
            }
            if(data.msg.indexOf(noPhone) != -1 ){
              return 'Please enter your phone number';
            }
            if(data.msg.indexOf(tooMany) != -1){
              return 'This email has too many requests. Please try again with a different email.';
            }
            if(data.msg.indexOf(alreadyEx) != -1){
              return "Whoops, you\'ve already signed up for our email list. Send an email to <a href='mailto:info@myfertilitycenter.com'>info@myfertilitycenter.com</a> for any questions or concerns.";
            }
            if(data.msg.indexOf(invalidEmail) != -1 || data.msg.indexOf(invalidAt) != -1 || data.msg.indexOf(noEmail) != -1){
              return 'Please enter a valid email.';
            }
            else{
              data.msg.substring(4) 
            }
          }
        // Something went wrong, do something to notify the user.
        console.log(data.msg)
        $('.mcField').css('borderColor', '#e22929')
        $('#subscribe-result').css('color', '#e22929')
        $('#subscribe-result').html('<p>' + errorMsg() + '</p>')
         
      }
    }
  })
};

以上是关于javascript 带有jQuery错误处理的Mailchimp Ajax表单的主要内容,如果未能解决你的问题,请参考以下文章

当正则表达式有效且在其他地方工作时,带有“m”标志的 Javascript 正则表达式错误、“无效的正则表达式组”

如何处理 JavaScript 或 jQuery 中的 CORS 错误?

jquery引用错误和执行顺序?

JS或者jQuery中怎么处理时间戳为Y-m-d 这样的格式

未捕获的 ReferenceError:无法处理绑定 - 带有淘汰赛的 jquery mobile

使用 Twig 处理动态 Javascript 文件