fetch(my_ajax_object.ajax_url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
action: 'process_checkout',
nonce: my_ajax_object.nonce_process_checkout,
selected_price: selectedPriceValue,
quote_id: quoteId,
}),
})
.then(response => {
console.log('Raw Response:', response);
return response.json();
})
.then(data => {
console.log('Parsed Response:', data);
if (data.success) {
window.location.href = nextStepPath;
} else {
console.error('Error:', data.message);
alert('An error occurred. Please try again.');
}
})
.catch(error => {
console.error('Error:', error);
});
}
<?php
function handle_process_checkout() {
// Start session if not already started
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
// Verify nonce for security
if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'process_checkout_nonce')) {
wp_send_json_error(['message' => 'Unauthorized request. Invalid or missing nonce.'], 403);
return;
}
// Capture and validate incoming data
$selected_price = isset($_POST['selected_price']) ? floatval($_POST['selected_price']) : 0.00;
$valid_options = ['cash_price', 'regular_price'];
if (empty($selected_price_option) || !in_array($selected_price_option, $valid_options)) {
wp_send_json_error(['message' => 'Invalid or missing selected_price_option.'], 400);
return;
}
$quote_id = sanitize_text_field($_SESSION['quote_id'] ?? ($_POST['quote_id'] ?? ''));
if (empty($quote_id)) {
wp_send_json_error(['message' => 'Missing quote ID.'], 400);
return;
}
// Ensure session data exists for prices and cast as float
$cash_price = isset($_SESSION['cash_price']) ? floatval($_SESSION['cash_price']) : 0.00;
$regular_price = isset($_SESSION['regular_price']) ? floatval($_SESSION['regular_price']) : 0.00;
// Determine the selected price value
$selected_price_value = ($selected_price_option === 'cash_price') ? $cash_price : $regular_price;
// Update session with selected price value
$_SESSION['selected_price'] = $selected_price_value;
// Update the database with the numeric value
global $wpdb;
$table_name = $wpdb->prefix . 'jet_cct_instant_quotes';
$result = $wpdb->update(
$table_name,
[
'selected_price' => $selected_price_value // Use the calculated value
],
[
'quote_id' => $quote_id
],
[
'%f' // Float format for the selected_price
],
[
'%s' // String format for quote_id
]
);
// Check for database errors
if ($result === false) {
wp_send_json_error([
'message' => 'Database update failed.',
'query_error' => $wpdb->last_error ?: 'No database error reported.',
], 500);
return;
}
// Respond with success
wp_send_json_success([
'message' => 'Selected price saved successfully.',
'selected_price' => $selected_price_value,
]);
}
// Register the AJAX handlers for logged-in and logged-out users
add_action('wp_ajax_nopriv_process_checkout', 'handle_process_checkout'); // For non-logged-in users
add_action('wp_ajax_process_checkout', 'handle_process_checkout'); // For logged-in usersHata kodu 400 aliyorum