无jQuery无重载:表单提交调用PHP函数获取指定年份大坝数据
Hey there! Let's work through this no-refresh year-filtering problem for your dam data map. I’ve tackled similar issues before, so here’s a straightforward, jQuery-free solution that should get your data loading and map updating without page reloads.
Core Fixes & Approach
The main issue with your earlier AJAX attempt was likely missing a critical step: preventing the form’s default submission behavior (which causes page reloads). We’ll use vanilla JavaScript’s XMLHttpRequest to send the year to a dedicated PHP handler, fetch filtered data as JSON, and then update your map directly.
Step 1: Updated HTML Form
First, let’s make sure your form has an ID to hook into, and we’ll keep it simple:
<form id="yearFilterForm"> <label for="selectedYear">Select Year:</label> <select id="selectedYear" name="year"> <option value="2020">2020</option> <option value="2021">2021</option> <option value="2022">2022</option> <!-- Add more years as needed --> </select> <button type="submit">Load Dam Data</button> </form> <div id="damMap"><!-- Your map renders here --></div>
Step 2: Vanilla JS AJAX Handler
This code listens for form submission, blocks the default reload, sends the year to your PHP backend, and updates the map when data comes back:
// Hook into the form submit event document.getElementById('yearFilterForm').addEventListener('submit', function(e) { // Critical: Stop the form from reloading the page e.preventDefault(); // Get the selected year from the dropdown const selectedYear = document.getElementById('selectedYear').value; // Initialize XMLHttpRequest const xhr = new XMLHttpRequest(); // Configure the request (POST to our PHP handler) xhr.open('POST', 'fetch_dam_data.php', true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); // Handle successful response xhr.onload = function() { if (this.status === 200) { try { // Parse the JSON data returned from PHP const damData = JSON.parse(this.responseText); // Update your map with the new data (call your existing map function) updateDamMap(damData); } catch (err) { console.error('Failed to parse dam data:', err); } } else { console.error('Request failed with status:', this.status); } }; // Handle network errors xhr.onerror = function() { console.error('Network error occurred while fetching data'); }; // Send the year parameter to PHP xhr.send('year=' + encodeURIComponent(selectedYear)); }); // Replace this with your actual map-drawing logic function updateDamMap(damData) { const mapContainer = document.getElementById('damMap'); // Clear old map content first mapContainer.innerHTML = ''; // Example: Render dam markers (adjust to match your map library) damData.forEach(dam => { const marker = document.createElement('div'); marker.className = 'dam-marker'; marker.textContent = `${dam.dam_name} | Year: ${dam.year}`; // Add position styling or map library-specific logic here mapContainer.appendChild(marker); }); }
Step 3: PHP Data Handler (fetch_dam_data.php)
This file will use your existing connectBDD function to fetch filtered data and return it as JSON (easy for JS to parse):
<?php // Include the file with your connectBDD function require_once 'your_db_config.php'; // Replace with your actual file path // Validate the incoming year parameter if (isset($_POST['year']) && is_numeric($_POST['year'])) { $targetYear = (int)$_POST['year']; // Connect to the database using your existing function $dbConnection = connectBDD(); if (!$dbConnection) { http_response_code(500); echo json_encode(['error' => 'Failed to connect to database']); exit; } // Use a prepared statement to prevent SQL injection (critical security step!) $stmt = $dbConnection->prepare("SELECT * FROM dam_data WHERE year = ?"); $stmt->bind_param("i", $targetYear); $stmt->execute(); // Fetch the results as an associative array $result = $stmt->get_result(); $filteredDams = []; while ($row = $result->fetch_assoc()) { $filteredDams[] = $row; } // Clean up database connections $stmt->close(); $dbConnection->close(); // Return data as JSON header('Content-Type: application/json'); echo json_encode($filteredDams); } else { // Return error if year is invalid http_response_code(400); echo json_encode(['error' => 'Invalid or missing year parameter']); } ?>
Key Things to Note
- Prevent Default Behavior: The
e.preventDefault()line is non-negotiable—without it, the form will still reload the page. - SQL Injection Protection: Always use prepared statements when passing user input to a database query (we did this in the PHP code).
- JSON Format: Returning data as JSON makes it trivial to parse and use in JavaScript.
- Map Updates: If you’re using a third-party map library (like Leaflet or Google Maps), just adjust the
updateDamMapfunction to use that library’s API for updating markers/layers instead of the simple DOM example above.
内容的提问来源于stack exchange,提问作者J.Delannoy

