33

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>
1

3 Answers 3

56

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);
  });
Sign up to request clarification or add additional context in comments.

1 Comment

fetch is the vanilla version of jquery.ajax, I don't see whats the problem with that, what I did wrong??
25

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

Comments

6

you can use build in fetch module for example

fetch('http://yourapi.com/data')
  .then(response => {
    console.log(response)
  });

2 Comments

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.
response.text() and response.json() will not show full response object with status code and headers

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.