简体   繁体   English

对 PHP 的 Ajax POST 调用

[英]Ajax POST call to PHP

I'm trying to send a string from my JS file to my PHP file with an AJAX POST call and then insert that string into my Wordpress database.我正在尝试使用 AJAX POST 调用将字符串从我的 JS 文件发送到我的 PHP 文件,然后将该字符串插入到我的 Wordpress 数据库中。

I am able to send the string however I get this error message:我可以发送字符串但是我收到此错误消息:

Notice: Undefined index: data in C:\\Bitnami\\wordpress-5.0.3-2\\apps\\wordpress\\htdocs\\wp-content\\plugins\\Kalkylator\\templates\\create.php on line 81注意:未定义索引:数据在 C:\\Bitnami\\wordpress-5.0.3-2\\apps\\wordpress\\htdocs\\wp-content\\plugins\\Kalkalator\\templates\\create.php 中的第 81 行

line 81 is: $data = $_POST['data'];第 81 行是: $data = $_POST['data'];

JS FILE JS文件

$(document).ready(function() {
  var testingString = "hello people";
  $.ajax({
    url: "admin.php?page=jvformbuilder_create",
    method: "POST",
    data: { 'data': testingString }, 
    success: function(result) {
      console.log("result: " + result);
    },
    error: function(error) {
      console.log("error: " + error);
    }
  });
});

PHP FILE PHP文件

$data = $_POST['data'];   
echo $data; 
insertToDB($data);    

function insertToDB($data)
{
  $db = new mysqli('localhost', 'root', 'password', 'bitnami_wordpress');

  if ($db->connect_errno > 0)
  { 
    die('Unable to connect to database [' . $db->connect_error . ']');
  }

  // Attempt insert query to database.
  $testing = "INSERT INTO wp_test (value) VALUES ('$data')";

  mysqli_close($db);
} 

Here is the file structure这是文件结构

这是文件结构

I am currently working on my happypath hence why I don't validate the input to the database.我目前正在处理我的happypath,因此为什么我不验证数据库的输入。

All help and tips are welcome, thanks in advance :D欢迎所有帮助和提示,提前致谢:D

Edit: I managed to solve the problem, it was like alot of people suggested that the data was being redirected in admin.php.编辑:我设法解决了这个问题,就像很多人建议在 admin.php 中重定向数据一样。 so I just moved my php function there and now it works (atleast for my happypath).所以我只是将我的 php 函数移到那里,现在它可以工作了(至少对于我的happypath)。 Thanks alot to all who took their time to help :D非常感谢所有花时间提供帮助的人:D

You need to pass $data to the insertToDB() function.您需要将$data传递给insertToDB()函数。 You currently reference it like this:您目前像这样引用它:

$data = $_POST['data'];   
echo $data; 
insertToDB ();

You need to do this:你需要这样做:

$data = $_POST['data'];   
echo $data; 
insertToDB ($data);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM