0

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; }; }); 
1
  • This question can't really be answered without guesswork; could you place the relevant HTML and JS in a jsFiddle? Commented Jun 18, 2013 at 4:15

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Forgot to mention my form gets submitted on enter press i.e. $('#commentForm').keydown(function(e) { if (e.keyCode == 13) {

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.