-2

I have an HTML registration Form

  <form id="register">
        <label>first name</label>
        <input type="text" name="txt-fname" id="firstName" /><br/>
        <label>last name</label>
        <input type="text" name="txt_lname" id="lastName" /><br/>
        <label>email address</label>
        <input type="email" name="txt-email" id="email" autocomplete="new-username"/><br/>
        <label>password</label>
        <input type="password" name="txt-pass" id="password" autocomplete="new-password"/><br/>
        <label>confirm password</label>
        <input type="password" name="txt_cpass" id="confirmPassword" autocomplete="new-password"/><br/>
        <label>phone number</label>
        <input type="tel" name="txt-phone" id="phoneNumber" /><br/>
      <button type="submit">sign up</button>
  </form>

I'm trying to send the data of this form to php backend using vanilla javascript

const form = document.getElementById("register");

form.addEventListener("submit", function (event) {
  if (!validateForm(event)) {
    // If the form validation fails, prevent the submission
    event.preventDefault();
  } else {
    sendData();
  }
});

  function sendData() {
  // Create an object to hold the form data
  const formData = new FormData(form);
  // Make a POST request to the backendEndpointURL using fetch
  fetch("http://localhost/registration/api/add-user.php", {
    method: "post",
    body: formData,
  })
    .then((response) => {
      if (!response.ok) {
        throw new Error("Network response was not ok");
      }
      return response.json();
    })
    .then((data) => {
      console.log(data);
    })
    .catch((error) => {
      console.error("Error sending data to the backend:", error);
    });
}

The Problem is that the data appear in the url like i'm using GET Method not Post Method Like That

http://127.0.0.1:5500/index.html?txt-fname=m&txt_lname=s&txt-email=m%40c.c&txt-pass=M_123456s&txt_cpass=M_123456s&txt-phone=70801253

Also when i check the network on the browser nothing on it it's empty and also nothing in the mysql database

PHP Code for add-user.php

<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Content-Type");

include_once "../includes/connect.php";
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Assuming the form fields are named "firstName", "lastName", "email", "password", "confirmPassword", and "phoneNumber"
    $firstName = $_POST['firstName'];
    $lastName = $_POST['lastName'];
    $email = $_POST['email'];
    $password = $_POST['password'];
    $confirmPassword = $_POST['confirmPassword'];
    $phoneNumber = $_POST['phoneNumber'];

    // Now you can use the received data as needed, such as storing it in a database or performing other operations
    // For example, you can store the data in a MySQL database using mysqli.

    // Prepare the data for inserting into the database (you should sanitize the data to prevent SQL injection)
    $firstName = mysqli_real_escape_string($conn, $firstName);
    $lastName = mysqli_real_escape_string($conn, $lastName);
    $email = mysqli_real_escape_string($conn, $email);
    $password = mysqli_real_escape_string($conn, $password);
    $confirmPassword = mysqli_real_escape_string($conn, $confirmPassword);
    $phoneNumber = mysqli_real_escape_string($conn, $phoneNumber);

    if (!empty($firstName) && !empty($lastName) && !empty($email) && !empty($password) && !empty($phoneNumber)) {
        if ($password === $confirmPassword) {
            // Hash the password
            $hashedPassword = password_hash($password, PASSWORD_DEFAULT);

            // Create the SQL query
            $sql = "INSERT INTO tbl_user (db_fname, db_lname, db_email, db_pass, db_encpass, db_phone) VALUES ('$firstName', '$lastName', '$email', '$password', '$hashedPassword', '$phoneNumber')";

            if (mysqli_query($conn, $sql)) {
                // Data inserted successfully
                echo json_encode(array("message" => "User added successfully"));
            } else {
                // Error inserting data
                echo json_encode(array("message" => "Error adding user"));
            }
        } else {
            // Passwords do not match
            echo json_encode(array("message" => "Passwords do not match"));
        }
    } else {
        // Required fields are empty
        echo json_encode(array("message" => "Please fill in all required fields"));
    }

    // Close the database connection
    $conn->close();
}

?>

How to send data in a correct way to php and insert this data in mysql database?

Mohamad
  • 602
  • 2
  • 5
  • 18
  • Move `event.preventDefault();` to the top of your event handler. You need to stop subission in any case – mplungjan Aug 05 '23 at 12:29
  • `document.getElementById("register").addEventListener("submit", function (event) { event.preventDefault(); if (!validateForm(event)) return; /* leave */ const formData = new FormData(form); ....... });` – mplungjan Aug 05 '23 at 12:32
  • @mplungjan thank you so much this help me to stop submetting the form but when i check the network on the browser the Status Code: is green 200 ok – Mohamad Aug 05 '23 at 12:40
  • Why is that a problem? The fetch is still needed to run – mplungjan Aug 05 '23 at 12:45
  • @mplungjan the problem is this now error sending data to the backend: SyntaxError: Unexpected token '<', "
    – Mohamad Aug 05 '23 at 12:47
  • That is unlikely. Look at the request in the network tab. You should have the formdata only – mplungjan Aug 05 '23 at 13:00
  • That error sounds like it's more likely to have come from trying to process the response to the request, rather than what the request had sent – ADyson Aug 05 '23 at 22:17

0 Answers0