0

I am trying to check if an email exists in a DB using JQuery. Currently, I am sending the email through an $ajax request:

$(".newsletter form").submit(function (event) {
        event.preventDefault();
        var postData = JSON.stringify($(this).serialize());
        var status = $(".newsletter p");
        status.removeClass('shake');

        $.ajax({
            type: "POST",
            contentType: "application/json;charset=utf-8",
            url: "/Home/AddEmail",
            data: JSON.stringify(postData),
            dataType: "json", 
            success: function(data) {
                if (data == "success")
                    status.html("Thanks for your interest! We will let you know.").slideDown();

                else if (data == "subscribed")
                    status.toggleClass('shake').html("This email is already subscribed.").slideDown();

                else if (data == "invalid")
                    status.toggleClass('shake').html("This email is invalid.").slideDown();

                else if (data == "noValue")
                    status.toggleClass('shake').html("No email specified.").slideDown();

                else
                    status.toggleClass('shake').html("Oops, something went wrong!").slideDown();    

            },
            error: function () {
                status.toggleClass('shake').html("Oops, something went wrong!").slideDown();
            }
        });
    });

And my controller gets it by:

[HttpPost]
        public JsonResult AddEmail(EmailA email)
        {
            string returnMessage = "success";

            if (string.IsNullOrEmpty(email.ToString()))
            {
                return Json("noValue");
            }

            try
            {

                SqlConnection sqlConn =
                    new SqlConnection(ConfigurationManager.ConnectionStrings["ICECONNSTRING"].ConnectionString);

                sqlConn.Open();

                string sSQL = "SELECT COUNT(em_email) FROM v2_email WHERE em_email = @email";
                SqlCommand sqlCommand = new SqlCommand(sSQL, sqlConn) { CommandType = CommandType.Text };

                sqlCommand.Parameters.Add(new SqlParameter("@email", SqlDbType.NVarChar, 50)).Value = email;

                int count = (int)sqlCommand.ExecuteScalar();

                if (count == 0)
                {
                    return Json("subscribed");
                }
            }
            catch (Exception es)
            {
                Console.Write(es.Message);
                return Json("error");
            }


            return Json(returnMessage);
        }

        [Serializable]
        public class EmailA
        {
            public string email { get; set; }
        }

But the value for email is ALWAYS null. Can someone point out where I'm going wrong? I'm new to MVC

2
  • why JSON.stringify twice? and what inputs your form contains? also there's no need to use serialize here. Commented Jun 3, 2013 at 13:58
  • The JSON.stringify was just to force the data (thought it may help). I'm using a template which I HAVE to stick to. When I place alert(postData) I get "email=whatever" Commented Jun 3, 2013 at 14:02

3 Answers 3

1

you use JSON.stringify two times, when serializing your form.

this will lead to a misformed request as in example:

JSON.stringify({x: 5, y: 6}); //"{"x":5,"y":6}"
JSON.stringify(JSON.stringify({x: 5, y: 6})); //""{\"x\":5,\"y\":6}""

UPDATE:

as we learned from the discussion, the problem was a mismatch between the data being sent and the header of the request: for a contentType: "application/json;charset=utf-8", the values of the form need to be serialized properly. after the call to JSON.stringify($(this).serialize()); form data is being sent as a JSON object, with no name that contains a string with urlencoded form data. for a regular post with the data from the form, the contentType header needs to be "application/x-www-form-urlencoded;charset=utf-8", which will be set by JQuery if the data is $(this).serialize() so the proper way would be, as BrunoLM sugessted

....
$.ajax({
        type: "POST",
        url: "/Home/AddEmail", //without setting the contentType
        data: $(this).serialize(),
        dataType: "json", 
        success: function(data) {
...
Sign up to request clarification or add additional context in comments.

6 Comments

Then i would suggest you take an input as a string and deserialize it using JavaScriptSerializer Class within the action. what happens when you post the values directly?
@NewAmbition if you post the form directly to the action, at witch line do you resieve the error?
Line 126, on $.ajax({. Thats if I try @BrunoLM's answer
and if you use data: postData, //without the seccond call to JSON.stringify?
Sorry, I should of said - I've taken all the calls to JSON.stringify out.
|
0

Try this:

var postData = { email: { email: $('#email').val() } };

Comments

0

You are using JSON.stringify twice, and actually all you need is

data: $(this).serialize()

Here is a working example on jsFiddle

1 Comment

Without the JSON.stringify I get the error Invalid JSON primitive

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.