-1

I need the form.php code to run without refreshing the page. I'd like to use $.post. Here is my HTML code:

<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML Contact Form</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script src="form.js"></script>
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body>
<div class="form">
    <form method="POST" action="form.php" id="foo" name="foo">
        <h1>Contact Form</h1>
        <table>
            <tr>
                <td>
                    <label for="fname">Full Name:</label><br>
                    <input type="text" name="fname" placeholder="John Doe" id="">
                </td>
            </tr>
            <tr>
                <td>
                    <label for="email">Your Email:</label><br>
                    <input type="email" name="email" placeholder="example@gmail.com" id="">
                </td>
            </tr>
            <tr>
                <td>
                    <label for="msg">Your Message:</label><br>
                    <textarea name="msg" placeholder="Type your message..." id="" cols="30" rows="10"></textarea>
                </td>
            </tr>
            <tr>
                <td>
                    <input type="submit" name="submit" value="Send Message">
                </td>
            </tr>
        </table>
    </form>
</div>
<p id="target">
</p>
<script>
$(document).ready(function() {

$("#foo").submit(function(event){
        // Stop form from submitting normally
        event.preventDefault();
        
        /* Serialize the submitted form control values to be sent to the web server with the request */
        var formValues = $(this).serialize();
        
        // Send the form data using post
        $.post("form.php", formValues);

    $('#target').load('show.php');
});
});

</script>
</body>
</html>

Here is form.php

<?php
error_reporting(E_ALL);
log_errors(1);
display_errors(1);
    if(isset($_POST['submit']))
    {
        $name = $_POST['fname'];
        $email = $_POST['email'];
        $message = $_POST['msg'];
        
        //database details. You have created these details in the third step. Use your own.
        $host = "localhost";
        $username = "user";
        $password = "secret";
        $dbname = "form_entriesdb";

        //create connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
        $con = mysqli_connect($host, $username, $password, $dbname);
        //check connection if it is working or not
        if (!$con)
        {
            die("Connection failed!" . mysqli_connect_error());
        }
        //This below line is a code to Send form entries to database
        $sql = $con->prepare("INSERT INTO contactform_entries (name_fld, email_fld, msg_fld) VALUES (?, ?, ?)");
$sql->bind_param("sss", $name, $email, $message);
$sql->execute();

    
      //connection closed.
$sql->close();
 $con->close();

Sorry for the lorem ipsum. I need to add it to post. "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.

Neo
  • 51
  • 5
  • I don't see any issue with your code overall. I suspect the `.load()` is running before the `$.post()` is complete. You may want to perform the `.load()` in the success callback. – Twisty May 11 '22 at 22:34
  • How do I do that? $.post("form.php", formValues, $('#target').load('show.php'))? – Neo May 11 '22 at 22:41
  • Need to assign a anonymous function to the callback and then run the load within it. – Twisty May 11 '22 at 22:42

1 Answers1

1

Your current code will execute the .load() asynchronously with the $.post(). Consider the following.

$(function() {
  $("#foo").submit(function(event){
    // Stop form from submitting normally
    event.preventDefault();  
    /* Serialize the submitted form control values to be sent to the web server with the request */
    var formValues = $(this).serialize();
    // Send the form data using post
    $.post("form.php", formValues, function(response){
      $('#target').load('show.php');
    });
  });
});

This will execute the .load() in the success callback. This means that the load activity will occur after the POST is completed and the data is now in the Database.

Twisty
  • 30,304
  • 2
  • 26
  • 45
  • Posted Right before ending body. When I submit form I get a blank page. When I contain this in documentready, the data isn't submitted. – Neo May 12 '22 at 00:04
  • Now data is displayed but not inserted. – Neo May 12 '22 at 00:08
  • @Neo you may need to review your PHP Script then and test it to ensure data is being properly inserted to DB without error. – Twisty May 12 '22 at 14:15
  • My form.php file code is in my question. What’s wrong with it? – Neo May 12 '22 at 16:01
  • @Neo I am unable to address that question. There is no way for me to know how your DB is configured or if it is throwing any errors on query. – Twisty May 12 '22 at 19:44
  • Username is user. Database name is form_entriesdb. Table name is contactform_entries. Fields are id=int(20) PRIMARY KEY AUTO_INCREMENT, name_fld=varchar(20), email_fld=varchar(20), msg_fld=text. I also edited the php script in my question to include error checking. Please enter this table and all the fields so you can reproduce my setup. Thanks. – Neo May 12 '22 at 20:45
  • @Neo where would you suggest I do this? I tested the schema: http://sqlfiddle.com/#!9/6b01d4/1/0 – Twisty May 12 '22 at 21:54
  • I'm looking at this question. https://stackoverflow.com/questions/31822543/connect-to-mysql-server-from-php-and-jquery. The only problem is I don't know how to include multiple parameters in the dataString Javascript variable. – Neo May 12 '22 at 22:05