I got a php code to run the ajax handler but something seems to be off, can you please help a little.
<?php
// Function to fetch prices based on the zip code
function get_price_based_on_zip_code($zipCode) {
// Include WordPress
define(‘WP_USE_THEMES’, false);
require_once(‘../../../wp-load.php’);
// Perform your query or logic here to fetch prices based on the provided zip code
// For example, you might query a custom post type or a custom database table
// Replace the code below with your actual logic
// Sample logic to fetch prices from a custom post type
$args = array(
‘post_type’ => ‘Prices’,
‘posts_per_page’ => 1,
‘meta_query’ => array(
array(
‘key’ => ‘zip_code’,
‘value’ => $zipCode,
)
)
);
$query = new WP_Query($args);
if ($query->have_posts()) {
$query->the_post();
$price = get_field(‘price’); // Assuming price is stored as a custom field
wp_reset_postdata();
return $price;
} else {
return false; // Return false if no price found for the given zip code
}
}
// Check if the zip code is provided
if (isset($_POST[‘zipCode’])) {
$zipCode = $_POST[‘zipCode’];
// Call the function to get the price based on the provided zip code
$price = get_price_based_on_zip_code($zipCode);
if ($price !== false) {
echo ‘<p>This is your price for ZIP code ‘ . $zipCode . ‘: $’ . $price . ‘</p>’;
} else {
echo ‘<p>No information available for the entered ZIP code.</p>’;
}
} else {
echo ‘<p>Invalid request.</p>’;
}
?>
​
[ad_2]
the code for the form
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>Price Checker</title>
</head>
<body>
<h2>Check Price by Zip Code</h2>
<form id=”priceForm”>
<label for=”zipCodeInput”>Enter Zip Code:</label>
<input type=”text” id=”zipCodeInput” name=”zipCodeInput” required>
<button type=”submit”>Check Price</button>
</form>
<div id=”priceResult”></div>
<script>
document.getElementById(‘priceForm’).addEventListener(‘submit’, function(event) {
event.preventDefault(); // Prevent the default form submission
var zipCode = document.getElementById(‘zipCodeInput’).value.trim();
if (zipCode) {
fetchPrice(zipCode); // Call function to fetch price
} else {
alert(‘Please enter a valid ZIP code.’);
}
});
function fetchPrice(zipCode) {
// AJAX request to fetch price based on zip code
fetch(‘ajax-handler.php’, {
method: ‘POST’,
headers: {
‘Content-Type’: ‘application/x-www-form-urlencoded’,
},
body: ‘zipCode=’ + encodeURIComponent(zipCode),
})
.then(response => {
if (!response.ok) {
throw new Error(‘Network response was not ok’);
}
return response.json();
})
.then(data => {
// Display price or error message
if (data.price) {
document.getElementById(‘priceResult’).innerHTML = ‘Price for ZIP code ‘ + zipCode + ‘: $’ + data.price;
} else if (data.error) {
document.getElementById(‘priceResult’).innerHTML = data.error;
}
})
.catch(error => {
console.error(‘There was a problem with the fetch operation:’, error);
});
}
</script>
</body>
</html>