尝试使用jQuery向PHP提交表单

时间:2021-08-15 08:52:01

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

我创建了一个非常基本的HTML表单,它使用PHP将值传递给SQL数据库。我试图通过jquery ajax方法执行此操作,因为我不希望页面重新加载(这似乎也是最简单的方法之一)。

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

但它似乎不起作用,PHP页面返回500错误代码。

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>

1 个解决方案

#1


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.

现在$ test总是包含一个值。如果$ _POST [Test]未定义会引发错误。

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

您的页面当前返回500内部服务器错误。 PHP会在引发错误并关闭错误报告时执行此操作。

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.

请在php.ini中打开错误报告。它回应了服务器端脚本中引发的错误,您可以在ajax请求的网络选项卡中捕获该错误。


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.

您正在加载一个完整的页面(HTML正文中的PHP代码)。您只想在使用像这样的ajax调用时返回成功或失败,而不是完整的HTML页面。这些天的常见方式是使用JSON。

Example based on your code, using PHP's json_encode to return JSON:

基于代码的示例,使用PHP的json_encode返回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.

现在数据类型将是JSON。 jQuery可能会猜测,但您可以在ajax()选项中设置数据类型:JSON。使用JSON.parse,jQuery会自动将数据解析为有效的Javascript。

Now you can test in the success clause:

现在您可以在success子句中进行测试:

        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注入的影响。在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.

#1


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.

现在$ test总是包含一个值。如果$ _POST [Test]未定义会引发错误。

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

您的页面当前返回500内部服务器错误。 PHP会在引发错误并关闭错误报告时执行此操作。

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.

请在php.ini中打开错误报告。它回应了服务器端脚本中引发的错误,您可以在ajax请求的网络选项卡中捕获该错误。


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.

您正在加载一个完整的页面(HTML正文中的PHP代码)。您只想在使用像这样的ajax调用时返回成功或失败,而不是完整的HTML页面。这些天的常见方式是使用JSON。

Example based on your code, using PHP's json_encode to return JSON:

基于代码的示例,使用PHP的json_encode返回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.

现在数据类型将是JSON。 jQuery可能会猜测,但您可以在ajax()选项中设置数据类型:JSON。使用JSON.parse,jQuery会自动将数据解析为有效的Javascript。

Now you can test in the success clause:

现在您可以在success子句中进行测试:

        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注入的影响。在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.