views:

382

answers:

1

Hi, I have couple of forms on my php page. I am using jQuery (& Ajax) to process this page and show the results. Let's call the forms as: ToDo and Register forms. I have submit events attached to both the forms so that their corresponding processing takes place on submission. The ToDo form is located towards the top of the page and the Register form is located towards the bottom of the page. There are corresponding tags right above these forms that show the error/success messages when the forms are processed. div #result_todo shows the errors obtained when ToDo form is submitted. div #result shows the errors obtained when Register form is submitted.

The actual problem: Let's say that I tried to submit ToDo form without filling any information. As expected, my related php file processes the submitted info and shows the errors in div #result_todo . There's a cross image located in this div which,when clicked upon, fades away the complete div #result_todo (& it's errors as well)from user display when clicked upon. Now when I scroll to my Register form and try to submit it without filling any info, as expected, my related php file processes the submitted info and shows the errors in div #result. The problem now is that even the div #result_todo shows up along with the errors in it, when in fact it should not. This is unwanted as I wanted to submit only the Register form and I have to be shown only the errors related to this form and not the ToDo form.

To reduce the amount of coding, I am calling the function to show the error messages in the success event(?) of the form submission. So I feel maybe that's where something is going wrong. I am very new to jQuery and javascripting, so kindly bear with me. The code is below:

<script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
 function removeElement(divRemove) {
     $(divRemove).fadeOut(1000);
    }

function theResult(data, popuDivDel)    {

    var popuDiv = popuDivDel;

    $(popuDiv).removeClass('success'); //remove the classes to avoid overlapping
    $(popuDiv).removeClass('error'); //remove the classes to avoid overlapping

    //If var success received from the php file is 0, then that means there was an error
    if(data.success == 0) 
     {      
      $(popuDiv).html(data.message); //attach the message to the div
      $(popuDiv).addClass('error');  //attach the error class to the result div to show the errors
      //Add a link to dismiss the errors
      $(popuDiv).prepend('<a href=\"javascript:;\" onclick=\"removeElement(\''+popuDiv+'\')\"><img src="images/dismiss.png" alt="Dismiss Errors" title="Dismiss Errors" width="20" height="20" align="right" /></a>');
     }     
    else if(data.success == 1)  //means that our submission was good
     {
      $(popuDiv).html(data.message); //attach the message to the div
      $(popuDiv).addClass('success'); //attach the success class to the result div to show success msg
      setTimeout(function(){ $(popuDiv).fadeOut('slow'); }, 2000); //attach the animated effect as well
     }

}
</script>



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

    $().ajaxStart(function() {
     $('#loading').show();
     $('#result').hide();

     $('#loading_todo').show();
     $('#result_todo').hide();
    }).ajaxStop(function() {
     $('#loading').hide();
     $('#result').fadeIn('slow');

     $('#loading_todo').hide();
     $('#result_todo').fadeIn('slow');  
    });


    $('#myForm').submit(function() {
     $.ajax({
      type: 'POST',
      url: $(this).attr('action'),
      data: $(this).serialize(),
      dataType: 'json',
      success: function(data) //trigger this on successful reception of the vars from the php file
         {
          var popuDiv2 = '#result';

          theResult(data, popuDiv2);
         }

     })
     return false;
    });



    $('#frm_todo').submit(function() {
     $.ajax({
      type: 'POST',
      url: $(this).attr('action'),
      data: $(this).serialize(),
      dataType: 'json',   
      success: function(data) //trigger this on successful reception of the vars from the php file
         {
          var popuDivDel = '#result_todo';

          theResult(data, popuDivDel);
         }

     })
     return false;
    });
})
</script>


<h4>ToDo Form</h4>
<div id="loading_todo" style="display:none;"><img src="images/loading.gif" alt="loading..." /></div>
<div id="result_todo" style="display:none;"></div>

<form id="frm_todo" name="frm_todo" method="post" action="proses2.php">
 <label for="todo">Enter to-do item:</label>
<input type="text" name="todo" id="todo" />
<input type="submit" name="sbt_todo" id="sbt_todo" value="Add Item" />
</form>



<p>&nbsp;</p><p>&nbsp;</p><p>&nbsp;</p>




<h4>REGISTER Form</h4>
<div id="loading" style="display:none;"><img src="images/loading.gif" alt="loading..." /></div>
<div id="result" style="display:none;"></div>
<form id="myForm" method="post" action="proses.php">
    <table>
     <tr>
      <td width="100">Name</td>
      <td>
       <input name="name" size="30" type="text" /><?php echo (isset($error)) ? $error['name'] : ''; ?>
      </td>
     </tr>
     <tr>
      <td>e-mail</td>
      <td>
       <input name="email" size="40" type="text" /><?php echo (isset($error)) ? $error['email'] : ''; ?>
      </td>
     </tr>
     <tr>
      <td>phone</td>
      <td>
       <input name="phone" size="40" type="text" /><?php echo (isset($error)) ? $error['phone'] : ''; ?>
      </td>
     </tr>
     <tr>
       <td>comment</td>
       <td><input name="comment" size="40" type="text" id="comment" /><?php echo (isset($error)) ? $error['comment'] : ''; ?></td>
      </tr>
     <tr>
      <td></td>
      <td>
       <input name="submit" type="submit" id="submit" value="Submit" />
       <input type="reset" value="Reset" />
      </td>
     </tr>
    </table>
</form>



<?php //proses.php
//validation

if (trim($_POST['name']) == '') {
    $error['name'] = '- Name Must Fill';
}
if (trim($_POST['email']) == '') {
    $error['email'] = '- Email Must Fill & Valid Mail';
}
if (trim($_POST['phone']) == '') {
    $error['phone'] = '- Phone must be filled';
}
if (trim($_POST['comment']) == '') {
    $error['comment'] = '- Comment must be filled';
}

if ($error) 
    {
     $success = 0;
        $message = '<b>Error</b>: <br />'.implode('<br />', $error);
    } 
else 
    {
     $success = 1;
     $message = '<b>Thank You For Filling This Form</b><br />'; 
    }


print json_encode(array('success' => $success, 'message' => $message)); 
die();
?>

<?php //proses2.php
//validation
    if (trim($_POST['content']) == '') 
    {
     $error['content'] = '- Must Fill Todo';
    }


    if ($error) 
    {
     $success = 0;
        $message = '<b>Error</b>: <br />'.implode('<br />', $error);
     $message .= $error['content'];
    } 
    else 
    {
     $success = 1;
     $message = '<b>Thank You For Filling This Form</b><br />'; 
    }



print json_encode(array('success' => $success, 'message' => $message)); 
die();
?>

Please suggest me a possible solution to this problem while making an efficient use of the functions to reduce the amount of coding it might require to achieve common objectives (like showing the results with their corresponding effects).

Thank you in advance.

A: 

Hiya, just from a quick glance at your code (I haven't testing this thoroughly), I have the following comments:

  • Pressing Enter will submit both forms
    • You could fix this by disabling the Enter key, or the following:
    • Remove the form method (it's already in the $.ajax function)
    • Move the form action into the $.ajax function
    • Replace the input type="submit" with type="button".
    • Change the .submit functions to .click and target the buttons instead of the form.
  • Remove the $.ajaxStart and $.ajaxStop
    • These functions reveal both loading messages when either form is submitted
    • Move the show loading message into the .click function
    • Move the hide loading and fade in result to the end of the .click function

Like, I stated before, I haven't tested any of this (I don't have my php server up), but I do know that both forms submit when pressing enter.

fudgey
Awesome!!! I implemented your solution and seems like it did the trick! Thank you so much for the same. Unfortunately, at the same time, it did break some of the existing functionality. I targeted the forms to submit even though Javascript was disabled and my previous code (i.e $('#myForm').submit(... and $('#from_todo').submit(... ) achieved it. So maybe there's a tweak out there that I can apply to your solution and make the forms work even when JS was disabled? I am looking forward for the fix and can't wait to try it. I would be trying something meanwhile. Thanks so much again.
Devner
if you want the page to work with JS off, then you may be back to your original problem of having both forms submitted at the same time. But if that's ok (with JS off), then start out with the input buttons as submit buttons then when the DOM is loaded, use JS/jQuery to switch the type from submit to button. The only other alternative I can think of to prevent the multiple submissions is to have one form inside an iframe.
fudgey
Also, I found this page (http://bavotasan.com/tutorials/processing-multiple-forms-on-one-page-with-php/) that uses php to determine which form is being submitted... maybe it'll work better?
fudgey
Oh and one last comment about my suggestions above, with JS off, you will need the form method and action for the submit button to work. And you most likely won't need to remove them when you switch the submit type to a button type as I previously suggested.
fudgey
Hi, Thank you so much for your replies (and the link). I have been trying to make the submit forms work in the way that I specified for the past 12+ hours, but no use. I have tried different combination but again, no use.The errors still trigger for both the forms when in fact they should trigger for the relevant ones. I not an expert in jquery but will try to implement your last suggestion. You have been really helpful and I really appreciate all your help. Just in case anytime you find an answer to this problem before I do, please do let me know. Thanks again.
Devner