3

Ive created a very basic HTML form which uses PHP to pass the values through to a SQL database. I'm attempting to do this through the jquery ajax method as I dont want the page to reload (this also seems like one of the simplest methods).

However it doesnt seem to work, the PHP page returns a 500 error code.

Right away need to warn you this is the first time ive tried this, so very probable its just a really stupid 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>
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
Ash
  • 169
  • 1
  • 2
  • 13
  • 1
    Please describe more detail about __"it doesnt seem to work"__. – fuyushimoya Aug 02 '15 at 11:10
  • Please also post your PHP code here. – Mouser Aug 02 '15 at 11:13
  • 1
    Open your browser's dev tools, and check the Networks tab. What is the status code returned by the PHP script? – kkaosninja Aug 02 '15 at 11:13
  • 500 server error returned from php page – Ash Aug 02 '15 at 11:19
  • the submit button work fine ( [Fiddle Example](http://jsfiddle.net/eup8uoqv/7/) ) you can see in network tab on your browser console that the submit send the fields values to your php page `form_validation.php`. – Zakaria Acharki Aug 02 '15 at 11:19
  • Please turn error reporting on in your `php.ini`. It will tell you the error that is being raised inside the server side script. – Mouser Aug 02 '15 at 11:23
  • Turned on error reporting. It now seems to submit correctly (not sure why it is now working though!), however none of the data is being saved to the database table – Ash Aug 02 '15 at 11:31
  • **Danger**: You are **vulnerable to [SQL injection attacks](http://bobby-tables.com/)** that you need to [defend](http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php) yourself from. – Quentin Aug 02 '15 at 12:35

1 Answers1

2

This line is causing an error. Please remove the +.

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

Also test your post vars:

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

Now $test always contains a value. If $_POST[Test] was undefined that would raise an error.

Your page is currently returning a 500 internal server error. PHP does that when an error is raised and error reporting is off.

Please turn error reporting on in your php.ini. It echo the error that is being raised inside the server side script, you can catch that error inside the network tab on your ajax request.


A tip as bonus:

You are loading a complete 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 complete HTML page. The common way these days is by using JSON.

Example based on your code, using PHP's 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 the data-type will be JSON. jQuery would probably guess that, but you can set the data-type : JSON in the ajax() options. data is automatically parsed into valid Javascript by jQuery using JSON.parse.

Now you can test in the success clause:

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

Security advice:

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

This line 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.
Mouser
  • 13,132
  • 3
  • 28
  • 54
  • that seems to have got it, thanks a lot. Im really new to PHP, i find the syntax a real headache! so with the success clause, would this go within PHP as well? or would i have to GET it with jquery? – Ash Aug 02 '15 at 11:39
  • Try to see in the network tab of your browser (accessible via `F12`) what the page returned is telling you. There might be some php errors on it. – Mouser Aug 02 '15 at 11:57