I’m working on a WordPress project where I’ve created a form to submit data to an external API using JavaScript. The form appears to be structured correctly, but it’s not making the expected API request when I click the “Submit” button. There’s no error message in the frontend, but I suspect something is going wrong.
Below is my form code with the JavaScript function that handles the form submission and makes the API request. I’ve tried to ensure that the data is sanitized and that the request is set up correctly. However, I can’t identify the source of the problem.
// WordPress Shortcode Function
function availability_form() {
ob_start();
$hotel_code = get_field('hotel_code');
$hotel_cityname = get_field('cityname');
global $cities;
global $hotels;
?>
<div class="availability-form-container">
<form class="availability-form desktopavail" onSubmit="return false;">
<div>
<label>City</label>
<select id="form-city" class="cityname" required name="city">
<option>Select City</option>
<?php foreach ($cities as $row) { ?>
<option value="<?php echo $row; ?>" <?php if ($hotel_cityname == $row) { echo 'selected'; } ?>>
<?php echo $row; ?>
</option>
<?php } ?>
</select>
</div>
<!-- Additional form fields -->
<div>
<label for="" style="opacity: 0;">Submit</label>
<button type="submit" onClick="handleFormSubmission()">View Price</button>
</div>
</form>
</div>
<script>
function handleFormSubmission() {
var city = document.getElementById('form-city').value;
// Collect other form data
// API endpoint and request data
var apiUrl = 'https://malc-integration-api-stage.thecapital.co.za/api/ChatBot/createBookingLink';
var requestData = {
city: city,
// Additional data
};
var args = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_BEARER_TOKEN',
},
body: JSON.stringify(requestData),
};
fetch(apiUrl, args)
.then(response => response.json())
.then(data => {
console.log('Form submitted!', data);
})
.catch(error => {
console.error('API request failed:', error);
});
}
</script>
<?php
return ob_get_clean();
}
Checked the browser console for errors (no errors were reported).
Verified that the form data is being collected correctly.
Ensured that the API endpoint and headers are correct.
Added error handling in the fetch call to capture any errors during the API request.
Amna Akhtar is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.