How can I remove the need to download a full jquery library when all I want to use is AJAX. Is there a smaller file that focuses on AJAX or is there a Vanilla Javascript version of this code?
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$.ajax({
type: 'POST',
url: 'cookies.php',
success: function(data) {
alert(data);
}
});
});
});
</script>
The Fetch API, is a newer and convenient way to make Ajax calls. There are many frameworks that have already wrapped AJAX codes into short snippets. One example would be Axios Js. Ajax is gradually being replaced by functions within JavaScript frameworks and the official Fetch API Standard.
Javascript provides client-side support whereas AJAX provides server-side support by exchanging data with the server. Javascript is applicable when there is an HTML and AJAX functionality that takes data using XMLHttpRequest. Javascript is a well-known programming language whereas AJAX is not a programming language.
AJAX is still relevant and very popular, but how you write it may change based on what libraries or frameworks are in the project. I almost never use the "raw" JavaScript way of writing it because jQuery makes it easier and is almost always already loaded into a project I'm working on.
You can use the fetch
function.
Here is an example from the link:
fetch('http://example.com/movies.json')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(myJson);
});
You can try with XMLHttpRequest like below.
<!DOCTYPE html>
<html>
<body>
<h2>The XMLHttpRequest Object</h2>
<button type="button" onclick="loadDoc()">Request data</button>
<p id="demo"></p>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("POST", "cookies.php", true);
xhttp.send();
}
</script>
</body>
</html>
Demo: https://www.w3schools.com/js/tryit.asp?filename=tryjs_ajax_first
Reference: https://www.w3schools.com/js/js_ajax_http_send.asp
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With