【问题标题】:How do I connect my ajax post to php and mysql?如何将我的 ajax 帖子连接到 php 和 mysql?
【发布时间】:2015-01-22 07:32:15
【问题描述】:

我花了几个小时逐步测试我的所有代码,但仍然无法使其正常工作。我最终得到了 php 文件以将测试对象发送到 mysql 数据库,但我仍然无法让 jQuery ajax 帖子连接到 php。谁能发现这个问题?我在运行代码时收到“500 内部服务器错误”消息。

Javascript:

    var jsonEntry = {"timestamp":"2015/01/21 22:18:00","note":"hi there","tags":["one", "two"]};

    // send json converted object to php file via ajax
    $("#sendButton").click(function () {
        $.ajax({
            url: 'php/ajax.php',
            type: 'POST',
            dataType: 'JSON',
            data: jsonEntry,
        error :
                function(xhr, status, error) {
                alert(xhr.status);
                    alert(error);
                },
        success : 
                function(data) {
                        console.log('send success');
        }
        });
    });

来自“ajax.php:”的PHP代码

<?php
if(isset($_POST["data"])) {
$json = file_get_contents('php://input');
$obj = json_decode($json, true);

$timeStamp = $obj[timestamp]; //added semicolon here
$note = $obj[note];
$tags = $obj[tags];

//Connecting to a database
    //Connection info
    $hostname = "localhost";
    $username = "root";
    $password = "root";

    //Code to connect
    $dbhandle = mysql_connect($hostname, $username, $password)
        or die("Unable to connect to MySQL");
    echo "Connected to MySQL<br>";

    // Select database to work with
    $selected = mysql_select_db("notes", $dbhandle)
        or die("Could not select examples");

    //Execute SQL query and return records
    mysql_query("INSERT INTO notes (dateAndTime, noteBody, noteTags) VALUES ('$timestamp', '$note', '$tags')");

    // Close the connection
    mysql_close($dbhandle);
}
?>

更新: 我已经在 php 文件中需要的地方添加了分号,但现在出现错误 200,“SyntaxError: JSON Parse error: Unexpected EOF。”

【问题讨论】:

  • 请在此处添加您的 ajax.php 代码。
  • 如果你得到错误 500 总是因为 PHP 端有问题,在这种情况下是 Rob M 所说的分号。

标签: javascript php jquery mysql ajax


【解决方案1】:

我认为问题在于这里缺少分号:

$timeStamp = $obj[timestamp]

修复此错误后,您可以切换此行:

$json = file_get_contents('php://input');

到:

$json = $_POST['data'];

【讨论】:

  • 谢谢罗伯!但是,一旦我解决了这个问题,我就遇到了“200”错误。有什么想法吗?
  • 关闭,但仍然有这个:SyntaxError: JSON Parse error: Unexpected identifier "Connected"
  • 尝试抓取您传递给服务器的 JSON 并将其放入 jsonlint.com 以查看错误在哪里
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
  • 2014-03-09
  • 2019-09-23
  • 1970-01-01
  • 2018-09-05
  • 2019-02-08
相关资源
最近更新 更多