AJAX调用未传参无报错及根据选中州获取城市列表问题咨询
Question 1: How to Fetch City List Based on Selected State
Your current setup is almost there, but there are a couple of key fixes needed to get it working properly:
1. Fix the Server-Side PHP Code
In your get_city() function, you have print_r($query); exit(); which stops execution before generating the city option HTML. Remove those lines so the dropdown options can be rendered. Also, add a check to ensure the id parameter is received correctly:
public function get_city() { // Check if state ID is provided if (!isset($_POST['id']) || empty($_POST['id'])) { echo '<option value="" disabled selected>Please select a state first</option>'; exit(); } $id = $_POST['id']; $query = $this->common->select_data_by_id('city', 'state', $id, '*', ''); // Start building the city options echo '<option value="" disabled selected>Choose your city</option>'; if (!empty($query)) { foreach($query as $place) { echo '<option value="'.$place['city_name'].'">'.$place['city_name'].'</option>'; } } else { echo '<option value="" disabled>No cities found for this state</option>'; } exit(); }
2. Update the AJAX Success Handler
Uncomment the line that populates the city dropdown, and remove the debug alert (or keep it temporarily for testing):
$(document).ready(function() { jQuery('#state').change(function() { var id = jQuery(this).val(); if (!id) return; // Exit if no state is selected jQuery.ajax({ type: 'post', url: "<?php echo base_url().'routes/get_city' ?>", data: { id: id }, // Use object syntax for cleaner data passing success: function(result) { jQuery('.city').html(result); // Populate the city dropdown }, error: function(xhr, status, error) { console.error("AJAX Error:", status, error); // Add error logging } }); }); });
Question 2: Troubleshooting AJAX Call Not Passing Data (No Errors Thrown)
If your AJAX call isn't sending data and isn't throwing errors, follow these steps to diagnose the issue:
Check the Browser Network Tab:
Open your browser's developer tools (F12), go to the Network tab, and trigger the state change. Look for the AJAX request toget_city:- Confirm the request method is
POST - Verify the request URL is correct (no typos in the base URL or route)
- Check the "Form Data" section to see if the
idparameter is being sent
- Confirm the request method is
Validate Server-Side Receipt:
Add debug code to yourget_city()function to confirm if the data is reaching the server:public function get_city() { var_dump($_POST); // Check if id is present exit(); }If
$_POSTis empty, you might need to check if your server requires CSRF tokens (common in frameworks like CodeIgniter) or if the request content type is set correctly.Add AJAX Error Handling:
Your current code only has a success handler. Add error callbacks to catch silent failures:jQuery.ajax({ // ... existing options error: function(xhr, status, error) { console.log("Request failed:", xhr.responseText); alert("Failed to load cities: " + error); }, complete: function(xhr) { console.log("Request status:", xhr.status); } });Check for Syntax or Scope Issues:
- Ensure there are no typos in your JavaScript (e.g., misspelled
idvariable, incorrect selector for the state dropdown) - Confirm that
base_url()is generating a valid absolute URL (echo it out in the HTML to verify) - If using CodeIgniter, make sure the
routes/get_cityroute is properly defined in your routes file
- Ensure there are no typos in your JavaScript (e.g., misspelled
Verify State Dropdown Value:
Ensure the selected state option has a non-emptystate_idvalue. You can test this by addingconsole.log(id)right aftervar id = jQuery(this).val();
内容的提问来源于stack exchange,提问作者Arazu Gajera

