-1

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('');
    });
}

1 Answers1

0

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

});
BATMAN_2008
  • 2,788
  • 3
  • 31
  • 98
  • Thank you very much for the answer, I added the line of code you told me. I think maybe I have another problem, after I added the line of code you told me, there was a refresh as before. Maybe the code I entered does not reach this function - I do not understand why. –  Jul 19 '20 at 14:06
  • @masterHaham Can you `console.log` in this function and see if it's being triggered when you submit the form? Edited the answer it should be after the submission of the form. Not sure why you have 2 submit to the same form. – BATMAN_2008 Jul 19 '20 at 14:09
  • 1
    Typo: it's `event.preventDefault()`. Notice the capital 'D' – Rob Moll Jul 19 '20 at 14:10
  • Thanks for the help, I followed the code you told me. And I added console.log. I'm new to php and sql - so I'm not sure. The error I get is "GET http://localhost/final%20project/script/jquery-1.8.1.min.js net::ERR_ABORTED 404 (Not Found)" –  Jul 19 '20 at 14:17
  • Based on the 404 error, you should confirm the paths to your ` – Rob Moll Jul 19 '20 at 14:21
  • I am doubting if your PHP is being called or not. I have added a code to my answer try the second function and comment the function `$("#submit-insert").click`. As it is doing the same thing. Maybe add a console to '$('#form-insert').' to see if it's being triggered after the form submit. If everything works then after inserting to DB you should get an alert. Also, from PHP you should return the control to again AJAX. – BATMAN_2008 Jul 19 '20 at 14:28
  • Thanks for the comment, I used a link that is incorrect - you're right. I'm still new to the subject. –  Jul 19 '20 at 14:30
  • Np :) everyone is new. I hope its working as expected now. – BATMAN_2008 Jul 19 '20 at 14:31