After confirming that your implementation is correct and functional, you can proceed by opening the developer tools of your browser, navigating to the network tab, running the provided code snippet below, and clicking the submit button. This action will trigger a request to the server, resulting in Safari displaying an output like:
e.g. [Error] Failed to load resource: the server responded with a status of 404 (Not Found) (petDetails.php, line 0)
. As expected, this error occurs because the server-side script
petDetails.php
is not found.
<form action="petDetails.php" id="animalInput">
<ul>
<li>
<label for="dogName">Dog Name:</label><input id="dogName" type="text" name="dogName" />
</li>
<li>
<label for="submit"></label><input id="submit" type="submit" value="Enter dog name" name="submit" />
</li>
</ul>
</form>
To achieve the same result using Ajax, you can follow these steps:
// Send data to backend via Ajax
function save_dog_name() {
// Create XMLHttpRequest Object
var http_handle = new XMLHttpRequest();
// Define data to be sent to the server
var data = 'dogName=' + document.getElementById("dogName").value;
// Open the connection
http_handle.open('POST', "petDetails.php", true);
// Specify urlencoded data in the request body
http_handle.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
// Handle response from the server
http_handle.onreadystatechange = function() {
if(http_handle.readyState == 4 && http_handle.status == 200) {
// Print response on success
console.log("Data received. Server response: " + http_handle.responseText);
} else {
// Print error message and response on failure
console.log("An error occurred. Server response: " + http_handle.status + " " + http_handle.statusText + " " + http_handle.responseText);
}
}
http_handle.send(data);
}
<ul>
<li>
<label for="dogName">Dog Name:</label><input id="dogName" type="text" name="dogName" />
</li>
<li>
<label for="submit"></label><button onclick="save_dog_name()">Enter dog name</button>
</li>
</ul>
You can enhance the design of your buttons using Bootstrap. Refer to: https://getbootstrap.com/docs/3.4/css/#buttons