Ajax,从函数内部检索插入的ID

时间:2018-07-24 13:04:07

标签: php jquery

我正在尝试使用Ajax将表单数据插入数据库并返回该插入的ID。

它目前可以插入为止(我可以在数据库中看到它),但是我正在使用alert来测试它是否正在获取插入的ID,它只是说未定义。

检索ID是否出错?

<script type="text/javascript">
  $(document).ready(function(){
    $("#submitForm").click(function(){

      var string = $('#pageForm').serialize();

      // AJAX Code To Submit Form.
      $.ajax({
        type: "POST",
        url: "addPage.php",
        data: string,
        cache: false,
        success: function(result){
          alert(result.id);//this will alert you the last_id

        }
      });

    });

  });
</script>

addPage.php

$title = $_POST['addTitle'];
$page_type = $_POST['pageType'];
$display_id = $_POST['displayId'];
$duration = $_POST['durationSet'];

$addpage = "
    INSERT INTO pages (title, page_type_id, display_id, duration)
    VALUES ('$title','$page_type','$display_id','$duration');
";

if ($mysqlConn->query($addpage) === TRUE) {
$last_id = $mysqlConn->insert_id;
echo json_encode(['id'=>$last_id]);
echo "New record created successfully" . $last_id;
} else {
    echo "Error: " . $addpage . "<br>" . $mysqlConn->error;
}

2 个答案:

答案 0 :(得分:1)

尝试返回最后插入的数据ID

$title = $_POST['addTitle'];
$page_type = $_POST['pageType'];
$display_id = $_POST['displayId'];
$duration = $_POST['durationSet'];

$addpage = "
    INSERT INTO pages (title, page_type_id, display_id, duration)
    VALUES ('$title','$page_type','$display_id','$duration');
";

if ($mysqlConn->query($addpage) === TRUE) {
$last_id = $mysqlConn->insert_id;
$data = json_encode(['id'=>$last_id]);
echo "New record created successfully" . $data ;
} else {
    echo "Error: " . $addpage . "<br>" . $mysqlConn->error;
}

答案 1 :(得分:0)

https://www.w3schools.com/PHP/php_mysql_insert_lastid.asp

请先搜索,然后再提出问题

if ($mysqlConn->query($addpage) === TRUE) {
    $last_id = $mysqlConn->insert_id;
    echo "New record created successfully" . $last_id;
} else {
    echo "Error: " . $addpage . "<br>" . $mysqlConn->error;
}