Copied to clipboard

Flag this post as spam?

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


  • Phillip Turner 98 posts 412 karma points
    May 10, 2016 @ 17:23
    Phillip Turner
    0

    Ajax form Json success is false but returns true

    This is a strange one. I have a Surface controller for an Ajax contact form. I integrated reCaptcha on that form and have an issue. When the reCaptcha is invalid, all logic works and I return a Json value of "Success = false" but when returned to the PartialView, it fires the OnSuccess script and not the OnFailure script. The correct scripts are fired when the form is successful.

    Here is the controller code:

    public class ContactFormController : SurfaceController
    {
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult PostContactFormResults(Models.ContactFormModel model)
        {
            if (!ModelState.IsValid)
            {
                return Json(new { success = false });
            }
    
            string EncodedResponse = Request.Form["g-Recaptcha-Response"];
            ReCaptcha rc = new ReCaptcha();
            rc.PrivateKey = ConfigurationManager.AppSettings["rcSecretKey"];
            bool IsCaptchaValid = (rc.Validate(EncodedResponse) == "True" ? true : false);
    
            if (!IsCaptchaValid)
            {
                return Json(new { success = false });
            }
    
            var service = ApplicationContext.Services.ContentService;
            var config = service.GetById(common.GetConfigurationId("ew"));
            string emailFrom = config.GetValue("contactUsFromEmailAddress").ToString();
            string emailTo = config.GetValue("contactUsEmailRecipients").ToString();
            string emailSubject = config.GetValue("contactUsSubjectLine").ToString();
            string messageTemplate = config.GetValue("contactUsEmailTemplate").ToString();
    
            string _FirstName = model.FirstName;
            string _LastName = model.LastName;
            string _PhoneNumber = model.PhoneNumber;
            string _EmailAddress = model.EmailAddress;
            string _Company = model.Company;
            string _State = model.State;
            string _City = model.City;
            string _Country = model.Country;
            string _ZipPostalCode = model.PostalCode;
            string _BusinessUnit = model.BusinessUnit;
            string _Comments = model.Comments;
            string _DateTimeNow = DateTime.Now.ToString();
    
            string[] messageVariables = { "[FirstName]", "[LastName]", "[PhoneNumber]", "[EmailAddress]", "[BusinessUnit]", "[Company]", "[Country]", "[City]", "[State]", "[PostalCode]", "[DateTimeNow]" };
            string[] modelVariables = { _FirstName, _LastName, _PhoneNumber, _EmailAddress, _BusinessUnit, _Company, _Country, _City, _State, _ZipPostalCode, _DateTimeNow };
    
            for (var i = 0; i < messageVariables.Length; i++)
                messageTemplate = messageTemplate.Replace(messageVariables[i], modelVariables[i]);
    
            Messaging msg = new Messaging();
            msg.EmailFrom = emailFrom;
            msg.EmailTo = emailTo;
            msg.EmailSubjectLine = emailSubject;
            msg.EmailBody = messageTemplate;
            bool result = msg.SendMailMessage();
    
            return Json(new { success = result });
        }
    }
    

    This is in the header of the PartialView:

    @model MyNameSpace.Models.ContactFormModel
    @using (Ajax.BeginForm("PostContactFormResults", "ContactForm", null,  new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "submit-status", OnFailure = "ShowContactError()", OnSuccess = "ShowContactSuccess()" }, new { @id = "frmContact" }))
    

    {

    Can anyone see an obvious mistake? I have 2 forms that are doing this.

    Thanks

    Phillip

  • Nicholas Westby 2054 posts 7103 karma points c-trib
    May 10, 2016 @ 17:32
    Nicholas Westby
    0

    Returning a JSON object that has a property you happen to have named success does not affect the actual success or failure of the response.

    I imagine the JSON result is passed to the OnSuccess function (not sure of how exactly), but it would be in your ShowContactSuccess method that you'd want to check the JSON result to see if the success property is set to true or false and respond accordingly.

  • Phillip Turner 98 posts 412 karma points
    May 10, 2016 @ 17:39
    Phillip Turner
    0

    OnFailture and OnSuccess are defined properties of Ajax.BeginForm() (AjaxOptions), you just tell it what function to fire based on the returned result (true or false). I do not know how to access this result.

    These are the 2 functions that can be called.

    function ShowContactError() {
        $("#submit-status").html("<p style='color: red;'>There was an error while processing your request.  <a style='color: red;' data-dismiss='modal' aria-hidden='true'>Click Here</a> to close this window</p>")
        $("#submit-status").show();
    }
    
    function ShowContactSuccess() {
        //alert("Showing Success");
        $("#submit-status").html("<p style='color: white;'>The request form was successfully transmitted.  <a style='color: white;' data-dismiss='modal' aria-hidden='true'>Click Here</a> to close this window</p>")
        $("#submit-status").show();
    }
    

    https://msdn.microsoft.com/en-us/library/system.web.mvc.ajax.ajaxoptions(v=vs.118).aspx

  • Nicholas Westby 2054 posts 7103 karma points c-trib
    May 10, 2016 @ 17:54
  • Phillip Turner 98 posts 412 karma points
    May 10, 2016 @ 19:35
    Phillip Turner
    0

    That was a good find. Many thanks. I was able to enhance my error responses and is now working like a charm

    OnSuccess = "HandleResponse(data)", OnFailture = "HandleResponse(data)"
    

    client script

    function HandleResponse(data) {
        if (data.success) 
            // Fire Success Message
        else {
            if (data.captureerror)
                // Fire Captcha Specific Error
            else
                // Fire General Error Message
        }
    }
    
Please Sign in or register to post replies

Write your reply to:

Draft