Skip to content
Advertisement

Use AJAX to prevent refresh when adding to a database

I’m a computer science student, in my sophomore year. For independent learning I decided to create a website in technologies like: SQL, PHP, JS, AJAX, BOOTSTRAP. I’m trying to add content to the database, I use AJAX – I do not want to refresh the page, so I use AJAX. I manage to add the content to a database – but the page refreshes. I tried to use jquery – when I add content – to prevent refresh. The code works – but there is still a refresh.

The code that accesses the database:

<?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>

<body>
<form id="form-insert" action="" method="post">

    <!--<input type="text" name="id" required placeholder="id"><br><br>-->

    <input type="text" name="name" required placeholder="Name"><br><br>

    <input type="text" name="description" required placeholder="description" min="10" max="100"><br><br>

    <input type="text" name="price" required placeholder="price"><br><br>

    <input type="text" name="picture" required placeholder="picture" min="10" max="100"><br><br>

    <input id="submit-insert" type="submit" name="insert" value="Add Data To Database">

</form>

<span id="result"></span>

<script src="script/jquery-1.8.1.min.js" type="text/javascript"></script>
<script src ="js/DBscript.js" type="text/javascript"></script>
</body>

</html>

Using ajax – to prevent refresh:

$("#submit-insert").click( function() {
    $.post( $("#form-insert").attr("action"),
        $("#form-insert :input").serializeArray(),
        function(info){ $("#result").html(info);
        });
    //clearInput();
});

$("#form-insert").submit( function() {
    return false;
});

function clearInput() {
    $("#form-insert :input").each( function() {
        $(this).val('');
    });
}

Advertisement

Answer

After submitting the form you have to use event.preventDefault()

   $("#submit-insert").click( function(event) {
        event.preventDefault();
    });


$('#form-insert').on('submit', function (event) {
    event.preventDefault();
    
    $.ajax({
        type    : 'post',
        url     : 'NameOfPHPFile.php',
        data    : $('#form-insert').serialize(),
        success : function () {
          alert('form was submitted');
        }
    });

});
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement