Help needed for submitting form data with Javascript

I am a new coder with a little bit of understanding of PHP and MySQL, but no exposure to Javascript.

I am planning to build out a database that will be used for collection tracking. The collections are part of pre-defined sets of items. The user will select a set to manage, and will be able to enter the quantity they have for each item in the set. Once the user enters the quantities, I then want to add those to the database by submitting the form data with Javascript.

I have been researching the Javascript that I need to use for this, and I thought I had found everything I needed to make my quick test example work, but it is not working.

Could someone please tell me what I need to do, to get this to work:

<?php
echo "Collection Tracking Enabled</br></br>";

// Variables
$location_sw = 1;   //Testing - set as 1 so that location column is displayed
$quantity = !empty($_POST["quantity"]) ? $_POST["quantity"] : null;
$offering = !empty($_POST["offering"]) ? $_POST["offering"] : null;
$trade_sw = !empty($_POST["trade_sw"]) ? $_POST["trade_sw"] : null;
$sell_sw = !empty($_POST["sell_sw"]) ? $_POST["sell_sw"] : null;
$location = !empty($_POST["location"]) ? $_POST["location"] : null;
$notes = !empty($_POST["notes"]) ? $_POST["notes"] : null;
$submitted = !empty($_POST["submitted"]) ? $_POST["submitted"] : null;

// Testing - Display Variables that were passed from the form submit
if (!empty($submitted)) {
    echo "passing new data into database" . "</br>";
    echo "quantity: " . $quantity . "</br>";
    echo "offering: " . $offering . "</br>";
    echo "trade_sw: " . $trade_sw . "</br>";
    echo "sell_sw: " . $sell_sw . "</br>";
    echo "location: " . $location . "</br>";
    echo "notes: " . $notes . "</br>";
}
?>

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Collections Testing</title>
        <meta name="description" content="MinisGallery Collections Tracking Test">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <script>
            function submitForm(){
                var form = document.getElementById("myForm");
                var formData = new FormData(form);
                var xhr = new XMLHttpRequest();
                xhr.open("POST", "collectionsTest1.php", true);
                xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                xhr.send(formData);
            }
        </script>
    </head>
    <body>
        <?php if (empty($submitted)) { ?>
        <form id="myForm" method="post">
            <label for="quantity">Quantity</label>
            <input type="number" id="quantity" name="quantity"></br></br>
            <label for="offering">Sale/Trade</label>
            <input type="number" id="offering" name="offering"></br></br>
            <label for="quantity">Trade</label>
            <input type="checkbox" id="trade_sw" name="trade_sw"></br></br>
            <label for="quantity">Sell</label>
            <input type="checkbox" id="sell_sw" name="sell_sw"></br></br>
            <?php
            if ($location_sw == 1) {
                ?>
                <label for="location">Location</label>
                <input type="text" id="location" name="location"></br></br>
                <?php
            }
            ?>
            <label for="notes">Notes</label>
            <input type="text" id="notes" name="notes"></br></br>
            <input type="hidden" id="submitted" name="submitted" value="complete">         
            <button type="button" onclick="submitForm()">Submit</button>
        </form>
        <?php }
        ?>

    </body>
</html>

Personally fetch is much easier in my opinion to implement. I will give you an example of my scripts.

The following grabs the the data from my form, sends it to PHP and then waits for a response.

        // Add an event listener to the edit form's submit event
        editForm.addEventListener("submit", async function (event) {
            // Prevent the default form submit behavior
            event.preventDefault();

            // Create a FormData object from the edit form
            const formData = new FormData(editForm);
            //console.log("form data", formData);
            // Send a POST request to the edit_update_blog.php endpoint with the form data
            const response = await fetch("edit_update_blog.php", {
                method: "POST",
                body: formData,
            });

            // Check if the request was successful
            if (response.ok) {
                const result = await response.json();
                console.log(result);
                // If the response has a "success" property and its value is true, clear the form
                if (result.success) {
                    resultInput.value = '';          // Clear the current value of the input field
                    resultInput.placeholder = "New Search"; // Set the placeholder to `New Search`
                    image_for_edit_record.src = "";
                    image_for_edit_record.alt = "";
                    editForm.reset(); // Updated line: call reset() method on the form element
                }
            } else {
                console.error(
                    "Error submitting the form:",
                    response.status,
                    response.statusText
                );
                // Handle error response
            }
        });

Then it responds back after updating the form and here is the PHP

<?php
// edit_update_blog.php

header('Content-Type: application/json');
require_once 'assets/config/config.php';
require_once "vendor/autoload.php";

use PhotoTech\ErrorHandler;
use PhotoTech\Database;
use PhotoTech\LoginRepository as Login;
use Intervention\Image\ImageManagerStatic as Image;

$errorHandler = new ErrorHandler();

// Register the exception handler method
set_exception_handler([$errorHandler, 'handleException']);

$database = new Database();
$pdo = $database->createPDO();
$login = new Login($pdo);

try {
    // Check if the required form data is provided
    if (!isset($_POST['id']) || !isset($_POST['heading']) || !isset($_POST['content'])) {
        throw new Exception("Missing required form data.");
    }

    // Get form data
    $id = (int) $_POST['id'];
    $category = $_POST['category'];
    $heading= $_POST['heading'];
    $content = $_POST['content'];

    // Handle image upload
    if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
        $image = $_FILES['image'];
        $destinationDirectory = 'assets/image_path/';
        $saveDirectory = 'assets/image_path/';

        $destinationFilename = time() . '_' . str_replace(' ', '_', basename($image['name']));
        $destinationPath = $destinationDirectory . $destinationFilename;
        $target_file = $destinationPath;

        // Load the image
        $loadedImage = Image::make($image['tmp_name']);

        // Resize the image
        $loadedImage->resize(2048, 1365, function ($constraint) {
            $constraint->aspectRatio();
            $constraint->upsize();
        });

        // Save the new image
        $loadedImage->save($destinationPath, 100);

        // Create a thumbnail
        $new_width = 205;
        $new_height = 137;

        // Load the image with Intervention Image
        $image = Image::make($destinationPath);

        // Resize the image while maintaining the aspect ratio
        $image->resize($new_width, $new_height, function ($constraint) {
            $constraint->aspectRatio();
            $constraint->upsize();
        });

        // Save the thumbnail
        $thumb_path = 'assets/thumb_path/thumb-gallery-' . time() . '-205x137' . '.' . pathinfo($destinationFilename, PATHINFO_EXTENSION);
        $image->save($thumb_path, 100);

        // Retrieve the current image file path from the database
        $current_image_query = "SELECT image_path FROM gallery WHERE id = :id";
        $current_image_stmt = $pdo->prepare($current_image_query);
        $current_image_stmt->bindParam(':id', $id, PDO::PARAM_INT);
        $current_image_stmt->execute();
        $current_image_row = $current_image_stmt->fetch(PDO::FETCH_ASSOC);
        $current_image_path = $current_image_row['image_path'];

        // Delete the old image if it exists
        $current_image_abs_path = $_SERVER['DOCUMENT_ROOT'] . $current_image_path;
        if (file_exists($current_image_abs_path)) {
            unlink($current_image_abs_path);
        }

        // Prepare the SQL query with placeholders
        $sql = "UPDATE gallery SET category = :category, heading = :heading, content = :content, image_path = :image_path, thumb_path = :thumb_path WHERE id = :id";
        $stmt = $pdo->prepare($sql);

        // Bind the values to the placeholders
        $savePath = $saveDirectory . $destinationFilename;
        $stmt->bindParam(':image_path', $savePath);
        $stmt->bindParam(':thumb_path', $thumb_path);

    } else {
        // Prepare the SQL query with placeholders
        $sql = "UPDATE gallery SET category = :category, heading = :heading, content = :content WHERE id = :id";
        $stmt = $pdo->prepare($sql);
    }

    // Bind the values to the placeholders
    $stmt->bindParam(':id', $id, PDO::PARAM_INT);
    $stmt->bindParam(':category', $category);
    $stmt->bindParam(':heading', $heading);
    $stmt->bindParam(':content', $content);

    // Execute the prepared statement
    $stmt->execute();

    // Check if the update was successful
    if ($stmt->rowCount() > 0) {
        echo json_encode(['success' => true, 'message' => 'Record updated successfully.']);
    } else {
        echo json_encode(['success' => false, 'message' => 'No record updated.']);
    }
} catch (PDOException $e) {
    echo json_encode(['PDO error' => $e->getMessage()]);
} catch (Exception $e) {
    echo json_encode(['error' => $e->getMessage()]);
}

I would suggest reading about Fetch or even finding a tutorial on it. It is pretty easy to learn. BTW - never echo out error messages to people. This is my own private website where I have to login to access this page, plus this is on my local server.

Hi @orclord1, with not working you mean the form is still getting submitted the usual way? You’ll need to prevent the default event here like so (I’d also suggest to use addEventListener() rather than inline JS):

<form id="myForm">
  ...
  <button>Submit</button>
</form>

<script>
const form = document.getElementById('myForm')

form.addEventListener('submit', function (event) {
  event.preventDefault()
  // Now the form won't get submitted and you
  // can send the form data using AJAX instead
  const xhr = new XMLHttpReqest()
  // ...
})
</script>
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.