The database powered by Postgresql performs flawlessly when it comes to updating data with accurate code execution. However, there seems to be an

Imagine a zoo with a postgresql database. To enable web access to this database, I am using php and javascript. Most of the web pages are working fine, but I am currently working on a page where clients can add or remove animals from existing exhibits. There is a dropdown menu that displays exhibit names from the database. The second dropdown is populated dynamically based on the exhibit name selected, showing animal names and their corresponding IDs (with reference to exhibit_id in the animal table). Upon initial loading of the page, everything works correctly. However, when the client clicks the add or remove button, although the database is updated properly, the page keeps loading instead of displaying a success message and allowing the client to choose another exhibit to see the updates. This issue may be due to my code being sloppy, as I have been teaching myself HTML, PHP, and JS. I would appreciate any assistance in resolving this problem and implementing appropriate fixes. Thank you!

<?php
  //Read database information from file and assign it to variables
  $myfile = fopen("../pg_connection_info.txt", "r") or die("Unable to open \"../pg_connection_info.txt\" file!");
  $my_host = fgets($myfile);
  $my_dbname = fgets($myfile);
  $my_user = fgets($myfile);
  $my_password = fgets($myfile);
  fclose($myfile);

  // Establish a connection to the database
  $dbhost = pg_connect("host=$my_host dbname=$my_dbname user=$my_user password=$my_password");

  // If there is an error in the $dbhost variable, display error message
  if(!$dbhost)
  {
    die("Error: ".pg_last_error());
  }

  // Retrieve exhibits from the database
  $query = "SELECT exhibit_id, name FROM exhibit";
  $result = pg_query($dbhost, $query);
  
  while($row = pg_fetch_row($result))
  {
    $categories[] = array("id" => $row[0], "val" => $row[1]);
  }

  // Get animals assigned to exhibits
  $query2 = "SELECT animal_id, exhibit_id, name FROM animal";
  $result2 = pg_query($dbhost, $query2);

  while($row = pg_fetch_row($result2))
  {
    $subcats[$row[1]][] = array("id" => $row[0], "val" => $row[2]);
  }

  $jsonCats = json_encode($categories);
  $jsonSubCats = json_encode($subcats);
?>


<html lang="en-us">
 <head>
   <title>Manage Animals/Exhibits</title>
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script type='text/javascript'>
      <?php
        echo "var categories = $jsonCats; \n";
        echo "var subcats = $jsonSubCats; \n";
      ?>
      function loadCategories(){
        var select = document.getElementById("exhibit");
        select.onchange = updateSubCats;
        var j = 0;
        select.options[0] = new Option("--Select an option--"); 
        for(var i = 0; i < categories.length; i++){
          select.options[j + 1] = new Option(categories[i].val,categories[i].id);   
          j++;       
        }
      }

      function updateSubCats(){
        var catSelect = this;
        var catid = this.value;
        var subcatSelect = document.getElementById("animal");
        subcatSelect.options.length = 0;
        for(var i = 0; i < subcats[catid].length; i++){
          subcatSelect.options[i] = new Option(subcats[catid][i].val + " - " + subcats[catid][i].id ,subcats[catid][i].id);
        }
      }

     window.onmousedown = function(e)
    {
      var el = e.target;
      if(el.tagName.toLowerCase() == 'option' && el.parentNode.hasAttribute('multiple'))
      {
        e.preventDefault();
        if(el.hasAttribute('selected')) el.removeAttribute('selected');
        else el.setAttribute('selected', '');
      }
    }
   </script>

</head>
<body onload='loadCategories()'>
<h1>Manage Animals/Exhibits</h1>
<form action="Manage_Animal_Exhibit.php" method="post">
<p>Select an exhibit to add or remove animal(s) from:</p>
Exhibit: <select name="exhibit" id="exhibit">
  </select><br><br> 
  <p>Current animals in the exhibit:</p> 
  <select name="animal[]" id='animal' multiple>
  </select><br><br>
  <input type="submit" name="Remove" value="Remove"/><br><br>
  <p>Current unassigned animals:</p>
  <select name="animalAvail[]" id='animalAvail' multiple>
<?php
 $query3 = "SELECT name, animal_id FROM animal WHERE exhibit_id is NULL";
 $result3 = pg_query($dbhost, $query3);
  while($row = pg_fetch_row($result3)){
      $name = $row[0]; 
      $id = $row[1];
      echo "<option value='$id'>$name - $id </option>";
  }
?>
  </select><br><br>
  <input type="submit" name="Add" value="Add"/><br><br>
  </form>

  <form action="Home_Page.php" method="post">
    <input type="submit" name="Exit" value="Exit"/>
  </form>


<?php
if(isset($_POST["Add"]))
{ 
  if($_POST["exhibit"] == "--Select an option--")
  {
    echo "<script type='text/javascript'>alert('Select an exhibit')</script>";
  }
  else
  { 
    $arr = array();
    foreach($_POST["animalAvail"] as $animalID)
    {
       array_push($arr, "$animalID");
    } 

    $exhibitID =  $_POST["exhibit"];
    $query4 = "UPDATE Animal SET exhibit_id = $1 WHERE animal_id = $2";
    pg_prepare($dbhost, "prepare1", $query4);
    for($i = 0; i < count($arr); $i++)
    { 
      $idToUpdate = $arr[$i];
      pg_execute($dbhost, "prepare1", array($exhibitID, $idToUpdate));
    }
      echo "<script type='text/javascript'>alert('The animals were added to the exhibit')</script>";
  }
}


if(isset($_POST["Remove"]))
{
  if($_POST["exhibit"] == "--Select an option--")
  {
    echo "<script type='text/javascript'>alert('Select an exhibit')</script>";
  }
  else
  { 
    $arr2 = array();
    foreach($_POST["animal"] as $aID)
    {
       array_push($arr2, "$aID");
    }      
    $query5 = "UPDATE Animal SET exhibit_id = NULL WHERE animal_id = $1";
    pg_prepare($dbhost, "prepare2", $query5);
    for($i = 0; i < count($arr2); $i++)
    { 
      $idUpdate = $arr2[$i];
      pg_execute($dbhost, "prepare2", array($idUpdate));
    }
    echo "<script type='text/javascript'>alert('The animals were removed from the exhibit')</script>";
  }
}
pg_free_result($result);

pg_close($dbhost);
?>

</body>
</html>

Answer №1

After optimizing my code, I accomplished immediate loading of the webpage. The problem stemmed from the code responsible for updating the database when either the add or remove button was pressed. Initially, I utilized an enhanced for loop to collect the selected values and store them in an array, followed by a for loop to update the records in the database. However, I managed to streamline the process by combining both tasks into a single enhanced for loop. Here's an example of what I implemented for the add functionality. The remove function follows a similar format.

// Execute this block of code when the add button is pressed to assign animals to the exhibit
if(isset($_POST["Add"]))
{ 
  // Display an alert message if no exhibit is selected
  if($_POST["exhibit"] == "--Select an option--")
  {
    echo "<script type='text/javascript'>alert('Select an exhibit');</script>";
  }
  else
  { 
    // Retrieve the ID of the selected exhibit and proceed to add animals
    $exhibitID = $_POST["exhibit"];
    $query4 = "UPDATE Animal SET exhibit_id = $1 WHERE animal_id = $2";
    pg_prepare($dbhost, "prepare1", $query4);
    foreach($_POST["animalAvail"] as $animalID)
    { 
      pg_execute($dbhost, "prepare1", array($exhibitID, $animalID));
    }
    echo "<script type='text/javascript'>alert('The animals were added to the exhibit');</script>";
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering a glitch while attempting to execute my test on webdriverio

Lately, I've encountered an issue while attempting to execute my webdriverio tests following an upgrade of my node version. The error message that now pops up is: 2022-01-11T12:45:05.628Z DEBUG @wdio/config:utils: Couldn't find ts-node package, n ...

Identify an asynchronous JavaScript and XML (AJAX)

As a part of my practice, I am developing my own MVC framework and have created a Request class. My goal is to identify the type of request being made, whether it is an AJAX/JSON call or an HTML/XML request, in order to parse the data accordingly. Current ...

Locate the next element with the same class using jQuery across the entire document

I'm working with the following HTML: <section class="slide current"></section> <section> <div class="slide"></div> <div class="slide"></div> </section> <section class="slide"></section> ...

Extracting Data from JSON Structures

I am struggling with extracting data from a JSON string that looks like this: var txt= '{“group”: [ {“family1”: { “firstname”:”child1”, “secondname”:”chlid2” }}, {“family2”: { ...

Implementing a loading spinner in React Native until the component is fully mounted

I am dealing with a List component that takes some time to load. I am trying to display a spinner until the component is loaded and mounted, but all my attempts have been unsuccessful. Here is the approach I am currently attempting: class List extends R ...

best practices for sending multiple requests using node js

I have a list of 4 URLs, each containing JSON data. How can I iterate through these URLs? Example: URLs = [ "", "", "", ""]; Each URL contains JSON data for one student as follows: { date: 08/05/2014 stude ...

Matching with Regex beyond the limits

Trying to extract a body tag using regex and then replace it with an appended string. However, encountering an issue where the regex is selecting more content than intended. regex: /<body.*[^>]>/i test string: <bla bla ><body class=&apo ...

In PHP, the response from Ajax can also serve as a class name

I attempted to retrieve a success response from my ajax call, but unfortunately, it failed. Upon inspecting the console in Chrome, I noticed that the response contained my JSON data along with the class name triggered in my .php file, leading to an excepti ...

Error: Unable to cast value "undefined" to an ObjectId for the "_id" field in the "User" model

Whenever a user logs into their account, I am trying to retrieve their data on the login screen. The login functionality itself works perfectly, but unfortunately, the user data is not displaying. I have tried troubleshooting this issue by making changes i ...

Adding Space Before Bullet Points in HTML: A Quick Guide

Is there a way to add space before bullet points? My requirements are as follows: This is paragraph 1 The first text line The second text line This is paragraph 2 The first text line The second text line I would greatly appreciate any ...

The combination of Ajax, JavaScript, PHP/HTML, and dynamic variables

Hey there, I'm currently working on a game development project and have encountered what seems to be a scope issue. The issue arises in my js file when a player clicks on the card they want to play: It starts in my js file:</p> <pre>&l ...

My server keeps crashing due to an Express.js API call

I'm completely new to express.js and API calls, and I'm stuck trying to figure out why my server keeps crashing. It works fine the first time, rendering the page successfully, but then crashes with the error: TypeError: Cannot read property &apo ...

What is the best way to customize the CSS of the Skype contact me button?

I am struggling with customizing the Skype contact me button. The standard Skype button has a margin of 24px and vertical-align set to -30px. I have tried removing these styles but have had no success. Here is the code snippet I am working with: Skype ...

Remove the first character if the variable starts with a dot

Seeking a foolproof solution that is simple. I have a $keyword variable and I need to filter it by removing the first character if it is a '.' Otherwise, I want to leave it unchanged. I am hesitant to attempt this on my own because in the past, I ...

Sharing AngularJs controllers between different modules can help streamline your

I'm facing an issue with trying to access an array from one controller in another controller. Despite simplifying the code for clarity, I still can't seem to make it work. Here is my first controller: app.controller('mycont1', [' ...

Is it possible to interpret all events from multiple perspectives?

Is it possible to listen for events in three different ways? This example shows how we can listen for the load event: 1. <body onload="doSomething();"> 2. document.body.onload = doSomething; 3. document.body.addEventListener('load', doS ...

Exploring the Pros and Cons of Incorporating ob_start() Function in PHP

Just recently, I encountered an issue with a PHP script that threw an error message: An alert popped up: Warning - Headers cannot be modified because they were already sent by (output started at C:\xampp\htdocs\jnexm\login.php:2) in ...

Move the button above a hyperlink in a Bootstrap carousel

Is there a way to add a top-right button on each slide that will be positioned over the carousel-control link? How can I achieve this design? Currently, the buttons appear under the carousel-control as shown below: .myButton { position: absolute; ...

Retrieving Data from a JSON File in ASP.NET MVC 4

After diving into learning ASP.NET MVC 4, I dabbled in some small projects... On my index page, my goal is to fetch a JSON file containing data and showcase it on the main page. In basic HTML and JavaScript, I utilize ajax for fetching or posting JSON da ...

css boxShadow merger

Looking to create a sleek horizontal navigation bar using an unordered list with list items representing each element: To ensure the elements fit perfectly within the bar, I set the width of each at 25% and added a box-shadow for a border. Using a traditi ...