Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vanilla Javascript version of AJAX [duplicate]

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>
like image 222
John Avatar asked Jun 09 '18 16:06

John


People also ask

What is the replacement of AJAX?

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.

Is AJAX similar to JavaScript?

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.

Is JavaScript AJAX outdated?

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.


2 Answers

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);
  });
like image 72
Gustavo Topete Avatar answered Sep 19 '22 19:09

Gustavo Topete


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

like image 28
Always Sunny Avatar answered Sep 18 '22 19:09

Always Sunny