views:

288

answers:

1

I have a comment window that opens up in a small jqmodal window. I am trying to use $.ajax to submit the form and show "success" in the small modal window. but in all browsers except firefox, the modal closes when I submit the form.

<script type="text/javascript">
$().ready(function() {

$('.reportForm').submit( function(){
 if (document.rForm.comment.value != "") {
  $('.reportForm').hide();

  $.ajax({
   type: "POST",
   url: "<?php echo $_SERVER["PHP_SELF"]; ?>?c=<?php echo $c; ?>",
   cache: false,
   data: "comment=" + document.rForm.comment.value,
   success: function(html){
      $("#results").append(<?php echo get_option('ddrc_success'); ?> + " ");
      }

  });
  return false;   
 } 

});
});

fs

A: 

I'm not 100% sure but the problem could be in this line:

if (document.rForm.comment.value != "") {

I don't think this code is cross-browser. Assuming rForm in the .reportForm you can replace it with

if ($(this).find("[name='comment']").val()) {

$(this) in this context will reference $('.reportForm'), because you are binding to reportForm's submit event. find("[name='comment']") will locate a child element with attribute name is comment. val() returns the value of the element.

Also, the way you wrote this method if there is no value in the comment field the form will get submitted the normal way.

You should consider moving

return false;

to be the last line in your method.

The whole example reworked:

<script type="text/javascript">
    $(function() {
        $('.reportForm').submit(function() {
            if ($(this).find("[name='comment']").val()) {
                $(this).hide();

                $.ajax({
                    type: "POST",
                    url: "<?php echo $_SERVER["PHP_SELF"]; ?>?c=<?php echo $c; ?>",
                    cache: false,
                    data: "comment=" + $(this).find("[name='comment']").val(),
                    success: function(html) {
                        $("#results").append(<?php echo get_option('ddrc_success'); ?> + " ");
                    }

                });
            } else {
                alert("Please, fill the comment field");
            }
            return false;                   
        });
    });
</script>
Emil Ivanov
Thanks for your response, but it's still not working in other browsers. Still works in FF though.The "return false;" is there because it's supposed to keep the modal window from closing.The code I used is based on this:http://jorenrapini.com/blog/css/jquery-validation-contact-form-with-modal-slide-in-transitionAny other ideas? Thanks.