I have a unique website where users can input a cost code, which is then submitted and POSTed to a page called 'process-cost-code.php'
. This page performs basic validation checks and saves the information to a database if everything is correct. The 'process-cost-code.php'
page then displays a brief message indicating whether the submission was successful or not.
To enhance user experience, I wanted to incorporate JavaScript and XMLHttpRequest
to submit this information without redirecting the user to another page. Instead, I aimed to display the responseText
in a designated 'feedback'
div on the current page.
Although I am relatively new to JavaScript and typically use Notepad for coding, I usually rely on alerts to show key details. Surprisingly, after successfully implementing the feature with the response displaying correctly in the feedback div, I decided to remove some of the alerts, resulting in the entire functionality breaking down. The responseText
appeared empty, even when I tried inserting "hello world" into the body of process-cost-code.php
.
Strangely, adding an alert right after the .send
method seemed to resolve the issue. However, upon removing the alert again, the response failed to appear at all. I also experimented with a wait
function after the response but saw no improvement in results.
Do you have any suggestions or ideas on what might be causing this inconsistency? Please see the code snippet below:
function submit_cost_code() {
var costCode = document.getElementById("cost-code").value;
var xmlhttp = new XMLHttpRequest();
var url = 'process-cost-code.php';
var params = 'cost-code=' + costCode;
xmlhttp.open('POST', url, true);
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlhttp.send(params);
alert("Why does it only work when I have this alert in place?");
document.getElementById("feedback").innerHTML = xmlhttp.responseText;
}