MomasVII
MomasVII

Reputation: 5071

Submit form w/ ajax not working

I am trying to get my comments area to post without refreshing the page using the below code but It just refreshes anyway. I have tried putting return false; everywhere but nothing. Is there an obvious problem i cant see?

    $('#commentForm').keydown(function(e) {
    if (e.keyCode == 13) {
        var songComment = $("#songComment").val();
        var username = $("#username").val();
        var comid = $("#comid").val();
        var dataString = 'songComment=' + songComment + '&username=' + username + '&comid=' + comid;
        if(dataString=='' || songComment=='' || username=='' || comid=='')
        {
            $('.success').fadeOut(200).hide();
            $('.error').fadeOut(200).show();
        }
        else
        {
            $.ajax
            ({
                type: "POST",
                url: "comment.php",
                data: dataString,
                success: function(){
                    $('.success').fadeIn(200).show();
                    $('.error').fadeOut(200).hide();
                }
            });
        }
        return false;
    };
});

Upvotes: 0

Views: 56

Answers (1)

doppelgreener
doppelgreener

Reputation: 5094

There's nothing in there which would cause the page to refresh. You're just submitting an AJAX request and you're not altering the window location at all nor telling it to refresh.

Do you have a submit button inside your comment form? If so, it's probably being activated when the user presses enter. You need to call e.preventDefault() to prevent the event passed to your handler function from taking its normal course of action. Specifically, you need to call that within your handling of only the enter key, i.e.:

$('#commentForm').keydown(function(e) {
    if (e.keyCode == 13) {
        e.preventDefault();
        // do stuff in response to enter key being pressed
    }
}

Otherwise, you'll stop all keystrokes from doing anything!

Of course, this might not help you if the submit button was activated prior to your event handler being called. Consider just using a regular button that isn't a submit button: use a button or input element with a type of button.

Upvotes: 2

Related Questions