【问题标题】:PHP and AJAX: AJAX is working, PHP is not implementing queryPHP 和 AJAX:AJAX 正常工作,PHP 没有实现查询
【发布时间】:2025-12-14 12:20:12
【问题描述】:

慢慢但肯定地,我将获得 AJAX。我有一个将文本字段和文件上传到数据库的表单。我之前在 PHP 中使用过查询,但在 AJAX 中没有。现在 AJAX 可以工作,但 PHP 不行。而且我知道有些人会觉得将图像加载到 BLOB 是令人反感的,但查询本身是有效的,所以我想专注于让我的 javascript 与我的 PHP 对话时遇到的问题。我已经疯狂地研究了这个问题并尝试了很多东西,但我发现上传文件很复杂。

问题 1.如果我错了,请纠正我,但是如果javascript和jquery实现“POST”调用,传递的参数不应该出现在页面的URL中?因为他们是。
2. 为什么我的PHP文件没有解析出发送的数据并将其发送到数据库?我可以在 URL 和 Firebug(虽然我也在慢慢学习 Firebug)中看到数据正在传递。我运行了一个测试 php 文件,我正在使用该文件连接数据库。

谢谢!

HTML

<!DOCTYPE html>
<html>
<head>
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script src="http://code.jquery.com/jquery-migrate-1.1.1.min.js"></script>
    <script src="jquery.validate.js"></script>
    <script src="jquery.form.js"></script>
    <script>
        $(document).ready(function(){
            $('#addForm').validate();
            function addRecord() {
                $("#aTable").hide('slow', function () { //this is not working
                    alert('Working on it.');
                });
                $("#tableText").hide('slow', function() {//this is not working
                        alert('Working on it.');
                });
                var output = document.getElementById("message");
                var nAname = document.getElementById("aname");
                var nAInfo = new FormData(document.forms.namedItem("addForm"));
                nAInfo.append('aname', nAname);

               $.ajax({
                type: "POST",
                url: "addPhoto.php",
                data: nAInfo
            });
        });
    </script>
</head>
<body>

<form id="addForm" name="addForm" onsubmit="addRecord()" enctype="multipart/form-data">
    <label>Name: </label>
    <input type="text" id="aname" name="aname" class=required/>
    <br>
    <br>
    <label>Photo: </label>
    <input type="file" id="aimage"  name="aimage" class="required">
    <br>
    <br>
    <input type="submit" value="ADD" />
    <br>
</form>

<div id="message" name="message"></div>
<br>
<br>
<div id="image_display"></div>
</body>
</html>

PHP

<?php
ini_set('display_errors', 'On');
ini_set('display_startup_errors', 'On');
error_reporting(E_ALL);

$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);

if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $db->connect_errno . ") " . $db->connect_error;
}

if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

        echo $_SERVER['REQUEST_METHOD'];

    $aname = $_POST['aname'];
    $errorinfo = $_FILES["aimage"]["error"];
    $filename = $_FILES["aimage"]["name"];
    $tmpfile = $_FILES["aimage"]["tmp_name"];
    $filesize = $_FILES["aimage"]["size"];
    $filetype = $_FILES["aimage"]["type"];

    $fp = fopen($tmpfile, 'r');
    $imgContent = fread($fp, filesize($tmpfile));
    fclose($fp);

    if (!($filetype == "image/jpeg" && $filesize > 0)) {
        echo "Import of photo failed";
    }

    if ($filetype == "image/jpeg" && $filesize > 0 && $filesize < 1048576) {

        if (!($stmt=$mysqli->prepare("INSERT INTO actor_info (aname, aimage_data) VALUES (?,?)"))) {
            echo "Prepare failed: (" . $mysqli->errno . ")" . $mysqli->error;
        }

        if (!$stmt->bind_param("ss", $aname, $imgContent)) {
            echo "Binding parameters failed: (" . $stmt->errno .") " . $stmt->error;
        }

        if (!$stmt->execute()) {
            echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
        }
    $stmt->close();
    }
    else {
        echo "Image must be under 1 MB";
    }

echo mysqli_error();
mysqli_close($mysqli);
?>

【问题讨论】:

  • 停止。从这段代码中退后一步。看看有多疯狂。您正在使用 jquery... 但实现您的 OWN ajax 代码? 为什么? jquery 内置了美妙而简单的 ajax 接口:api.jquery.com/jQuery.post
  • 同样,如果您的表单参数显示在 url 中,那么您可能没有执行 POST,它很可能是 GET。您可以通过在您的 php 代码中执行 echo $_SERVER['REQUEST_METHOD'] 来简单地调试它。您的文件处理代码很糟糕。 addslashes() 太糟糕了,甚至不能希望被称为残暴。 切勿使用它,尤其是在数据库代码中。 绝不*假设文件上传成功。 **从不信任 $_FILES 中的数据
  • @Marc B 我尝试了以下但没有成功 $.ajax({ type: "POST", url: "addActorPhoto.php", data: nAInfo });
  • @Marc B 我把echo $_SERVER['REQUEST_METHOD']放在mysqli连接代码下,在执行文件解析之前没有收到回消息。不确定这是因为我发送代码的方式还是因为 PHP 文件没有去任何地方。对下一步去哪里有什么建议?

标签: php ajax forms file mysqli


【解决方案1】:
$("#aTable").hide('slow', function () { //this is not working
           alert('Working on it.');
});

$("#tableText").hide('slow', function() {//this is not working
           alert('Working on it.');
});

上面的代码不起作用,因为您的 html 代码中没有任何 id 为“#aTable”或“#tableText”的元素。

尝试 print_r($_POST) 来查看是否所有值都到达服务器。

同时使用 JQuery 的 Ajax 函数将使您的代码更容易...下面是一个示例

$.ajax({
        url : $domain + "/index/email/" + "?" + $arguments, //add your args here...
        cache : false,
        beforeSend : function (){
            alert('sending....');
        },
        complete : function($response, $status){
            if ($status != "error" && $status != "timeout") {
                if($response.responseText == "200"){
        alert('done');
                } else {
        alert($response.responseText);
                }
            }
        },
        error : function ($responseObj){
            alert("Something went wrong while processing your request.\n\nError => "
                + $responseObj.responseText);
        }
    }); 

【讨论】:

  • 原谅我的新手,但是$status 是我必须定义的东西,还是服务器的响应,不需要做任何进一步的事情?并且响应是否充当将返回的消息植入指定位置的变量,即var response=document.getElementById("message");
  • 我的代码中有带有这些 id 的元素,但为了简洁起见,我没有发布它们。
  • 您不必定义 $status 它会自动返回。此外,响应将在 $response 对象中返回,因此您可以简单地将响应称为 $response.responseText 并将其加载到您的 div 中,如下所示 $('#message').html($response.responseText);
  • 另外,如果你不想重新发明*,你可以尝试一些现成的插件,它们也提供了额外的功能......即uploadify.com/demos