Gosi
Gosi

Reputation: 2003

Validating using JQuery and processing by PHP

I want to validate my form using JQuery and use php to send it to my database.

This is what I've tried:

<body>

    <form id="first_form" method="post" action="">
      <div>
        <label for="first_name">First Name:</label>
        <input type="text" id="first_name" name="first_name"></input>
      </div>
      <div>
        <label for="last_name">Last Name:</label>
        <input type="text" id="last_name" name="last_name"></input>
      </div>
      <div>
        <label for="handphone">Handphone:</label>
        <input type="text" id="handphone" name="handphone"></input>
      </div>
      <div>
        <input type="submit" value="Submit" />
      </div>
    </form>

<script>

    $(document).ready(function() {

      $('#first_form').submit(function(e) {
        e.preventDefault();
        var first_name = $('#first_name').val();
        var last_name = $('#last_name').val();
        var handphone = $('#handphone').val();

        $(".error").remove();

        if (first_name.length < 1) {
          $('#first_name').after('<span class="error">This field is required</span>');
          return false;
        }
        if (last_name.length < 1) {
          $('#last_name').after('<span class="error">This field is required</span>');
          return false;
        }
        if (handphone.length < 1) {
          $('#handphone').after('<span class="error">This field is required</span>');
          return false;
        } 

      });

    });

</script>


<?php   

    $first_name = "<script>var first_name = $('#first_name').val();</script>";
    $last_name = "<script>var first_name = $('#last_name').val();</script>";
    $handphone = "<script>var first_name = $('#handphone').val();</script>";

    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "test";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } 

    $sql = "INSERT INTO vali (first_name, last_name, handphone)
    VALUES (first_name, last_name, handphone)";

    if ($conn->query($sql) === TRUE) {
        echo "New record created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }

    $conn->close();
?>

</body>

So as you can see, the first part is just the html and form.

The second part is where I used Jquery to validate (which works).

Now the issue is at the php part, where it sends the data to my database as empty.

The logic behind my php code is that, I take the values of the variables I set in Jquery and just update it to the database. But its updating empty values.

I tried to return false in Jquery, but its not working for me. May I know what am I doing wrong here?

Upvotes: 1

Views: 453

Answers (1)

Joshua
Joshua

Reputation: 182

Firsty, you have to understand JavaScript in this case is a client-scripting language and PHP is a server-scripting language. Variables can't be pass from JavaScript to PHP is the <script> tag.

Secondly, we have different types of requests; GET, POST, PUT, DELETE and so on. This we can check via PHP. A form can only send two types of request as at the time of me typing this answer, GET and POST request, this is the method value you set in your form. Every value set in a form can be accessed in the request global array and the name of the value being the key/indetifier. $_GET[] if you sent a get request and $_POST[] if you sent a post request.

In your form above, your method is set to POST, meaning all the values would be available in the global $_POST[].

When ever a page loads, the server script gets loaded first before the Client Side / HTML / CSS and other resources used by your document.

PHP has a function called isset() which is used to check if a variable available regardless it's value which is very useful for form validation.

If you ever have PHP codes in file performing logic/operations, it is advisable you placed them topmost of you file since it isn't used in rendering your document/view.

From your code, you should edit as

<?php

    if(isset($_POST['submit'])){ 
        // This block will only be executed when a submit button is triggered

       //Make your connection here, it is not a must but good practice to always make connection first in order to make it available everywhere. Ensure to check if connection was successful or not.

     $first_name = $_POST['first_name']; // this gives you the exact value you passed in the form.

       ... 
       // All you variables should be assigned using the above method

     //in the above assignation of variables, we didn't sanitize. mysqli has a method real_escape_string() which does that for us. Ensure to always sanitize and properly validate inputs you send to your DB

    //Sanitizing inputs
    $first_name = $con ->real_escape_string($first_name);

    // Do the above for other inputs, then you are good to perform an insert.

   $result = $conn->query($sql);
   if($result){
       //Record has been inserted, you can choose to redirect or do some other logic
   }else{ 
       //Record was not successfully inserted. Print your error if in development to get an insight to what went wrong
  }

  }

  $conn->close()

?>

Upvotes: 3

Related Questions