0

I am facing issues with: 1. getting my form to validate if radio buttons are selected before submitting the form.
2. resetting the form when the user hits submit (without reset button) so that a user may be able to submit another form without having to refresh the page.

I am trying my best to find a solution to the problem I am facing, there are numerous tutorials and other forms I can try but I want to figure out how to use this particular method because this form is working quite well for many of my projects.

The original form that worked great for me in the past had only Name, Email, Phone and Enquiry. But this time I needed to add some more questions, that would need a drop-down select, and a few radio buttons.

I tried my best to use online resources and the form's original working to get it to work, but I am unable to get it validated.

The form submits fine if all fields are filled. The form first checks if the text fields and the drop-down are selected and then checks for php server side errors like length, numbers etc - except for the radio buttons.

The best solution I came up with for the radio buttons was to check if the string length is shorter than 2 letters. But that would not be the right way to do this.

Either ways if a person wants to submit enquiry more than once, they will not be able to use the form unless refreshed.

Please help!!!

I tried using if(!isset...) it didnt work. If I try to add the new fields to //check $_POST vars are set, exit if any missing, the form breaks! I am not able to use most suggestions on stack for other cases, I want to keep this simple and not have to mix two different form methods. My knowledge of coding is still basic, so Im not sure how to fix this.

jquery

            <script type="text/javascript">
            $(document).ready(function() {
                $("#submit_btn").click(function() { 
                    //collect input field values
                var user_location = $('select[name=location]').val();
                var user_chain    = $('input:radio[name=chain]:checked').val();
                var user_number   = $('input:radio[name=number]:checked').val();
                var user_first    = $('input:radio[name=first]:checked').val();
                var user_message    = $('textarea[name=message]').val();


                    //simple validation at client's end
                    //we simply change border color to red if empty field using .css()
                    var proceed = true;
                    if(user_location=="Select Country") {    
                        $('select[name=location]').css('border-color','red'); 
                        proceed = false;
                    }


                    //everything looks good! proceed...
                    if(proceed) 
                    {
                        //data to be sent to server
                        post_data = {'userName':user_name, 'userEmail':user_email, 'userPhone':user_phone, 'userLocation':user_location, 'userChain':user_chain, 'userNumber':user_number, 'userFirst':user_first, 'userMessage':user_message};

                        //Ajax post data to server
                        $.post('contact_me.php', post_data, function(data){  

                            //load success massage in #result div element, with slide effect.       
                            $("#result").hide().html('<div class="success">'+data+'</div>').slideDown();

                            //reset values in all input fields
                            $('#contact_form input').val(''); 
                            $('#contact_form textarea').val('');
                    $('#contact_form select').val(''); 
                            $('#contact_form input[type:radio]').val('');

                        }).fail(function(err) {  //load any error data
                            $("#result").hide().html('<div class="error">'+err.statusText+'</div>').slideDown();
                        }); 
                    }

                });

                //reset previously set border colors and hide all message on .keyup()
                $("#contact_form input, #contact_form textarea, #contact_form select").keyup(function() { 
                    $("#contact_form input, #contact_form textarea, #contact_form select").css('border-color',''); 
                    $("#result").slideUp();
                });

            });
            </script>

PHP SERVER SIDE

            <?php
            if($_POST)
            {
                //check if its an ajax request, exit if not
                if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
                    die();
                } 

                $to_Email       = "xyz@gmail.com"; //Replace with recipient email address
                $subject        = 'Enquiry for Contract Packaging'; //Subject line for emails

                //check $_POST vars are set, exit if any missing
                if(!isset($_POST["userName"]) || !isset($_POST["userEmail"]) || !isset($_POST["userPhone"]) || !isset($_POST["userMessage"]))
                {
                    die();
                }

                //Sanitize input data using PHP filter_var().
                $user_Location    = filter_var($_POST["userLocation"], FILTER_SANITIZE_STRING);
                $user_Chain       = filter_var($_POST["userChain"], FILTER_SANITIZE_STRING);
                $user_Number      = filter_var($_POST["userNumber"], FILTER_SANITIZE_STRING);
                $user_First       = filter_var($_POST["userFirst"], FILTER_SANITIZE_STRING);
                $user_bodymessage ="NAME: ".$user_Name."\n\n";
                $user_bodymessage.="EMAIL: ".$user_Email."\n\n";
                $user_bodymessage.="PHONE: ".$user_Phone."\n\n";
                $user_bodymessage.="LOCATION: ".$user_Location."\n\n";
                $user_bodymessage.="CHAIN: ".$user_Chain."\n\n";
                $user_bodymessage.="QUANTITY: ".$user_Number."\n\n";
                $user_bodymessage.="FIRST TIME: ".$user_First."\n\n";
                $user_bodymessage.="ENQUIRY: ".$user_Message."\n\n";


                //additional php validation
                if(strlen($user_Name)<3) // If length is less than 4 it will throw an HTTP error.
                {
                    header('HTTP/1.1 500 Name is too short or empty!');
                    exit();
                }
                if(!filter_var($user_Email, FILTER_VALIDATE_EMAIL)) //email validation
                {
                    header('HTTP/1.1 500 Please enter a valid email!');
                    exit();
                }
                if(!is_numeric($user_Phone)) //check entered data is numbers
                {
                    header('HTTP/1.1 500 Only numbers allowed in phone field');
                    exit();
                }
                if(strlen($user_Chain)<2) // If length is less than 4 it will throw an HTTP error.
                {
                    header('HTTP/1.1 500 Have you missed a few questions?');
                    exit();
                }
                if(strlen($user_Message)<5) //check emtpy message
                {
                    header('HTTP/1.1 500 Too short message! Please enter something.');
                    exit();
                }
new_frontenddev
  • 173
  • 3
  • 6
  • 20
  • Good grief, you really need to learn to make a [minimal example](http://en.wikipedia.org/wiki/Minimal_Working_Example). Nobody wants to read hundreds of lines of code which is mostly boring; rather it its up to you to make a smaller version that still exhibits the bug or problem. – Antares42 Jan 07 '15 at 22:06
  • @Antares42 you're right. im sorry about that, except it has happened before that ive given minimal info and then been asked to show code. That is why I tried to explain what my issue is, any suggestions? – new_frontenddev Jan 07 '15 at 22:26
  • 1
    For starters, in order to test client-side whether any of the radio buttons is selected you can test in your javascript for ``user_chain===undefined`` (note the three "="). This should work because if nothing is selected/checked, then the jQuery returns an empty object, the ``.val()`` of which is, well, ``undefined``. – Antares42 Jan 07 '15 at 22:49
  • What you do server-side regarding the radio buttons seems fine to me. Checking whether the string content is 2 or more. Since your Ajax request always contains the fields (because you're not sending an HTML form but a custom-made object), that is a reasonable approach. – Antares42 Jan 07 '15 at 22:50
  • 1
    so you mean if(user_chain===undefined) { proceed = false; } but in this structure, how will I indicate to the user that the form is not proceeding because of the radio button questions? The other error hints only turn up from the PHP side. I tried giving color to the text of the radio just like the others that have a red outline but then that does not reset if a person selects one of the radios – new_frontenddev Jan 07 '15 at 22:52
  • But is there any particular reason why you must use Ajax? Is this because the original form did it like that? – Antares42 Jan 07 '15 at 22:52
  • @Antares42 perhaps most likely tht is the reason. But Ajax forms are usually better usability wise – new_frontenddev Jan 07 '15 at 22:55
  • Agreed that Ajax forms are nice, but they do require a lot of JS hacking. Maybe you could have a look at different [client-side validation plugins](http://stackoverflow.com/questions/4751780/best-javascript-solution-for-client-side-form-validation-and-interaction) to make your life a bit easier? – Antares42 Jan 07 '15 at 23:05
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/68372/discussion-between-new-frontenddev-and-antares42). – new_frontenddev Jan 07 '15 at 23:08

0 Answers0