Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • syn-rg 282 posts 425 karma points
    Jan 20, 2011 @ 07:21
    syn-rg
    0

    Adding extra drop down options and radio buttons

    I'm trying to add some extra drop down options and radio buttons to the contact form.

    However I'm having trouble getting their values to appear in the email. What do I need to do to get these values to display? I've had a look at adding them to the RVContactFormMailer.asmx.cs file and have added the details to the RV-ContactForm.emailBody library item.

    Can anyone help?

    Cheers,
    JV

    My XSLT:

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE xsl:stylesheet [ <!ENTITY nbsp "&#x00A0;"> <!ENTITY linebreak "&#x0D0A;">]>
    <xsl:stylesheet
      version="1.0"
      xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
      xmlns:msxml="urn:schemas-microsoft-com:xslt"
      xmlns:umbraco.library="urn:umbraco.library"
      xmlns:Exslt.ExsltCommon="urn:Exslt.ExsltCommon"
      xmlns:Exslt.ExsltDatesAndTimes="urn:Exslt.ExsltDatesAndTimes"
      xmlns:Exslt.ExsltMath="urn:Exslt.ExsltMath"
      xmlns:Exslt.ExsltRegularExpressions="urn:Exslt.ExsltRegularExpressions"
      xmlns:Exslt.ExsltStrings="urn:Exslt.ExsltStrings"
      xmlns:Exslt.ExsltSets="urn:Exslt.ExsltSets"
      xmlns:Cultiv.MediaCache="urn:Cultiv.MediaCache"
      xmlns:tagsLib="urn:tagsLib"
      xmlns:BlogLibrary="urn:BlogLibrary"
      exclude-result-prefixes="msxml
    umbraco.library Exslt.ExsltCommon Exslt.ExsltDatesAndTimes
    Exslt.ExsltMath Exslt.ExsltRegularExpressions Exslt.ExsltStrings
    Exslt.ExsltSets Cultiv.MediaCache tagsLib BlogLibrary "
    >


    <xsl:output method="html" omit-xml-declaration="yes"/>

    <xsl:param name="currentPage"/>

    <xsl:template match="/">

    <link href="/css/RVContactForm.css" rel="stylesheet" type="text/css" />
      <!--<script
    type="text/javascript"
    src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>-->

    <script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
    <script type="text/javascript" src="/Scripts/json2.js"></script>
    <script type="text/javascript" src="/Scripts/RVContactForm.js"></script>
    <script type="text/javascript">
    //custom
    error messages for this form fields. we defined them here and not in
    the js file because we need to use the dictionary items from the server.



    var errName =  "<xsl:value-of select='umbraco.library:GetDictionaryItem("RV-ContactForm.error.name")' />";
    var errCompany=  "<xsl:value-of select='umbraco.library:GetDictionaryItem("RV-ContactForm.error.company")' />";
    var errDigits = "<xsl:value-of select='umbraco.library:GetDictionaryItem("RV-ContactForm.error.digits")' />";
    var errPhone = "<xsl:value-of select='umbraco.library:GetDictionaryItem("RV-ContactForm.error.phone")' />";
    var errorEmail = "<xsl:value-of select='umbraco.library:GetDictionaryItem("RV-ContactForm.error.email")' />";
    var errState = "<xsl:value-of select='umbraco.library:GetDictionaryItem("RV-ContactForm.error.state")' />";
    var errSubject = "<xsl:value-of select='umbraco.library:GetDictionaryItem("RV-ContactForm.error.subject")' />";
    var errMessage = "<xsl:value-of select='umbraco.library:GetDictionaryItem("RV-ContactForm.error.message")' />";
    var thankYouHeaderText= "<xsl:value-of select='umbraco.library:GetDictionaryItem("RV-ContactForm.thankYouHeaderText")' />";
    var thankYouMessageText = "<xsl:value-of select='umbraco.library:GetDictionaryItem("RV-ContactForm.thankYouMessageText")' />";
    var failureHeaderText = "<xsl:value-of select='umbraco.library:GetDictionaryItem("RV-ContactForm.failureHeaderText")' />";
    var failureMessageText = "<xsl:value-of select='umbraco.library:GetDictionaryItem("RV-ContactForm.failureMessageText")' />";

    /*
    // custom error messages for this plugin.
    // change the text if you adding new form fields from different types (date, creditcard etc).
            
    jQuery.extend(jQuery.validator.messages, {
    required: "This field is required.",
    remote: "Please fix this field.",
    email: "Please enter a valid email address.",
    url: "Please enter a valid URL.",
    date: "Please enter a valid date.",
    dateISO: "Please enter a valid date (ISO).",
    number: "Please enter a valid number.",
    digits: "Please enter only digits.",
    creditcard: "Please enter a valid credit card number.",
    equalTo: "Please enter the same value again.",
    accept: "Please enter a value with a valid extension.",
    maxlength: jQuery.validator.format("Please enter no more than {0} characters."),
    minlength: jQuery.validator.format("Please enter at least {0} characters."),
    rangelength: jQuery.validator.format("Please enter a value between {0} and {1} characters long."),
    range: jQuery.validator.format("Please enter a value between {0} and {1}."),
    max: jQuery.validator.format("Please enter a value less than or equal to {0}."),
    min: jQuery.validator.format("Please enter a value greater than or equal to {0}.")
    });      
    */
    </script>

    <form id="ContactForm" runat="server" style="margin:0px; padding:0px; display:inline; ">
    <input id="RV_CurrentNodeId" value="{$currentPage/@id}" type="hidden" />
          <div class="ContactForm" id="ContactFormDiv">
            <div class="ContactFormRow">
              <div class="ContactFormCol">
                <label for="name"><xsl:value-of select='umbraco.library:GetDictionaryItem("RV-ContactForm.labels.name")' /></label>
                <input type="text" class="ContactInputReg" name="name" id="name" autocomplete="off" />
              </div>
            </div>
            <div class="ContactFormRow">
              <div class="ContactFormCol">
                <label for="company"><xsl:value-of select='umbraco.library:GetDictionaryItem("RV-ContactForm.labels.company")' /></label>
                <input type="text" class="ContactInputReg" name="company" id="company" autocomplete="off" />
              </div>
            </div>
            <div class="ContactFormRow">
              <div class="ContactFormCol">
                <label for="preferredContact"><xsl:value-of select='umbraco.library:GetDictionaryItem("RV-ContactForm.labels.preferredContact")' /></label>
                <input type="radio" checked="checked" value="Email" name="contactmethod" />
                Email
                <input type="radio" value="Phone" name="contactmethod" />
                Phone
              </div>
            </div>
             <div class="ContactFormRow">
              <div class="ContactFormCol">
                <label for="email"><xsl:value-of select='umbraco.library:GetDictionaryItem("RV-ContactForm.labels.email")' /></label>
                <input type="text" class="ContactInputReg" name="email" id="email" autocomplete="off" />
              </div>
            </div>       
            <div class="ContactFormRow">
              <div class="ContactFormCol">
                <label for="phone"><xsl:value-of select='umbraco.library:GetDictionaryItem("RV-ContactForm.labels.phone")' /></label>
                <input type="text" class="ContactInputReg" name="phone" id="phone" autocomplete="off" />
              </div>
            </div>
            <div class="ContactFormRow">
              <div class="ContactFormCol">
                <label for="state"><xsl:value-of select='umbraco.library:GetDictionaryItem("RV-ContactForm.labels.state")' /></label>
                <fieldset>
                <select name="state" id="state">
                 <option value="none">Please select</option>
                 <option value="ACT">
                    <xsl:value-of select='umbraco.library:GetDictionaryItem("RV-ContactForm.labels.state.dropdown.option1")' />
                  </option>
                  <option value="NSW">
                    <xsl:value-of select='umbraco.library:GetDictionaryItem("RV-ContactForm.labels.state.dropdown.option2")' />
                  </option>
                  <option value="QLD">
                    <xsl:value-of select='umbraco.library:GetDictionaryItem("RV-ContactForm.labels.state.dropdown.option3")' />
                  </option>
                  <option value="SA">
                    <xsl:value-of select='umbraco.library:GetDictionaryItem("RV-ContactForm.labels.state.dropdown.option4")' />
                  </option>
                  <option value="VIC">
                    <xsl:value-of select='umbraco.library:GetDictionaryItem("RV-ContactForm.labels.state.dropdown.option5")' />
                  </option>
                  <option value="WA">
                    <xsl:value-of select='umbraco.library:GetDictionaryItem("RV-ContactForm.labels.state.dropdown.option6")' />
                  </option>
                </select>
              </fieldset>
                <br />
              </div>
            </div>
            <div class="ContactFormRow">
              <p>Note that your enquiry will be fielded by your available state representative.</p>
            </div>
            <div class="ContactFormRow">
              <h3>Your message</h3>
            </div>
            <div class="ContactFormRow">
              <div class="ContactFormCol">
                <label for="subject"><xsl:value-of select='umbraco.library:GetDictionaryItem("RV-ContactForm.labels.subject")' /></label>
                <fieldset>
                <select name="subject" id="subject">
                 <option value="General enquiry">
                    <xsl:value-of select='umbraco.library:GetDictionaryItem("RV-ContactForm.labels.subject.dropdown.option1")' />
                  </option>
                  <option value="Sales enquiry">
                    <xsl:value-of select='umbraco.library:GetDictionaryItem("RV-ContactForm.labels.subject.dropdown.option2")' />
                  </option>
                  <option value="Support">
                    <xsl:value-of select='umbraco.library:GetDictionaryItem("RV-ContactForm.labels.subject.dropdown.option3")' />
                  </option>
                </select>
              </fieldset>
              </div>
            </div>
            <div class="ContactFormRow">
              <div class="ContactFormCol">
     
              <label for="message"><xsl:value-of
    select='umbraco.library:GetDictionaryItem("RV-ContactForm.labels.message")'
    /></label>

                <textarea cols="4" class="ContactInputReg" rows="8" name="message" id="message"></textarea>
              </div>
            </div>
            <div class="ContactFormRow">
              <div class="ContactFormCol">
     
              <input id="submit"  type="button"
    value="{umbraco.library:GetDictionaryItem('RV-ContactForm.labels.submit')}"

    title="{umbraco.library:GetDictionaryItem('RV-ContactForm.labels.submit.title')}"
    class="button" />

              </div>
            </div>
            <div id="ServerMsgContainer" style="display: none;">
              <div id="ServerMsgHeader"></div>
              <div id="ServerMsgMessage"></div>
            </div>
          </div>
        </form>

      
    </xsl:template>

    </xsl:stylesheet>

    My RVContactFormMailer.asmx.cs

    using System;
    using System.Collections;
    using System.ComponentModel;
    using System.Data;
    using System.Linq;
    using System.Web;
    using System.Web.Services;
    using System.Web.Services.Protocols;
    using System.Web.Script.Services;
    using System.Xml;
    using System.Xml.Linq;
    using System.Text;
    using System.Configuration;
    using System.Net;
    using System.Net.Mail;
    using System.Text.RegularExpressions;


    namespace RVContactForm
    {
    public class MailerRequest
    {
    public string name;
    public string company;
    public string preferredContact;
    public string phone;
    public string email;
    public string state;
    public string subject;
    public string message;
    }

    /// <summary>
    /// Send contact form data by mail.
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ScriptService] // To allow this Web Service to be called from script, (using ASP.NET AJAX or JQuery), and return json formatted data.
    [ToolboxItem(false)]
    public class RVContactFormMailer : System.Web.Services.WebService
    {

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public void SendContactForm(MailerRequest req)
    {

    #region get the form data

    string strName, strCompany, strPreferredContact, strPhone, strEmailFrom, strState, strEmailSubject, strMessage;
    strName = req.name;
    strCompany = req.company;
    strPreferredContact = req.preferredContact;
    strPhone = req.phone;
    strEmailFrom = req.email;
    strEmailSubject = req.subject;
    strState = req.state;
    strMessage = req.message;

    #endregion

    #region validate the form data

    string strValidationErr = umbraco.library.GetDictionaryItem("RV-ContactForm.error.serverValidation");

    if (strName==string.Empty)
    {
    throw new HttpRequestValidationException(strValidationErr);
    }
    /*
    if (strCompany==string.Empty)
    {
    throw new HttpRequestValidationException(strValidationErr);
    }
    */
    if (strPhone!=string.Empty)
    {
    bool isNum = Regex.IsMatch(strPhone, "^\\d+(\\.\\d+)?$");

    if (isNum==false || strPhone.Length<7)
    {
    throw new HttpRequestValidationException(strValidationErr);
    }
    }
    if (strEmailSubject==string.Empty)
    {
    throw new HttpRequestValidationException(strValidationErr);
    }

    if (strEmailFrom!=string.Empty)
    {
    //Email Regex String
    Regex reg = new Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");

    // Check if there is NO match in Regex
    if (!reg.IsMatch(strEmailFrom))
    {
    //Does not match RegEx - Invalid email address
    throw new HttpRequestValidationException(strValidationErr);
    }
    }
    if (strMessage==string.Empty)
    {
    throw new HttpRequestValidationException(strValidationErr);
    }

    #endregion

    #region set variables from config files

    string strEmailTo, emailReplyFrom, enableSSL;

    XmlDocument config = new XmlDocument();

    config.Load(HttpContext.Current.Server.MapPath(@"/config/RVContactForm.config"));
    XmlNode root = config.SelectSingleNode("/RVContactForm");
    try
    {
    strEmailTo = root["RV-ContactForm.emailTo"].InnerText;
    emailReplyFrom = root["RV-ContactForm.emailReplyFrom"].InnerText;
    enableSSL = root["RV-ContactForm.enableSSL"].InnerText;
    }
    catch (ConfigurationErrorsException ex)
    {
    throw new ConfigurationErrorsException("error reading configuration file",ex);
    }

    #endregion

    #region set email templates

    string strTime, strDate, strEmailBody, emailReplySubject, emailReplyBody;

    strEmailBody = umbraco.library.GetDictionaryItem("RV-ContactForm.emailBody");
    emailReplySubject = umbraco.library.GetDictionaryItem("RV-ContactForm.emailReplySubject");
    emailReplyBody = umbraco.library.GetDictionaryItem("RV-ContactForm.emailReplyBody");
    strTime = String.Format("{0:HH:mm:ss}", DateTime.Now.ToUniversalTime());
    strDate = String.Format("{0:dd/MM/yyyy}", DateTime.Now.ToUniversalTime());
    strEmailBody = strEmailBody.Replace("[Name]", strName);
    strEmailBody = strEmailBody.Replace("[Subject]", strEmailSubject);
    strEmailBody = strEmailBody.Replace("[Email]", strEmailFrom);
    strEmailBody = strEmailBody.Replace("[Message]", strMessage);
    strEmailBody = strEmailBody.Replace("[Time]", strTime);
    strEmailBody = strEmailBody.Replace("[Date]", strDate);
    strEmailBody = strEmailBody.Replace("[Phone]", strPhone);
    strEmailBody = strEmailBody.Replace("[Company]", strCompany);
    strEmailBody = strEmailBody.Replace("[State]", strState);
    strEmailBody = strEmailBody.Replace("[PreferredContact]", strPreferredContact);

    #endregion

    #region send the contact form

    SmtpClient mySMTPClient = new SmtpClient();
    if (enableSSL=="true")
    {
    mySMTPClient.EnableSsl = true;
    }
    try
    {
    mySMTPClient.Send(strEmailFrom, strEmailTo, strEmailSubject, strEmailBody);

    }
    catch (SmtpException ex)
    {
    throw new SmtpException("error sending mail",ex);
    }

    string strEmailReplyFrom, strEmailReplySubject, strEmailReplyBody;
    strEmailReplyFrom = emailReplyFrom;
    strEmailReplySubject = emailReplySubject;
    strEmailReplyBody = emailReplyBody;
    strEmailReplyBody = strEmailReplyBody.Replace("[Name]", strName);
    try
    {
    mySMTPClient.Send(strEmailReplyFrom, strEmailFrom, strEmailReplySubject, strEmailReplyBody);
    }
    catch (SmtpException ex)
    {
    throw new SmtpException("error sending mail",ex);
    }

    #endregion

    }
    }
    }

    RV-ContactForm.emailBody

    Hello.
    a user of your site has filled in your contact form on [Date] @ [Time] (UTC Global Time).

    Name: [Name]
    Organisation: [Company]
    Preferred contact: [PreferredContact]
    Email: [Email]
    Phone: [Phone]
    State: [State]
    Subject: [Subject]
    Message:
    [Message]
  • Eran 292 posts 436 karma points
    Jan 20, 2011 @ 12:48
    Eran
    0

    you should also add this values to the js file called "RVContactForm".

    in this file you actually send the values from the client side to the web service using Json. look for this line and add it your data:

    var myMailerRequest = { languageID: languageID, name: $('#name').val(), company: $('#company').val(), phone: $('#phone').val(), email: $('#email').val(), subject: $('#subject').val(), message: $('#message').val() };

    update if its help.

    Eran.

  • syn-rg 282 posts 425 karma points
    Jan 21, 2011 @ 00:10
    syn-rg
    0

    Thanks Eran,

    I've updated my js file. But it's still not sending the results from the "preferredContact" and "state" options:

    jQuery.validator.addMethod(
    "selectNone",
    function(value, element) {
    if (element.value == "none")
    {
    return false;
    }
    else return true;
    },
    "Please select an option."
    );
    $(document).ready(function() {


    $(window).unload( function () { GUnload(); } );
    // $("input[type=button]").click(function() {
    $("#submit").click(function() {
    $("#ServerMsgContainer").slideUp();
    var validator = $("#aspnetForm").validate({
    rules: {
    name: { required: true },
    company: { required: true },
    preferredContact: { required: false },
    phone: { required: true, minlength: 7, digits: true },
    email: { required: true, email: true },
    state: { selectNone: true },
    subject: { required: true },
    message: { required: true }
    },
    messages: {
    name: errName,
    company: errCompany,
    phone: {
    required: errPhone,
    minlength: errPhone,
    digits: errDigits
    },
    email: {
    required: errorEmail,
    email: errorEmail
    },
    state: errState,
    subject: errSubject,
    message: errMessage
    },
    submitHandler: function(form) {AjaxSubmit();}
    }).form();
    //AjaxSubmit();
    if ($("#aspnetForm").valid()){
    AjaxSubmit();
    }
    //$("#aspnetForm").submit(); //$(this).closest('form').submit();

    });
    });

    function AjaxSubmit() {
    $("#aspnetForm #submit").attr('disabled', 'disabled');
    $("#aspnetForm #submit").after('<img src="/media/assets/ajax-loader.gif" class="loader" />');

    // Convert the form data into an js object
    var myMailerRequest = { name: $('#name').val(), company: $('#company').val(), preferredContact: $('#preferredContact').val(), phone: $('#phone').val(), email: $('#email').val(), state: $('#state').val(), subject: $('#subject').val(), message: $('#message').val(), nodeid: $("#RV_CurrentNodeId").val() };
    // JSONify the js object - desirialize js object to MailerRequest object. the first param must be equal to the name of the input parameter in the web service method "SendContactForm"
    var data = JSON.stringify({ req: myMailerRequest });

    $.ajax({
    type: "POST",
    url: "/umbraco/webservices/RVContactFormMailer.asmx/SendContactForm",
    data: data,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: AjaxSucceeded,
    error: AjaxFailed

    });
    }

    function AjaxSucceeded(result) {
    $('#ServerMsgHeader').html(thankYouHeaderText);
    $('#ServerMsgMessage').html(thankYouMessageText);

    $("#ServerMsgContainer").removeClass("emailFailure");
    $("#ServerMsgContainer").addClass("emailSuccess");

    $('#ServerMsgContainer').slideDown('slow');
    $('#aspnetForm img.loader').fadeOut('fast', function() { $(this).remove() });
    $("#aspnetForm #submit").attr('disabled', '');
    //$('#ContactFormDiv').slideUp('slow');

    $('#ServerMsgHeader').html(thankYouHeaderText);
    $('#ServerMsgMessage').html(thankYouMessageText);
    $('#ServerMsgContainer').slideDown('slow');
    return
    }

    function AjaxFailed(result) {
    $("#ServerMsgContainer").removeClass("emailSuccess");
    $("#ServerMsgContainer").addClass("emailFailure");
    $('#ServerMsgHeader').html(failureHeaderText);
    $('#ServerMsgMessage').html(failureMessageText);
    $('#ServerMsgContainer').slideDown('slow');
    $('#aspnetForm img.loader').fadeOut('fast', function() { $(this).remove() });
    $("#aspnetForm #submit").attr('disabled', '');
    return;
    }
  • Eran 292 posts 436 karma points
    Jan 21, 2011 @ 02:58
    Eran
    0

    hi,

    you should debug using firebug and see what exactly is send to the webservice.

    you should see something like this.

    { name: eran, company: returnvalue, preferredContact: email, phone: 4564845, email: [email protected], state: SA, subject: test, message: hello

    if you see that all the values is sent properly except the field you added - probebly you are not get the value from this fields properly.

    check your jquery syntax. (by the way, try to send the webservice static values and check if it send properly to you email. if so - again - you have syntax error).

     

  • syn-rg 282 posts 425 karma points
    Jan 21, 2011 @ 06:21
    syn-rg
    0

    Ok I've made a change to the XSLT file and now I have the following result:

    name":"Kevin","company":"Google","preferredContact":"Email","phone":"94216279","email":"jarrod@gmail","state":"WA","subject":"General enquiry","message":"Hello"

    This is the change in the XSLT file:

            <div class="ContactFormRow">
              <div class="ContactFormCol">
                <label for="preferredContact"><xsl:value-of select='umbraco.library:GetDictionaryItem("RV-ContactForm.labels.preferredContact")' /></label>
                <input type="radio" checked="checked" value="Email" name="contactmethod" id="preferredContact" />
                Email
                <input type="radio" value="Phone" name="contactmethod" id="preferredContact" />
                Phone
              </div>
            </div>

    However I'm still not getting the 'preferredContact' or 'state' showing up in the email.

  • Eran 292 posts 436 karma points
    Jan 21, 2011 @ 11:54
    Eran
    0

    sorry but i didnt understand from your answer: did you put static values in the js to check if it gets to the asmx?

    i mean in the line:

    var myMailerRequest = { languageID: languageID, name: $('#name').val(), company: $('#company').val(), phone: $('#phone').val(), email: $('#email').val(), subject: $('#subject').val(), message: $('#message').val() };
    
    
    

    if yes, you should see in firebug all the values sent to the asmx. i want to know for sure so we know that the problem is in the asmx code.

    Thanks

  • syn-rg 282 posts 425 karma points
    Jan 25, 2011 @ 01:15
    syn-rg
    0

    I am seeing all the values sent to the asmx in firebug, however it's not being sent in the email.

    Here's my js file code:

    jQuery.validator.addMethod(
    "selectNone",
    function(value, element) {
    if (element.value == "none")
    {
    return false;
    }
    else return true;
    },
    "Please select an option."
    );
    $(document).ready(function() {


    $(window).unload( function () { GUnload(); } );
    // $("input[type=button]").click(function() {
    $("#submit").click(function() {
    $("#ServerMsgContainer").slideUp();
    var validator = $("#aspnetForm").validate({
    rules: {
    name: { required: true },
    company: { required: true },
    preferredContact: { required: false },
    preferredPhone: { required: false },
    phone: { required: true, minlength: 7, digits: true },
    email: { required: true, email: true },
    state: { selectNone: true },
    subject: { required: true },
    message: { required: true }
    },
    messages: {
    name: errName,
    company: errCompany,
    phone: {
    required: errPhone,
    minlength: errPhone,
    digits: errDigits
    },
    email: {
    required: errorEmail,
    email: errorEmail
    },
    state: errState,
    subject: errSubject,
    message: errMessage
    },
    submitHandler: function(form) {AjaxSubmit();}
    }).form();
    //AjaxSubmit();
    if ($("#aspnetForm").valid()){
    AjaxSubmit();
    }
    //$("#aspnetForm").submit(); //$(this).closest('form').submit();

    });
    });

    function AjaxSubmit() {
    $("#aspnetForm #submit").attr('disabled', 'disabled');
    $("#aspnetForm #submit").after('<img src="/media/assets/ajax-loader.gif" class="loader" />');

    // Convert the form data into an js object
    var myMailerRequest = { name: $('#name').val(), company: $('#company').val(), preferredContact: $('#preferredContact').val(), preferredPhone: $('#preferredPhone').val(), phone: $('#phone').val(), email: $('#email').val(), state: $('#state').val(), subject: $('#subject').val(), message: $('#message').val(), nodeid: $("#RV_CurrentNodeId").val() };
    // JSONify the js object - desirialize js object to MailerRequest object. the first param must be equal to the name of the input parameter in the web service method "SendContactForm"
    var data = JSON.stringify({ req: myMailerRequest });

    $.ajax({
    type: "POST",
    url: "/umbraco/webservices/RVContactFormMailer.asmx/SendContactForm",
    data: data,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: AjaxSucceeded,
    error: AjaxFailed

    });
    }

    function AjaxSucceeded(result) {
    $('#ServerMsgHeader').html(thankYouHeaderText);
    $('#ServerMsgMessage').html(thankYouMessageText);

    $("#ServerMsgContainer").removeClass("emailFailure");
    $("#ServerMsgContainer").addClass("emailSuccess");

    $('#ServerMsgContainer').slideDown('slow');
    $('#aspnetForm img.loader').fadeOut('fast', function() { $(this).remove() });
    $("#aspnetForm #submit").attr('disabled', '');
    //$('#ContactFormDiv').slideUp('slow');

    $('#ServerMsgHeader').html(thankYouHeaderText);
    $('#ServerMsgMessage').html(thankYouMessageText);
    $('#ServerMsgContainer').slideDown('slow');
    return
    }

    function AjaxFailed(result) {
    $("#ServerMsgContainer").removeClass("emailSuccess");
    $("#ServerMsgContainer").addClass("emailFailure");
    $('#ServerMsgHeader').html(failureHeaderText);
    $('#ServerMsgMessage').html(failureMessageText);
    $('#ServerMsgContainer').slideDown('slow');
    $('#aspnetForm img.loader').fadeOut('fast', function() { $(this).remove() });
    $("#aspnetForm #submit").attr('disabled', '');
    return;
    }

    Here's my asmx code:

    using System;
    using System.Collections;
    using System.ComponentModel;
    using System.Data;
    using System.Linq;
    using System.Web;
    using System.Web.Services;
    using System.Web.Services.Protocols;
    using System.Web.Script.Services;
    using System.Xml;
    using System.Xml.Linq;
    using System.Text;
    using System.Configuration;
    using System.Net;
    using System.Net.Mail;
    using System.Text.RegularExpressions;


    namespace RVContactForm
    {
    public class MailerRequest
    {
    public string name;
    public string company;
    public string preferredContact;
    public string phone;
    public string email;
    public string state;
    public string subject;
    public string message;
    }

    /// <summary>
    /// Send contact form data by mail.
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ScriptService] // To allow this Web Service to be called from script, (using ASP.NET AJAX or JQuery), and return json formatted data.
    [ToolboxItem(false)]
    public class RVContactFormMailer : System.Web.Services.WebService
    {

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public void SendContactForm(MailerRequest req)
    {

    #region get the form data

    string strName, strCompany, strPreferredContact, strPhone, strEmailFrom, strState, strEmailSubject, strMessage;
    strName = req.name;
    strCompany = req.company;
    strPreferredContact = req.preferredContact;
    strPhone = req.phone;
    strEmailFrom = req.email;
    strEmailSubject = req.subject;
    strState = req.state;
    strMessage = req.message;

    #endregion

    #region validate the form data

    string strValidationErr = umbraco.library.GetDictionaryItem("RV-ContactForm.error.serverValidation");

    if (strName==string.Empty)
    {
    throw new HttpRequestValidationException(strValidationErr);
    }
    /*
    if (strCompany==string.Empty)
    {
    throw new HttpRequestValidationException(strValidationErr);
    }
    */
    if (strPhone!=string.Empty)
    {
    bool isNum = Regex.IsMatch(strPhone, "^\\d+(\\.\\d+)?$");

    if (isNum==false || strPhone.Length<7)
    {
    throw new HttpRequestValidationException(strValidationErr);
    }
    }
    if (strEmailSubject==string.Empty)
    {
    throw new HttpRequestValidationException(strValidationErr);
    }

    if (strEmailFrom!=string.Empty)
    {
    //Email Regex String
    Regex reg = new Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");

    // Check if there is NO match in Regex
    if (!reg.IsMatch(strEmailFrom))
    {
    //Does not match RegEx - Invalid email address
    throw new HttpRequestValidationException(strValidationErr);
    }
    }
    if (strMessage==string.Empty)
    {
    throw new HttpRequestValidationException(strValidationErr);
    }

    #endregion

    #region set variables from config files

    string strEmailTo, emailReplyFrom, enableSSL;

    XmlDocument config = new XmlDocument();

    config.Load(HttpContext.Current.Server.MapPath(@"/config/RVContactForm.config"));
    XmlNode root = config.SelectSingleNode("/RVContactForm");
    try
    {
    strEmailTo = root["RV-ContactForm.emailTo"].InnerText;
    emailReplyFrom = root["RV-ContactForm.emailReplyFrom"].InnerText;
    enableSSL = root["RV-ContactForm.enableSSL"].InnerText;
    }
    catch (ConfigurationErrorsException ex)
    {
    throw new ConfigurationErrorsException("error reading configuration file",ex);
    }

    #endregion

    #region set email templates

    string strTime, strDate, strEmailBody, emailReplySubject, emailReplyBody;

    strEmailBody = umbraco.library.GetDictionaryItem("RV-ContactForm.emailBody");
    emailReplySubject = umbraco.library.GetDictionaryItem("RV-ContactForm.emailReplySubject");
    emailReplyBody = umbraco.library.GetDictionaryItem("RV-ContactForm.emailReplyBody");
    strTime = String.Format("{0:HH:mm:ss}", DateTime.Now.ToUniversalTime());
    strDate = String.Format("{0:dd/MM/yyyy}", DateTime.Now.ToUniversalTime());
    strEmailBody = strEmailBody.Replace("[Name]", strName);
    strEmailBody = strEmailBody.Replace("[Subject]", strEmailSubject);
    strEmailBody = strEmailBody.Replace("[Email]", strEmailFrom);
    strEmailBody = strEmailBody.Replace("[Message]", strMessage);
    strEmailBody = strEmailBody.Replace("[Time]", strTime);
    strEmailBody = strEmailBody.Replace("[Date]", strDate);
    strEmailBody = strEmailBody.Replace("[Phone]", strPhone);
    strEmailBody = strEmailBody.Replace("[Company]", strCompany);
    strEmailBody = strEmailBody.Replace("[State]", strState);
    strEmailBody = strEmailBody.Replace("[PreferredContact]", strPreferredContact);

    #endregion

    #region send the contact form

    SmtpClient mySMTPClient = new SmtpClient();
    if (enableSSL=="true")
    {
    mySMTPClient.EnableSsl = true;
    }
    try
    {
    mySMTPClient.Send(strEmailFrom, strEmailTo, strEmailSubject, strEmailBody);

    }
    catch (SmtpException ex)
    {
    throw new SmtpException("error sending mail",ex);
    }

    string strEmailReplyFrom, strEmailReplySubject, strEmailReplyBody;
    strEmailReplyFrom = emailReplyFrom;
    strEmailReplySubject = emailReplySubject;
    strEmailReplyBody = emailReplyBody;
    strEmailReplyBody = strEmailReplyBody.Replace("[Name]", strName);
    try
    {
    mySMTPClient.Send(strEmailReplyFrom, strEmailFrom, strEmailReplySubject, strEmailReplyBody);
    }
    catch (SmtpException ex)
    {
    throw new SmtpException("error sending mail",ex);
    }

    #endregion

    }
    }
    }
  • Eran 292 posts 436 karma points
    Jan 25, 2011 @ 12:14
    Eran
    0

    hi,

    in the asmx, try to change the lines:

    strEmailBody = strEmailBody.Replace("[State]", strState);
    strEmailBody
    = strEmailBody.Replace("[PreferredContact]", strPreferredContact);

    to this line:

    strEmailBody = "strPreferredContact=" + strPreferredContact + " strState=" + strState;

    now you will see in your email if you get the right values to the asmx.

    if you see the values: its means that something wrong in your email template that defined in the dictionary named "RV-ContactForm.emailBody".


    
    
    
    
    
                
Please Sign in or register to post replies

Write your reply to:

Draft