32

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>
John
  • 433
  • 1
  • 5
  • 8

3 Answers3

47

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);
  });
Ivan
  • 34,531
  • 8
  • 55
  • 100
Gustavo Topete
  • 1,246
  • 1
  • 9
  • 15
23

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

A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
6

you can use build in fetch module for example

fetch('http://yourapi.com/data')
  .then(response => {
    console.log(response)
  });
Ivan
  • 34,531
  • 8
  • 55
  • 100
  • 2
    logging `response` is not really useful. You’d rather return `response.text()`, `response.json()` or something similar and log that in the next `then` call. – Sebastian Simon Jun 09 '18 at 16:50
  • response.text() and response.json() will not show full response object with status code and headers –  Jun 09 '18 at 16:52