1

So I have form with First_Name, Last_Name, City and Email. I need to check If fields are not empty.

For now, after clicking submit It redirecting to GetFbId.php from here I have 5 values to insert to database: FB_Id, First_Name, Last_Name, City and Email

Form.html

<!DOCTYPE html>
<html>
  <head>
    <title>Registracija</title>
    <meta name="robots" content="noindex, nofollow">

    <!-- include css file here-->
   <link rel="stylesheet" href="css/style.css"/>

    <!-- include JavaScript file here-->
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script type="text/javascript" src="js/registration.js"></script>

  </head>   
  <body>
    <div class="container">
        <div class="main">
          <form class="form"  method="post" action="#">
            <h2>Registracijos forma</h2><hr/>
            <label>First Name: </label>
            <input type="text" name="first_name" id="first_name" required>

            <label>Last Name: </label>
            <input type="text" name="last_name" id="last_name" required>

            <label>City: </label>
            <input type="text" name="city" id="city" required>

            <label>Email: </label>
            <input type="text" name="email" id="email" required>

            <input type="submit" name="register" id="register" value="Register">
          </form>   
        </div>
   </div>
  </body>
</html>

As you see for now It have action="GetFbId.php". I have JS script to check It, but It not working for me. JS is called: registration.js

I'm including in Form.html, inside <head> tags following:

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script type="text/javascript" src="js/registration.js"></script>

And instead of action="GetFbId.php"> I've tried to use action="#">, but in this case nothing happens after I click submit button.

registration.js* looks like:

$(document).ready(function(){

$("#register").click(function(){
    var first_name = $("#first_name").val();
    var last_name = $("#last_name").val();
    var city = $("#city").val();
    var email = $("#email").val();

    if( first_name =='' || last_name =='' || email =='' || city =='')
        {
          alert("Fill all fields.");
        }   
    else if((first_name.length)<3)
        {
            alert("Too short first name.");
        }

    else if((last_name.length)<4)
        {
            alert("Too short last name.");
        }   
    else 
       {
         $.post("GetFbId.php",{first_name: first_name, last_name: last_name, city: city, email: email},
          function(data) {
           if(data=='Success')
           {
            $("form")[0].reset();
           }
           alert(data);
        });
       }

    });

});

And in GetFbId.php I'm trying to get variables in following:

$first_name = $_POST['first_name']; 
$last_name = $_POST['last_name']; 
$city = $_POST['city']; 
$email = $_POST['email']; 

But no action (nothing happens) when submit button is clicked. Have you ideas how to fix It?

  • 1
    Use the HTML `required` property on the form fields that cannot be blank. There is no need to check them with JavaScript. You're not doing anything to prevent the default submit function. Once you fix that you should watch the request / response in your browser's console. – Jay Blanchard Mar 24 '15 at 13:18
  • return false; after alert. – sharafatalee Mar 24 '15 at 13:20
  • put javascript code in the same file in which you have your form. – Pratik Gadoya Mar 24 '15 at 13:20
  • What do you mean by "nothing happens"? Do you at least get the alerts, when the form is incomplete? Or does the whole `onclick` doesnt trigger? – chillichief Mar 24 '15 at 14:12

2 Answers2

0

You need to prevent the default submit action. Otherwise, the button click submits the form, regardless of what you are doing in JavaScript. Your script both validates the input and uses jQuery's .post(), so you need to prevent that default submit action with:

event.preventDefault();

I would also recommend returning false when validation fails.

Updated JavaScript:

$(document).ready(function () {

    $("#register").click(function () { 
        event.preventDefault(); // <--  ADDED THIS LINE
        var first_name = $("#first_name").val();
        var last_name = $("#last_name").val();
        var city = $("#city").val();
        var email = $("#email").val();

        if (first_name == '' || last_name == '' || email == '' || city == '') {
            alert("Fill all fields.");
            return false; // <-- ADDED THIS LINE
        } else if ((first_name.length) < 3) {
            alert("Too short first name.");
            return false; // <-- ADDED THIS LINE
        } else if ((last_name.length) < 4) {
            alert("Too short last name.");
            return false; // <-- ADDED THIS LINE
        } else {
            $.post("GetFbId.php", {
                first_name: first_name,
                last_name: last_name,
                city: city,
                email: email
            },

            function (data) {
                if (data == 'Success') {
                    $("form")[0].reset();
                }
                alert(data);
            });
        }

    });

});

See demo: http://jsfiddle.net/BenjaminRay/n6jqvrra/

You can also let the browser handle the required field validation for you by adding "required" to the required fields. Then you only have to handle the $.post() side of things. However, this is not supported by all old browsers (e.g. IE8) so it's not guaranteed to stop the form from being submitted with empty values.

E.g.:

<input type="text" name="first_name" id="first_name" required>

And, of course, you will need to validate the input on the server side (PHP) as well.

Benjamin Ray
  • 1,855
  • 1
  • 14
  • 32
  • Thank you for an answer, but `event.preventDefault()` not working. The same issue, nothing happens after button is clicked. Helped out only when I added `required`, but I wanted to use JS to check also If valid email entered. – Stanislovas Kalašnikovas Mar 24 '15 at 13:39
  • Did you also add the event to this line? $("#register").click(function (event) { ... } – Benjamin Ray Mar 24 '15 at 13:40
  • @BenjaminRay there's no need to add `event` to the function, since it's a special keyword in Javascript... all event handlers have it defined. The problem is with the event you are preventing (a `click` event instead of a `submit` event: look at my answer). – Alejandro Iván Mar 24 '15 at 13:43
  • Thanks Alejandro, I didn't realize that. Updated answer. – Benjamin Ray Mar 24 '15 at 13:46
  • Stanislovas, what happens when you insert some kind of debugging code (e.g. alert('foo');) in the .click event handler? – Benjamin Ray Mar 24 '15 at 13:47
-1

Add an ID to your form:

<form class="form" id="form_id" method="post" action="GetFbId.php">

Now, instead of capturing the click event on #register, try to capture the submit event of the form.

$('#form_id').submit(function(evt) { // Better to use a form id
    // First, avoid the form being submitted normally (forms change the website from which they are submitted)
    evt.preventDefault();

    // Now do your form checking...
});

So your code will look like:

HTML

<form class="form"  method="post" action="GetFbId.php" id="form_id">
<h2>Registration</h2><hr/>
<label>First Name: </label>
<input type="text" name="first_name" id="first_name">

<label>Last Name: </label>
<input type="text" name="last_name" id="last_name">

<label>City: </label>
<input type="text" name="city" id="city">

<label>Email: </label>
<input type="text" name="email" id="email">
<input type="submit" name="register" id="register" value="Register">
 </form>

Registration.js

$(document).ready(function(){
    $("#form_id").submit(function(){ // Note the "submit" event OF THE FORM
        var $form = $(this); // Save the context of the form
        event.preventDefault(); // Prevent the form from being submitted normally

        var first_name = $( '#first_name' ).val();
        var last_name  = $( '#last_name' ).val();
        var city       = $( '#city' ).val();
        var email      = $( '#email' ).val();

        if (
            first_name.length == 0
            ||
            last_name.length == 0
            ||
            email.length == 0
            ||
            city.length == 0
        )
        {
            alert('All fields are required.');
        }
        else if ( first_name.length < 3 ) alert('First name is too short');
        else if ( last_name.length < 4 ) alert('Last name is too short');
        else 
        {
             $.post( "GetFbId.php", $form.serialize() )
                 .done(function(data) {
                     alert(data); // Print what the server returns
                })
                .fail(function() {
                     alert('An error has occured');
                })
             ;
        }
    });
});
Alejandro Iván
  • 3,969
  • 1
  • 21
  • 30