简体   繁体   中英

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.

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

这是文件结构

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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