1

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?

8
  • 1
    You're trying to insert the column into the column because you didn't actually supply any user data to your query. MySQL only has access to $_GET and $_POST params if you pass them through somehow. Commented Nov 8, 2018 at 4:42
  • 1
    Tip: Do try and get out of the habit of cluttering up your code with needless things like === TRUE. Many functions are designed to return values that evaluate as logically true or false so that's redundant. Commented Nov 8, 2018 at 4:42
  • 1
    When using mysqli you should be using parameterized queries and bind_param to add user data to your query. DO NOT use string interpolation or concatenation to accomplish this because you will create severe SQL injection bugs. NEVER put $_POST data directly into a query. Commented Nov 8, 2018 at 4:43
  • 1
    First of all you need to understand difference between server side script and client side script. better start with any tutorials. Commented Nov 8, 2018 at 5:04
  • 1
    NEVER trust user data and ALWAYS check it server side. So it's fine by checking the data with JQuery, but thats just for the usability. You MUST also check it with PHP Commented Nov 8, 2018 at 7:13

1 Answer 1

3

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()

?>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.