weixin_33701294 2019-03-20 14:49 采纳率: 0%
浏览 42

Ajax POST调用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.

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

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

JS FILE

$(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

$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

Here is the file structure

I am currently working on my happypath hence why I don't validate the input to the database.

All help and tips are welcome, thanks in advance :D

Edit: I managed to solve the problem, it was like alot of people suggested that the data was being redirected in admin.php. so I just moved my php function there and now it works (atleast for my happypath). Thanks alot to all who took their time to help :D

  • 写回答

1条回答 默认 最新

  • 三生石@ 2019-03-20 14:52
    关注

    You need to pass $data to the insertToDB() function. You currently reference it like this:

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

    You need to do this:

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

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能