dongpo1846 2018-04-29 14:13
浏览 140
已采纳

来自Ajax jQuery数组的未定义的POST索引

Im trying to insert the info from the array into my database. The problem im having is first of all that i am getting undefined index of $_POST['Person'], $_POST['Color_name'], $_POST['Opinion'] from the php.

The second issue is that i would like to use dataType: "json"; in my Ajax jQuery but my data is not reaching the php file if i use it.

What i have tried so far is to json stringify my return data in the get_data function without any success. I also tried decoding the data in the php but since it's getting undefined index i am guessing there has to be some work done in the jQuery.

This is the array the get_data() function returns

{Person: "James", Color_name: "blue", Opinion: "Looks good"}
{Person: "James", Color_name: "green", Opinion: "Looks ok"}
{Person: "Rebecka", Color_name: "blue", Opinion: "Looks bad"}
{Person: "Rebecka", Color_name: "black", Opinion: "Looks very bad"}

HTML

<div>
  <ul data-person="James">
    <li data-color_opinion="blue">Looks good</li>
    <li data-color_opinion="green">Looks ok</li>
  </ul>
  <ul data-person="Rebecka">
    <li data-color_opinion="blue">Looks bad</li>
    <li data-color_opinion="black">Looks very bad</li>
  </ul>
</div>

JQuery

function get_data() {
  var data = [];
  $.each($('ul'), function(i, el) {
    $.each($(el).find("[data-color_opinion]"), function(j, child) {
      let person = $(el).data('person');
      let color_name = $(child).data('color_opinion');
      let opinion = $(child).text();
      data.push({ Person: person, ColorName: color_name, Opinion: opinion });
    });
  });
  return data;
};
console.log(get_data())

$.ajax({
type: "POST",
url:'colors.php',
data:get_data´(),
success: function(data) {
  console.log(data);
}
});
});

PHP

<?php

$servername = "servername";
$username = "username";
$password = "password";

$person = $_POST['Person'];
$color_name = $_POST['Color_name'];
$opinion = $_POST['Opinion'];


try {
$db = new PDO("mysql:host=$servername;dbname=DB_NAME", $username, $password);
 $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
 $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);


 $sql = "INSERT INTO colors (person, color_name, opinion)
     VALUES ($person, $color_name, $opinion)";

$db->exec($sql);
echo "New records created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$db = null;

 ?>
  • 写回答

2条回答 默认 最新

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥15 香农解码的代码问题,无法输出解码结果
      • ¥15 内网同一网段设备和wifi隔离
      • ¥15 Python操作注册表
      • ¥45 入门级别的一段VUE前端拍照像后端发送请求的代码,帮排错
      • ¥15 anaconda打开spyder后一直闪退,不知道怎么办
      • ¥15 解决迷宫问题中无法运行的问题
      • ¥15 关于aspnetcore中使用mqttnet库的entire
      • ¥15 关于#python#的问题,请各位专家解答!
      • ¥100 关于远控软件的两个问题
      • ¥15 基于STM32的AD8232心电采集装置设计