Trying to submit a PHP form using jQuery

I've created a very basic HTML form that uses PHP to pass values โ€‹โ€‹through a SQL database. I am trying to do this with the jQuery ajax method as I don't want to reload the page (this also seems to be one of the simplest methods).

However, it doesn't seem to work, the PHP page is returning a 500 error code.

I need to warn you right away that this is the first time I tried this, so it is very likely that this is just a silly mistake with my syntax

HTML:

<form id ="form1">
    <input type="text" name="Test">
    <br><br>
    <input type="number" name="TestNumber">
    <br><br>
    <input type="radio" name="sex" value="male" checked>  Male
    <br>
    <input type="radio" name="sex" value="female"> Female
    <br><br>
    <input type="submit" value="Submit">
</form> 

      

Javascript:

$(document).ready(function() {
    console.log("jquery ready");
    var frm = $('#form1');

    frm.submit(function(ev) {
        $.ajax({
            type: "POST",
            url: "form_validation.php",
            data: frm.serialize(),
            success: function(data) {
                alert('ok');
            }
        });

        ev.preventDefault();
    });
});

      

PHP:

<html>
    <head>
        <title>Untitled</title>
    </head>
    <body>
        <?php
        $servername = "server";
        $username = "user";
        $password = "pass";
        $dbname = "name";
        $test = $_POST[Test];
        $testNumber = $_POST[TestNumber];
        $sex = $_POST[sex];


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

        $sql = "INSERT INTO test (Test, TestNumber, sex, date)
        VALUES ('$test', '$testNumber', '$sex', now())";

        $sqlback = "SELECT ID FROM `test` WHERE sex = \'Male\'";

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

        $conn->close();
        ?> 

    </body>
</html>

      

+3


source to share


1 answer


This line raises an error. Delete +

.

echo "New record created successfully" + . $sqlback;

      

Also check your posts:

$test = isset($_POST[Test]) ? $_POST[Test] : "";

      

Now $test

always contains a value. If $_POST[Test]

so undefined

, what would have resulted in an error.

Your page is currently returning 500 internal server error

. PHP does this when an error occurs and error reporting is disabled.

Turn error reporting in your php.ini. It echoes the error occurring in the server side script, you can catch this error in the network tab of your ajax request.


Bonus tip:

You are loading the full page (PHP code inside HTML body). You just want to return either success or failure when using an ajax call like this and not a full HTML page. The usual way these days is using JSON.



An example based on your code using PHP json_encode

to return JSON:

if ($conn->query($sql) === TRUE) {
  echo json_encode(array("message" => "New record created successfully", "sql" => $sqlback));
} else {
   echo json_encode(array("error" => $sql . "<br>" . $conn->error));
}

      

Now it data-type

will be JSON

. jQuery will probably guess, but you can set data-type : JSON

in options ajax()

. data

is automatically parsed into valid Javascript jQuery using JSON.parse

.

Now you can check in the success clause:

        success: function(data) {
            if (data.error)
            {
               alert(data.error);
            }
            else
            {
               alert(data.message + " " + data.sql);
            }
        }

      

Safety recommendations :

$sql = "INSERT INTO test (Test, TestNumber, sex, date)
VALUES ('$test', '$testNumber', '$sex', now())";

      

This string is susceptible to SQL injection. Use prepared statements

in mysqli

.

$sql = $conn->prepare("INSERT INTO test(Test, TestNumber, sex, date) VALUES (?, ?, ?, ?)");
$sql->bind_param("siss", $test, $testnumber, $sex, now()); //s = string, i = number
$sql->execute(); //execute the query;
$sql->close(); //close the statement.

      

+2


source







All Articles