AngularJS发送HTTP POST请求返回undefined及PHP后端数据接收异常问题求助
Hey there, let's work through why your POST request is returning undefined and failing to insert data into your database. I've gone over your code and spotted a few key mismatches and missing pieces that are causing the problem.
Key Issues in Your Original Code
1. Data is sent in the URL, not the POST body
You're using AngularJS's params option in your $http call, which appends data to the URL as query parameters (like you saw in your debug info: url: "insert.php?send_id=78..."). But your PHP code tries to read data from the POST request body using file_get_contents("php://input"). Since the body is empty, json_decode returns null, and your database logic never runs.
2. PHP tries to access array data as an object
You're using json_decode(..., true) which returns an associative array, but then you try to access values with object syntax ($data->send_id). This throws an error because $data is either null or an array, not an object.
3. Missing send_btnName parameter
Your PHP code checks for $btnname_received == 'ADD', but your AngularJS Indata object doesn't include a send_btnName key. Even if other data was sent correctly, this condition would fail and skip the insertion.
4. SQL Injection Risk
Using mysqli_real_escape_string is better than nothing, but prepared statements are the safer, recommended way to prevent SQL injection attacks.
Fixed Code Examples
Option 1: Send JSON Data (Simpler for AngularJS)
This approach sends data as JSON, which is easy to handle in both AngularJS and PHP.
AngularJS Code
var app = angular.module("myapp", []); app.controller("booking", function($scope, $http) { $scope.paidops = ["Paid", "Due"]; $scope.value = "ADD"; $scope.insertvalues = function() { // Include the missing send_btnName parameter var Indata = { 'send_id': $scope.id, 'send_name': $scope.name, 'send_phone': $scope.phone, 'send_status': $scope.status, 'send_btnName': $scope.value }; // Use $http.post directly - it handles JSON serialization automatically $http.post('insert.php', Indata) .then(function(response) { alert("Success: " + response.data); console.log("Full response:", response); }, function(error) { alert("Error: " + JSON.stringify(error)); console.error("Request failed:", error); }); } });
PHP Code
<?php error_reporting(E_ALL); ini_set('display_errors', 1); // Enable error reporting for debugging $connect = mysqli_connect("localhost:3307", "root", "", "ticket_booking"); if($connect === false){ die("ERROR: Could not connect. " . mysqli_connect_error()); } // Read and decode the JSON request body into an associative array $data = json_decode(file_get_contents("php://input"), true); // Validate the button action first if(isset($data['send_btnName']) && $data['send_btnName'] === 'ADD') { // Check that all required fields are present if(isset($data['send_id'], $data['send_name'], $data['send_phone'], $data['send_status'])) { // Use a prepared statement to prevent SQL injection $query = "INSERT INTO society_tour(id, name, phone, status) VALUES (?, ?, ?, ?)"; $stmt = mysqli_prepare($connect, $query); // Bind parameters (the "ssss" means all 4 are string values) mysqli_stmt_bind_param($stmt, "ssss", $data['send_id'], $data['send_name'], $data['send_phone'], $data['send_status'] ); if(mysqli_stmt_execute($stmt)) { echo "Data Inserted..."; } else { echo 'Error: ' . mysqli_stmt_error($stmt); } mysqli_stmt_close($stmt); } else { echo 'Error: Missing required fields (id, name, phone, status)'; } } else { echo 'Error: Invalid or missing button action'; } mysqli_close($connect); ?>
Option 2: Send Form-Encoded Data
If you prefer to use application/x-www-form-urlencoded (like your original header), use AngularJS's $httpParamSerializerJQLike to format data correctly, and access it via $_POST in PHP.
AngularJS Code
var app = angular.module("myapp", []); app.controller("booking", function($scope, $http, $httpParamSerializerJQLike) { $scope.paidops = ["Paid", "Due"]; $scope.value = "ADD"; $scope.insertvalues = function() { var Indata = { 'send_id': $scope.id, 'send_name': $scope.name, 'send_phone': $scope.phone, 'send_status': $scope.status, 'send_btnName': $scope.value }; $http({ method: 'POST', url: 'insert.php', data: $httpParamSerializerJQLike(Indata), // Serialize to form data headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).then(function(response) { alert("Success: " + response.data); console.log(response); }, function(error) { alert("Error: " + JSON.stringify(error)); console.error(error); }); } });
PHP Code
<?php error_reporting(E_ALL); ini_set('display_errors', 1); $connect = mysqli_connect("localhost:3307", "root", "", "ticket_booking"); if($connect === false){ die("ERROR: Could not connect. " . mysqli_connect_error()); } if(isset($_POST['send_btnName']) && $_POST['send_btnName'] === 'ADD') { if(isset($_POST['send_id'], $_POST['send_name'], $_POST['send_phone'], $_POST['send_status'])) { $query = "INSERT INTO society_tour(id, name, phone, status) VALUES (?, ?, ?, ?)"; $stmt = mysqli_prepare($connect, $query); mysqli_stmt_bind_param($stmt, "ssss", $_POST['send_id'], $_POST['send_name'], $_POST['send_phone'], $_POST['send_status'] ); if(mysqli_stmt_execute($stmt)) { echo "Data Inserted..."; } else { echo 'Error: ' . mysqli_stmt_error($stmt); } mysqli_stmt_close($stmt); } else { echo 'Error: Missing required fields'; } } else { echo 'Error: Invalid or missing button action'; } mysqli_close($connect); ?>
Debugging Tips
- Open your browser's DevTools (F12) → Network tab. Look for the
insert.phprequest and check the Request Body (for JSON) or Form Data (for form-encoded) to confirm data is sent correctly. - Check the Response tab to see exactly what your PHP script returns.
- The error reporting lines in PHP will help catch hidden issues during testing.
内容的提问来源于stack exchange,提问作者web_in

