too long

I apologize in advance if this is a duplicate, yet I searched stackoverflow and found nothing on this subject. In my base.html, I have a form like this:

<form method="post" action="../php/base.php">
   <input type="hidden" name="addToDB" value="addToDB" />
   <input type="text" id="name" name="name" placeholder="Enter name">
   <input type="text" id="address" name="address" placeholder="Enter address">
   <button type="submit">Submit</button>
</form>

Note a dummy input element; it will be used in PHP to target this form (is this a good practice?) base.php has the following:

if (isset($_POST['addToDB'])) {
    create_tables(); // creates tables in DB
    addToDB(); // inserts content to DB
}

function addToDB() {
try {
    // open DB connection
    $db = new PDO("sqlite:../db/mydb.sqlite");

    $name= $_POST['name'];
    $address= $_POST['address'];

    $db->exec("INSERT INTO Person (P_Name, P_Address) VALUES ('$name', '$address');");

    // The following needs to be redirected back to base.html:
    print "<table border=1>";
    print "<tr><td>Name</td><td>Address</td></tr>";
    $result = $db->query('SELECT * FROM Person');
    foreach($result as $row)
    {
        print "<tr><td>".$row['P_Name']."</td>";
        print "<td>".$row['P_Address']."</td></tr>";
    }
    print "</table>";

}catch(PDOException $e)
  {
      echo $e->getMessage();
  }
}

When submit button is clicked, the file base.php opens and displays a table. Instead, I want the script in base.php be executed and the output sent back to the base.html, which is where it will be displayed (somewhere inside content div).

  • I understand that I probably need to use AJAX, but I cannot figure out how to call a specific function in the external PHP file and redirect its return value (presumably a string with HTML markup in it, to construct a table) back to the HTML file (base.html)
  • I use SQLite for data storage; the DB is created using create_tables();
  • I am a novice in PHP, and any input/suggestions would be highly, highly appreciated.

THANK YOU

You can try the following with HTML, jQuery AJAX, and PHP:

HTML:

<form method="post"  id="formid">
   <input type="hidden" name="addToDB" value="addToDB" />
   <input type="text" id="name" name="name" placeholder="Enter name">
   <input type="text" id="address" name="address" placeholder="Enter address">
   <!-- take simple button -->
   <button type="button" id="submit">Submit</button>
</form>
    <div id="response"></div> 

JavaScript:

<script type="text/javascript">
  $(document).ready(function(){
      //on click of submit button
      $("#submit").click(function(){
          $.ajax({
              url:"../php/base.php",
                  data:{
                          addToDB:"addToDB",
                          name:$("#name").val(),
                          address:$("#address").val()
                       },
                          type:"POST",
                          success:function(res){
                          $("#response").html(res);
                       }
             });
       });
 });
</script>

No changes will be made to your PHP. Best of luck with this one.

You can change your base.html file as below:

<form method="post" action="../php/base.php" id="formid" onsubmit='return false;'>
       <input type="hidden" name="addToDB" value="addToDB" />
       <input type="text" id="name" name="name" placeholder="Enter name">
       <input type="text" id="address" name="address" placeholder="Enter address">
       <button type="submit" id="submit">Submit</button>
 </form>
 <div id="display"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("#submit").on("click",function(e){
        e.preventDefault();
        var formdata=$("#formid").serialize();
        var url=$("#formid").attr("action");

        $.post(url,formdata,function(data){
         $("#display").html(data);   
        },'json');

    });

});
</script>

It may help for you.

I want the ... output sent back to the base.html

Then why don't you processed in it.

form.php

<?php

//  you can save this two functions in a file 'DBhelper.php';
//  then you can 'require(DBhelper.php') here to make this file a little cleaner
//  function create_tables(){
//     put your codes here...
//  }; 
function addToDBandGetAllUsers($name,$address) {
try {
    // open DB connection
    $db = new PDO("sqlite:../db/mydb.sqlite");
    $db->exec("INSERT INTO Person (P_Name, P_Address) VALUES ('$name', '$address');");

    //The following needs to be redirected back to base.html:
    $result = $db->query('SELECT * FROM Person');
    // this data is for test, even the 1 + 1 solution, I will test it, I don't want to post codes in community with errors....
    // $result = array(
    //  array('P_Name' => 'John','P_Address' => 'Foobar'),
    //  array('P_Name' => 'Alex','P_Address' => 'Qux')
    //  );
    // array_push($result, array('P_Name' => $name,'P_Address' => $address));
    return $result;
}catch(PDOException $e)
  {
     echo $e->getMessage();
  }
}
// if the $_POST['name'] is not empty, we will update db
// this is just a basic validation, if we use isset() instead of empty(),
// the form can be submitted with a empty value;
if (! empty($_POST['name']) && ! empty($_POST['address']) ){
    create_tables(); // creates tables in DB

    // I change the the function name , since this guy do a lot of things.... 
    $result = addToDBandGetAllUsers($_POST['name'],$_POST['address']);
} else{
    echo 'Please fill the form.';
} 


?>

<!DOCTYPE html>
<html>
<head>
    <title>form</title>
</head>
<body>
// if we got $result, that means the form has been submitted, so we can display the table;
<?php if (isset($result)) :
    echo '<h1>All users:</h1>';
    print "<table border=1>";
    print "<tr><td>Name</td><td>Address</td></tr>";
    foreach($result as $row)
    {
        print "<tr><td>".$row['P_Name']."</td>";
        print "<td>".$row['P_Address']."</td></tr>";
    }
    print "</table>";
    echo '<hr>';
    endif;
?>
<form method="post" action="form.php">
   <input type="hidden" name="addToDB" value="addToDB" />
   <input type="text" id="name" name="name" placeholder="Enter name">
   <input type="text" id="address" name="address" placeholder="Enter address">
   <button type="submit">Submit</button>
</form>
</body>
</html>

the 'action' of the form element is its self.