添加到数据库时使用 AJAX 防止刷新

我是一名计算机科学专业的学生,大二。为了独立学习,我决定创建一个使用 SQL、PHP、JS、AJAX、BOOTSTRAP 等技术的网站。我正在尝试向数据库添加内容,我使用 AJAX - 我不想刷新页面,所以我使用 AJAX。我设法将内容添加到数据库 - 但页面刷新。我尝试使用 jquery - 当我添加内容时 - 来防止刷新。该代码有效 - 但仍然需要刷新。

访问数据库的代码:

<?php


$DBConInfo = [

    'server'   => '127.0.0.1',

    'username' => 'root',

    'password' => '',

    'name'     => 'test',

];

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

$conn = new mysqli($DBConInfo['server'],$DBConInfo['username'], $DBConInfo['password'],$DBConInfo['name']);


if ($conn->connect_error) {

    die("Connection failed: " . $conn->connect_error);

}

echo "Connected successfully";


// php code to Insert data into mysql database from input text

if(isset($_POST['insert']))

{

    $hostname = "127.0.0.1";

    $username = "root";

    $password = "";

    $databaseName = "test";


    // get values form input text and number


    $name = $_POST['name'];

    $description = $_POST['description'];

    $price = $_POST['price'];

    $picture = $_POST['picture'];


// mysql query to insert data


    $query = "INSERT INTO `product`(`name`,`description`, `price`, `picture`) VALUES ('$name','$description','$price','$picture')";


    $result = mysqli_query($conn,$query);


// check if mysql query successful


    if($result) {

        echo 'Data Inserted';

    }

    else{

        echo 'Data Not Inserted';

        var_dump($conn->error);

    }


    //mysqli_free_result($result);

    mysqli_close($conn);

}


?>


<!DOCTYPE html>


<html>


<head>


    <title> PHP INSERT DATA </title>


    <meta charset="UTF-8">


    <meta name="viewport" content="width=device-width, initial-scale=1.0">


</head>


慕姐8265434
浏览 81回答 1
1回答

慕的地10843

提交表格后,您必须使用event.preventDefault()&nbsp; &nbsp;$("#submit-insert").click( function(event) {&nbsp; &nbsp; &nbsp; &nbsp; event.preventDefault();&nbsp; &nbsp; });$('#form-insert').on('submit', function (event) {&nbsp; &nbsp; event.preventDefault();&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; &nbsp; type&nbsp; &nbsp; : 'post',&nbsp; &nbsp; &nbsp; &nbsp; url&nbsp; &nbsp; &nbsp;: 'NameOfPHPFile.php',&nbsp; &nbsp; &nbsp; &nbsp; data&nbsp; &nbsp; : $('#form-insert').serialize(),&nbsp; &nbsp; &nbsp; &nbsp; success : function () {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert('form was submitted');&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });});
打开App,查看更多内容
随时随地看视频慕课网APP