携带数据的Ajax请求返回成功但功能失效问题求助
Let’s walk through why your database insert isn’t working even though the AJAX call reports success. Here are the key issues and fixes to resolve this:
1. Critical SQL Syntax Error
Your INSERT query has a broken string concatenation that’s causing invalid SQL syntax—this is almost certainly why the insert fails:
// Your broken query $db->query("INSERT INTO zanr_anime(identificator, zanr) VALUES ('".$_POST['identificator'].",'...");
You’re missing the closing single quote for the identificator value before the comma. Fix it like this (and make sure to complete the zanr value using your genreS parameter):
$db->query("INSERT INTO zanr_anime(identificator, zanr) VALUES ('".$_POST['identificator']."', '".$_POST['genreS']."')");
Even better: Use prepared statements to avoid SQL injection (this is critical for security and avoids syntax issues with special characters):
if(isset($_POST['pridej'])){ $stmt = $db->prepare("INSERT INTO zanr_anime(identificator, zanr) VALUES (?, ?)"); $stmt->bind_param("ss", $_POST['identificator'], $_POST['genreS']); $stmt->execute(); }
2. Unreliable Check for $_POST['pridej']
Your condition if($_POST['pridej']){...} will fail if pridej is a falsy value (like 0, an empty string, etc.). Use isset() to properly verify the parameter exists:
if(isset($_POST['pridej'])){ // Your insert logic here }
3. Unexpected Output Before Database Logic
You’re echoing a script tag before running the insert:
echo("<script>alert('ola');</script>");
While this doesn’t break the AJAX success callback, it’s unnecessary for an API endpoint and can interfere if you ever need to parse the server response. Remove this line or move it after your database logic if you truly need it.
4. Debugging Steps to Confirm Fixes
- Check for SQL Errors: Add error handling to your query to see exactly what’s going wrong:
Then update your AJAX success callback to log the server response:$result = $db->query(...); if(!$result){ echo "SQL Error: " . $db->error; exit; }success: function(data) { console.log("Server response:", data); alert("ok"); } - Verify POST Parameters: Add
var_dump($_POST);at the top ofgenre_function.phpand check your browser’s console to confirm all parameters (pridej,identificator,genreS) are being passed correctly. - Validate Database Connection: Double-check that
../pripojeni.phpproperly initializes the$dbconnection (e.g., using mysqli/PDO correctly) and that there are no connection errors.
By fixing the SQL syntax and adding proper error handling, you should get the insert functionality working as expected.
内容的提问来源于stack exchange,提问作者Nuimi

