jquery post return undefined – Education Career Blog

The function is:

<script type="text/javascript">
jQuery(function () {
    jQuery("#JqPostForm").submit(function () {

        jQuery.post("index2.php?option=compon&task=sendemail", jQuery("#JqPostForm").serialize(),

        function (data) {
            alert(data.email_invalid);

            if (data.email_invalid == 'true') {
                jQuery("#message_post").append("Wrong email");
            } else {
                jQuery("#message_post").html("<div class='successMessage'>" + data.email + " is a valid e-mail address. Thank you, " + data.name + ".</div>");
            }
        },

        function (xhr, ajaxOptions, thrownError) {
            alert(xhr.status);
            alert(thrownError);
        }, "json");

        return false;

    });
});
</script>

The json data is returned {“email_invalid”:”true”}

However when accessing alert(data.email_invalid); I’ve got undefined?

,

You’ve got an error handler set where your dataType should be. You can’t set an error handler using $.post; you’ll need to use $.ajax instead:

$.ajax({
    type: 'POST',
    url: "index2.php?option=compon&task=sendemail",
    data: jQuery("#JqPostForm").serialize(),
    success: function (data) {
        alert(data.email_invalid);

        if (data.email_invalid == 'true') {
            jQuery("#message_post").append("Wrong email");
        } else {
            jQuery("#message_post").html("<div class='successMessage'>" + data.email + " is a valid e-mail address. Thank you, " + data.name + ".</div>");
        }
    },
    error: function (xhr, ajaxOptions, thrownError) {
        alert(xhr.status);
        alert(thrownError);
    },
    dataType: 'json'
});

Leave a Comment