Error deleting note: Note ID is required & Uncaught SyntaxError: missing ) after argument list

When I click on the menu, it displays edit and delete, but I am unable to proceed from there. Edit gives me the error:

Uncaught SyntaxError: missing ) after argument list (at notes.php:121:44)

while if I click delete, it asks me to confirm and then displays the error:

Error deleting note: Note ID is required

Here are my codes below:

notes.php

<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// Initialize the session
session_start();

// Check if the user is logged in
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true) {
    header("location: login.php");
    exit;
}

// Include config file
require_once "config.php";

// Fetch notes for the current user
$user_id = $_SESSION["id"];
$sql = "SELECT * FROM notes WHERE user_id = ?";

if ($stmt = $mysqli->prepare($sql)) {
    $stmt->bind_param("i", $user_id);
    if ($stmt->execute()) {
        $result = $stmt->get_result();

        echo '<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Notes | Noted App</title>
    <link rel="stylesheet" href="notes.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- Iconscout Link For Icons -->
    <link rel="stylesheet" href="https://unicons.iconscout.com/release/v4.0.8/css/line.css">
  </head>
  <body>
    <ul class="nav-links">
      <li class="center"><a href="#">Dashboard</a></li>
      <li class="upward"><a href="#">About</a></li>
      <li class="forward"><a href="logout.php">Logout</a></li>
    </ul>
    <div class="popup-box">
      <div class="popup">
        <div class="content">
          <header>
            <p></p>
            <i class="uil uil-times"></i>
          </header>
          <form action="#">
            <div class="row title">
              <label for="title">Title</label>
              <input type="text" spellcheck="false" id="title">
            </div>
            <div class="row description">
              <label for="desc">Description</label>
              <textarea spellcheck="false" id="desc"></textarea>
            </div>
            <button></button>
          </form>
        </div>
      </div>
    </div>
    <div class="wrapper">
      <li class="add-box">
        <div class="icon"><i class="uil uil-plus"></i></div>
        <p>Add new note</p>
      </li>
      <div class="notes-list">'; // Start the notes list
      
      while ($row = $result->fetch_assoc()) {
        // Format the date
        $formattedDate = date("F j, Y", strtotime($row['date_published']));
    
        echo '<li class="note">
                <div class="details">
                    <p>' . $row['title'] . '</p>
                    <span>' . nl2br($row['description']) . '</span>
                </div>
                <div class="bottom-content"> 
                    <span>' . $formattedDate . '</span>
                    <div class="settings">
                        <i class="showMenu uil uil-ellipsis-h"></i>
                        <ul class="menu">
                            <li onclick="updateNote(' . $row['id'] . ', \'' . $row['title'] . '\', \'' . addslashes($row['description']) . '\')"><i class="uil uil-pen"></i>Edit</li>
                            <li onclick="deleteNote(' . $row['id'] . ')"><i class="uil uil-trash"></i>Delete</li>
                        </ul>
                    </div>
                </div>
            </li>';
    }

    echo '</div></div></body>
    <script src="script.js"></script>
    </html>';
    } else {
        echo "Error fetching notes.";
    }
    $stmt->close();
}
$mysqli->close();
?>

script.js

document.addEventListener("DOMContentLoaded", function () {
        const months = [
          "January",
          "February",
          "March",
          "April",
          "May",
          "June",
          "July",
          "August",
          "September",
          "October",
          "November",
          "December",
        ];
        const addBox = document.querySelector(".add-box");
        const popupBox = document.querySelector(".popup-box");
        const popupTitle = popupBox.querySelector("header p");
        const closeIcon = popupBox.querySelector("header i");
        const titleTag = popupBox.querySelector("input");
        const descTag = popupBox.querySelector("textarea");
        const addBtn = popupBox.querySelector("button");
        const show_menu = document.querySelector(".showMenu");
        const notesList = document.querySelector(".notes-list");
        const menu = document.querySelector(".menu");
    
      
        addBox.addEventListener("click", () => {
          popupTitle.innerText = "Add a new Note";
          addBtn.innerText = "Add Note";
          popupBox.classList.add("show");
          document.querySelector("body").style.overflow = "hidden";
          if (window.innerWidth > 660) titleTag.focus();
        });
      
        closeIcon.addEventListener("click", () => {
          titleTag.value = descTag.value = "";
          popupBox.classList.remove("show");
          document.querySelector("body").style.overflow = "auto";
        });
      
        function showNotes() {
          // Send an AJAX request to fetch notes
          fetch("fetch_notes.php")
            .then((response) => {
              if (!response.ok) {
                throw new Error("Network response was not ok");
              }
              return response.json();
            })
            .then((data) => {
              if (data && data.length > 0) {
                notesList.innerHTML = ""; // Clear existing notes
                data.forEach((note) => {
                  let filterDesc = note.description.replaceAll("\n", "<br/>");
                  let liTag = `
                              <li class="note">
                                  <div class="details">
                                      <h3>${note.title}</h3>
                                      <p>${filterDesc}</p>
                                      <p>Date Published: ${note.date}</p>
                                  </div>
                                  <div class="bottom-content">
                                      <div class="settings">
                                          <i onclick="showMenu(this)" class="uil uil-ellipsis-h"></i>
                                          <ul class="menu">
                                              <li onclick="updateNote(${note.id}, '${note.title}', '${filterDesc}')"><i class="uil uil-pen"></i>Edit</li>
                                              <li onclick="deleteNote(${note.id})"><i class="uil uil-trash"></i>Delete</li>
                                          </ul>
                                      </div>
                                  </div>
                              </li>
                          `;
                  notesList.insertAdjacentHTML("beforeend", liTag);
                });
              } else {
                // Handle case where there are no notes or the data is empty
                notesList.innerHTML = "<p>No notes available.</p>";
              }
            })
            .catch((error) => {
              console.error("Error fetching notes:", error);
              // Handle other errors, e.g., network issues or server errors
              notesList.innerHTML = "<p>Error fetching notes. Please try again later.</p>";
            });
        }
      
        showNotes();
    
        show_menu.addEventListener("click", () => {
            showMenu();
        });
        
        // Initialize the openMenu variable
    let openMenu = null;

    window.showMenu = function (elem) {
        elem.parentElement.classList.add("show");
        document.addEventListener("click", e => {
            if(e.target.tagName != "I" || e.target != elem) {
                elem.parentElement.classList.remove("show");
            }
        });
    }

      // Close the menu when clicking outside of it
      document.addEventListener('click', function closeMenu(event) {
        if (!menu.contains(event.target)) {
          menu.classList.remove('show');
          document.removeEventListener('click', closeMenu);
          openMenu = null;
        }
      });
    
    // Attach the showMenu function to your settings icons
    document.addEventListener("DOMContentLoaded", function () {
      const notesList = document.getElementById("notesList");
      notesList.addEventListener("click", function (event) {
        const settingsIcon = event.target.closest(".settings i");
        if (settingsIcon) {
          const menu = settingsIcon.nextElementSibling;
          showMenu(settingsIcon, menu);
        }
      });
    });
    
      
        window.deleteNote = function (noteId) {
          let confirmDel = confirm("Are you sure you want to delete this note?");
          if (!confirmDel) return;
      
          // Send a DELETE request to delete the note
          fetch("delete_note.php", {
            method: "DELETE",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify({ id: noteId }),
          })
            .then((response) => response.json())
            .then((data) => {
              if (data.success) {
                showNotes(); // Refresh the notes list
              } else {
                console.error("Error deleting note:", data.error);
              }
            })
            .catch((error) => {
              console.error("Error deleting note:", error);
            });
        }
      
        window.updateNote = function (noteId, title, filterDesc) {
          let description = filterDesc.replaceAll("<br/>", "\r\n");
          addBox.click();
          titleTag.value = title;
          descTag.value = description;
          popupTitle.innerText = "Update a Note";
          addBtn.innerText = "Update Note";
      
          // Store the note ID to use when updating
          addBtn.dataset.noteId = noteId;
        }
      
        addBtn.addEventListener("click", (e) => {
          e.preventDefault();
          let title = titleTag.value.trim();
          let description = descTag.value.trim();
      
          if (title || description) {
            let currentDate = new Date();
            let month = months[currentDate.getMonth()]; // Change 'month' to 'months'
            let day = currentDate.getDate();
            let year = currentDate.getFullYear();
            let noteInfo = { title, description, date: `${month} ${day}, ${year}` };
      
            let isUpdate = !!addBtn.dataset.noteId;
            let url = isUpdate ? "update_note.php" : "add_note.php";
      
            if (isUpdate) {
              noteInfo.id = addBtn.dataset.noteId;
            }
      
            // Send an AJAX request to add/update the note
            fetch(url, {
              method: "POST",
              headers: {
                "Content-Type": "application/json",
              },
              body: JSON.stringify(noteInfo),
            })
              .then((response) => response.json())
              .then((data) => {
                if (data.success) {
                  showNotes(); // Refresh the notes list
                  closeIcon.click(); // Close the popup
                } else {
                  console.error("Error saving note:", data.error);
                }
              })
              .catch((error) => {
                console.error("Error saving note:", error);
              });
          }
        });
      });

delete_note.php

<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();

if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true) {
    // Redirect to login page or handle unauthorized access as needed
    echo json_encode(array("error" => "Unauthorized access"));
    exit;
}

require_once "config.php";

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

if (empty($data->id)) {
    echo json_encode(array("error" => "Note ID is required"));
    exit;
}

// Prepare and execute the SQL statement to delete the note
$sql = "DELETE FROM notes WHERE id = ? AND user_id = ?";

if ($stmt = $mysqli->prepare($sql)) {
    $stmt->bind_param("ii", $data->id, $_SESSION["id"]);

    if ($stmt->execute()) {
        echo json_encode(array("success" => true));
    } else {
        echo json_encode(array("error" => "Error deleting the note"));
    }

    $stmt->close();
} else {
    echo json_encode(array("error" => "Error preparing the statement"));
}

$mysqli->close();
?>
```
update_note.php

```
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();

if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true) {
    // Redirect to login page or handle unauthorized access as needed
    echo json_encode(array("error" => "Unauthorized access"));
    exit;
}

require_once "config.php";

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

if (empty($data->id) || empty($data->title) || empty($data->description)) {
    echo json_encode(array("error" => "Note ID, title, and description are required"));
    exit;
}

// Prepare and execute the SQL statement to update the note
$sql = "UPDATE notes SET title = ?, description = ? WHERE id = ? AND user_id = ?";

if ($stmt = $mysqli->prepare($sql)) {
    $stmt->bind_param("ssii", $data->title, $data->description, $data->id, $_SESSION["id"]);

    if ($stmt->execute()) {
        echo json_encode(array("success" => true));
    } else {
        echo json_encode(array("error" => "Error updating the note"));
    }

    $stmt->close();
} else {
    echo json_encode(array("error" => "Error preparing the statement"));
}

$mysqli->close();
?>

Creating a new note and fetching from the database works, but editing and deleting bring up the errors I mentioned.

  • Uncaught SyntaxError: missing ) after argument list is a client side error. Look at your jS for that one.

    – 

  • var_dump($data) in delete_note.php gives what back?

    – 

  • @user3783243 var_dump($data) gives back NULL

    – 

Leave a Comment