代码之家  ›  专栏  ›  技术社区  ›  Geoff_S

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

  •  -2
  • Geoff_S  · 技术社区  · 6 年前

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

    它目前可以插入(我可以在数据库中看到),但我正在使用 alert 为了测试它是否获得了插入的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>
    

    AdPGA.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 回复  |  直到 6 年前
        1
  •  1
  •   Mohammad Raheem    6 年前

    尝试返回上次插入的数据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;
    }
    
        2
  •  0
  •   zani    6 年前

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