I have the following js ajax call code, which creates a js object in the form of {1: '440', 5: '115'} and passes it via ajax to a php function:
function saveCredits() {
// Define an object to store the user IDs and credit values
var credits = {};
// Select the last column of each row in the table
$("table tbody tr").each(function() {
var userId = $(this).find("td:first-child").text();
var creditValue = $(this).find("td:last-child input").val();
credits[userId] = creditValue;
});
// Log the credits object to the console
console.log(credits);
var credits = JSON.stringify(credits);
// Send the credits object to the server via AJAX
$.ajax({
url: "'.$adminAjaxUrl.'",
data: {
action: "update_usermeta",
credits: credits
},
method: "POST",
success: function(response) {
console.log("Credits saved successfully");
},
error: function(xhr, status, error) {
console.log("Error saving credits: " + error);
}
});
};
and the following PHP ajax code:
function update_usermeta_callback() {
// Get the credits data sent via POST
$credits = $_POST['credits'];
$credits = json_decode($credits);
// Loop through the credits data and update the user meta values
foreach ( $credits as $user_id => $credit_value ) {
// Update the user meta value for 'ai_anna_credit'
update_user_meta( $user_id, 'ai_anna_credit', $credit_value );
}
// Send a success response
$response = array( 'success' => true );
echo json_encode( $response );
}
The ajax returns a success message but the database doesn’t update.
I believe that the JS object is correctly stringified and then decoded in the PHP, but why is the PHP function not correctly updating the dB?


