0

I am curious to know if it's possible that I can have a div reload like a window does. The reason for this is I have a forum but I don't want a full page reload after four is completed. So I was wondering if just the elements that are in that div or forum section could do a background reload or just load by them self when the submit button is pressed.

This is in a file called forum where the information gets typed in. I want it to not reload the page but stay on that forum and still send the data to the database.

<html>
    <body>
    
        <form action="demo.php" method="post" />
            <p>Input 1: <input type="text" name="firstname" /></p>
            <input type="submit" value="Submit" />
        </form>

        <div id = "load_results"></div>
    </body>
</html>

This is sending the information to the database but I want it to be done discreetly.

<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$value = $_POST['firstname'];

$sql = "INSERT INTO MyGuests (firstname) VALUES ('$value')";


if ($conn->query($sql) === TRUE) {
    echo "<a href=https://twitter.com/angela_bradley>My Twitter</a>";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>
wogsland
  • 9,106
  • 19
  • 57
  • 93
Jack
  • 77
  • 15

1 Answers1

0

Yes, there is a way. It is called AJAX - but, not to worry, it's pretty simple.

Your code will look something like this:

HTML:

<form action="demo.php" method="post" />
    <p>Input 1: <input type="text" name="firstname" /></p>
    <input type="submit" value="Submit" />
</form>

js/jQuery:

$(function(){
    $('form').submit(function(evt){
    //next line stops form submission from sending you to `demo.php`
    evt.preventDefault(); //evt stands for "event" - can be anything. I use e.preventDefault()
    var fn = $('[name=firstname]').val();
    $.ajax({
        type: 'post',
         url: 'demo.php', //send data ONLY to demo.php -- page stays as it is
        data: 'first='+fn,
        success: function(d){
            if (d.length) alert(d);
        }
    }); //END ajax
}); //END document.ready

demo.php

<?php
    $fn = $_POST['fn'];
    //Do your database insert here

    //If you wish, you can return some data to the AJAX's success function:
    echo 'You submitted: ' .$fn;

Here are some posts with simple AJAX examples:

AJAX request callback using jQuery

Community
  • 1
  • 1
cssyphus
  • 37,875
  • 18
  • 96
  • 111