Form data submission problem

Website URL

(My form data is not submitted, in network, I found some problem, )

Error Message

(script.js:10 GET https://errors.infinityfree.net/errors/404/ net::ERR_FAILED 500
(anonymous) @ script.js:10
script.js:24 Error saving form data: TypeError: Failed to fetch
at HTMLFormElement. (script.js:10:30)
errors.infinityfree GET errors.infinityfree. net/errors/404/ 404)

Other Information

Can anyone please help me
script.js

document.addEventListener("DOMContentLoaded", function () {
  const form = document.querySelector("form");
  const toastContainer = document.getElementById("toast-container1");
  const toastMessage = document.getElementById("formToast-message");

  form.addEventListener("submit", async function (event) {
    event.preventDefault();
    const formData = new FormData(form);
    try {
      const response = await fetch("/server.php", {
        method: "POST",
        body: formData, // Send form data directly, no need for JSON.stringify
      });
      if (response.ok) {
        toastContainer.classList.add("show");
        setTimeout(() => {
          toastContainer.classList.remove("show");
        }, 3000);
        form.reset();
      } else {
        console.error("Error saving form data");
      }
    } catch (err) {
      console.error("Error saving form data:", err);
    }
  });
});

server.php

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Parse the JSON data from the request body.
    $data = json_decode(file_get_contents("php://input"));

    // Extract form data.
    $name = $data->name;
    $email = $data->email;
    $contactNumber = $data->contactNumber;
    $feedbackText = $data->feedbackText;

    // Prepare and execute the SQL query.
    $sql = "INSERT INTO feedbackform (name, email, contactNumber, feedbackText, createdAt) VALUES (?, ?, ?, ?, NOW())";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ssss", $name, $email, $contactNumber, $feedbackText);


    if ($stmt->execute()) {
        // Form data saved successfully.
        http_response_code(200);
        echo "Form data saved successfully";
    } else {
        // Error saving form data.
        http_response_code(500);
        echo "Internal Server Error";
    }

form.htlm

<form action="/submit-form" method="post" style="font-size: 12px;">

Hi, there is some code here which demonstrates how to send mail via SMTP

Be sure to use composer to install all necessary dependencies before uploading to your site. Using the default PHP mail option won’t work for InfinityFree sites.

If you are just trying to insert data into your database, this is your error

(script.js:10 GET https://errors.infinityfree.net/errors/404/ net::ERR_FAILED 500
(anonymous) @ script.js:10
script.js:24 Error saving form data: TypeError: Failed to fetch
at HTMLFormElement. (script.js:10:30)
errors.infinityfree GET errors.infinityfree. net/errors/404/ 404)

Try to comment out lines of code (lines 10 or 24) trying to fetch the 404 page and see if db insert works? Bypass the error handling for now to see if the db insert works first.

This doesn’t seem to apply here, as the data are just inserted into a database.

@Washimul can you format your code properly (the first part isn’t formatted well and it’s hard to read) and show what the error you’re getting is?

If it’s a 500 error, this article may help (to see why you’re getting a 500 error):

3 Likes

Hi @Washimul,

Sure, let’s take a look at your code.

I can see that you have attempted to send formData to server.php using POST as native FormData.

const formData = new FormData(form);
try {
	const response = await fetch("/server.php", {
		method: "POST",
		body: formData, // Send form data directly, no need for JSON.stringify
	});

However, in your server.php, the code is expecting a JSON string as the request body, meaning the type does not match the code expectation.

$data = json_decode(file_get_contents("php://input"));

So we need to work on some changes here:

  1. Format your code using an IDE so it fixes quotation issues. (Recommended: VScode)
  2. Assuming the form in your HTML has the appropriate names, send the form data as a JSON string, the comment is not correct there so let’s get rid of that as well.
const response = await fetch("/server.php", {
	method: "POST",
	headers: {
		"content-type": "application/json",
	},
	body: JSON.stringify(formData),
});
  1. Not sure if it’s a copying issue or syntax actually has a missing }, you might want to adjust the output part as follows in the PHP. (notice the location of the quotes and code blocks.
<?php

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Parse the JSON data from the request body.
    $data = json_decode(file_get_contents('php://input'));
   
    // .......
    
    if ($statement->execute()) {
        http_response_code(200);
        echo "Form data saved successfully";
        exit();
    }
}

http_response_code(400); // bad request
echo "An error has occurred with your request, please try again.";

It didn’t work previously because there are multiple ways of sending data to the server. Both the server and the client need to talk in the same language to make things work. Normally POST requests do not become JSON by magic, they have to be JSON.stringify. Alternatively, you can simply use $_POST to get the values as array values if the data is sent natively.

The rule of thumb of choosing the appropriate sending method depends on whether you reload your webpage after sending. If you intend to do AJAX and display just a message box, definitely do the JSON way, otherwise, you can simply $_POST them.

This should solve all the mysteries you’ve asked above. Let us know if you have more questions. :+1:t2:

Cheers,
-chiucs123


Completed files for reference.

script.js
document.addEventListener("DOMContentLoaded", function () {
	const form = document.querySelector("form");
	const toastContainer = document.getElementById("toast-container1");
	const toastMessage = document.getElementById("formToast-message");

	form.addEventListener("submit", async function (event) {
		event.preventDefault();
		const formData = new FormData(form);
		try {
			const response = await fetch("/server.php", {
				method: "POST",
				headers: {
					"content-type": "application/json",
				},
				body: JSON.stringify(formData),
			});
			if (response.ok) {
				toastContainer.classList.add("show");
				setTimeout(() => {
					toastContainer.classList.remove("show");
				}, 3000);
				form.reset();
			} else {
				console.error("Error saving form data");
			}
		} catch (err) {
			console.error("Error saving form data:", err);
		}
	});
});
server.php
<?php

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Parse the JSON data from the request body.
    $data = json_decode(file_get_contents('php://input'));

    // Extract form data.
    $name = $data->name;
    $email = $data->email;
    $contactNumber = $data->contactNumber;
    $feedbackText = $data->feedbackText;

    // Prepare and execute the SQL query.
    $sql = "INSERT INTO feedbackform (name, email, contactNumber, feedbackText, createdAt) VALUES (?, ?, ?, ?, NOW())";
    $statement= $conn->prepare($sql);
    $statement->bind_param("ssss", $name, $email, $contactNumber, $feedbackText);
    if ($statement->execute()) {
        http_response_code(200);
        echo "Form data saved successfully";
        exit();
    }
}

http_response_code(400); // bad request
echo "An error has occured with your request, please try again.";
5 Likes

Hi @solace-ken,

Just happened to come across, for @Washimul 's case, the JavaScript fetch is not the main error he’s concerned about, he wants to know about the 500 error code generated on the PHP side of things, but you have pointed out another thing that he/she might need to check on.

For this JavaScript error, it is likely that the script.js is not located at the expected location, and it gets redirected to InfinityFree’s 404 page. (@Washimul you might want to check this via FTP, or file manager) Why this has net::ERR_FAILED 500 at the end after a 404 link is something that I also do not understand.

From what we see here, it’s likely that the submitted data never reached server.php, hence commenting the code does not make a change. For @Washimul, the server.php file should be placed at web root. At InfinityFree, this is right inside the /htdocs folder. Placing anything outside of this folder won’t work.

2 Likes

Hi @ChrisPAR,

He might have accidentally chose the error code 500 in his code…

But still, it really depends if the submission reaches the server.php in the first place, as there are a lot of other reasons that could cause 500, a better choice can be 400 bad request.

2 Likes

I solved my Issues

1 Like

Here its is my
script.js
document.addEventListener(“DOMContentLoaded”, function () {
const form = document.querySelector(“form”);
const toastContainer = document.getElementById(“toast-container1”);
const toastMessage = document.getElementById(“formToast-message”);

form.addEventListener("submit", async function (event) {
	event.preventDefault();
	const formData = new FormData(form);
	try {
		const response = await fetch("/server.php", {
			method: "POST",
			headers: {
				"content-type": "application/json",
			},
			body: JSON.stringify(formData),
		});
		if (response.ok) {
			toastContainer.classList.add("show");
			setTimeout(() => {
				toastContainer.classList.remove("show");
			}, 3000);
			form.reset();
		} else {
			console.error("Error saving form data");
		}
	} catch (err) {
		console.error("Error saving form data:", err);
	}

});

server.php

<?php $host = 'sql311.infinityfree.com'; $username = 'if0_34574230'; $password = ; $database = 'if0_34574230_imwashimul'; $conn = new mysqli($host, $username, $password, $database); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } header('Access-Control-Allow-Origin: https://imwashimul.rf.gd'); header('Access-Control-Allow-Methods: POST'); header('Access-Control-Allow-Headers: Content-Type'); if ($_SERVER['REQUEST_METHOD'] === 'POST') { // Parse the JSON data from the request body. $data = json_decode(file_get_contents('php://input')); // Extract form data. $name = $data->name; $email = $data->email; $contactNumber = $data->contactNumber; $feedbackText = $data->feedbackText; // Prepare and execute the SQL query. $sql = "INSERT INTO feedbackform (name, email, contactNumber, feedbackText, createdAt) VALUES (?, ?, ?, ?, NOW())"; $statement= $conn->prepare($sql); $statement->bind_param("ssss", $name, $email, $contactNumber, $feedbackText); if ($statement->execute()) { http_response_code(200); echo "Form data saved successfully"; exit(); } } http_response_code(400); // bad request echo "An error has occured with your request, please try again."; error_reporting(E_ALL); ini_set('display_errors', 1); ini_set('log_errors', 1); ?>

form.html

Name
<label for="email">Email</label>
<input type="email" class="form-control" id="email" placeholder="Enter email (optional)" name="email" autocomplete="off">

<label for="contact-number">Contact</label>
<input type="number" class="form-control" id="contact-number" placeholder="Enter contact number (optional)" name="contactNumber" min="0">

<label for="comment">Feedback</label>
<textarea required class="form-control" rows="4" id="comment" 
    placeholder="Share your valuable feedback, suggestions, or insights..." name="feedbackText"></textarea>

<p style="background-color: rgb(39, 28, 14); color: white; text-align: center; font-size: 10px;">
    *All inputs are <span style="color: rgb(107, 240, 107);">sanitized</span>, and the use of <span style="color: rgb(248, 75, 225);">special characters</span> is <span style="color: red;">not allowed</span>
</p>

<button type="submit" class="btn btn-primary">Submit</button>

Folder directory
htdocs → server.php and index.html
htdocs → assets → js-> script.js

Simply my problem is that when I submit the form that doesn’t receive the to SQL database,
or, My Form doesn’t work actually,
but when I developed this site on a local host, it worked properly, everything,
now please help me, I’m tired of trying this …

I solved my Issue

1 Like

You also leaked your vPanel username and password publicly. Consider changing it!

5 Likes

Hi @Washimul,

I checked a bit late but congrats on having everything solved, except one.

Since you posted the code with your database credentials, you now have to change that by migrating the database to a new one and then editing your previous post to hide the database information using “*” (just over type it to represent there are the credentials).

Specifically, the part where you shared server.php

<?php

$host = '*********.infinityfree.com'; // yes apparently we all use .infinityfree.com here
$username = '***********';
$password = '***********';
$database = '************************************'; 

Something like this.

This can be a security issue as outsiders can get to probe your database login info if you simply remove the password only. Having said tho they have a clear domain target as spotted in your code:

The only safe way to do this is to share this domain with no database credentials at all. Stricter would be hiding the MySQL statement as well, but since you already have PDO then that part is not as big a concern. PDO already protects your site from SQL injection.

Cheers!

2 Likes

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