Jump to content

Ajax jQuery vs. Vanilla JavaScript


Matze
 Share

Recommended Posts

Hi there,

I'm trying to get to work some AJAX call with vanilla Javascript, not jQuery.

Anything seems to work so far, but the !$config->ajax seems to be ignored.

To find out whats the problem by comparing both, jquery and plain javascipt, i built this template. commenting out //loadJquery(''); or loadVanilla(''); switches the two variants. (empty url variable means that the same pages will be loaded.)

The problem: the pure Javascript function ("loadVanilla") is loading the full page content into the dc-container, which is wrong. The jQuery function  ("loadJquery") only loads the part outside of the if(!$config->ajax): - which is as it should be. 

So - any help with this, what am i doing wrong?

Thanks a lot - Matze

<?php namespace ProcessWire;
if(!$config->ajax): ?>

(some static content)<br>
<a id="loadlink" href="#">load</a><br>

<?php endif; // end if not ajax ?>
<span id="dc-container">(dynamic content)</span>
<?php if(!$config->ajax): ?>


<script src="http://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>

var loadlink = document.getElementById('loadlink');

loadlink.addEventListener('click', function(event) {
  //loadJquery('');
  loadVanilla('');
  event.preventDefault()
});


function loadVanilla(url) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("dc-container").innerHTML = 'loaded: ' + this.responseText + (' (by vanilla javascript)');
    }
  };
  xhttp.open("POST", "", true);
  xhttp.send();
}

 
function loadJquery(url){ // Load content
  $.ajax({
      type: "POST",
      url: url,
      data: { ajax: true },
      success: function(data,status){
        pageData = data;
      }
  }).done(function(){ // when finished and successful
    document.getElementById("dc-container").innerHTML = 'loaded: ' + pageData + ' (by jquery ajax)';
  });
}


</script>

<?php endif; // end if not ajax ?>

 

Link to comment
Share on other sites

You need to add:

xhttp.setRequestHeader("X-Requested-With", "XMLHttpRequest");

This is something that jquery does automatically, but you have to do yourself with vanilla JS.

I think you may also need to add this inside your xhttp.onreadystatechange function.

xhttp.getAllResponseHeaders();

 

  • Like 6
Link to comment
Share on other sites

in the jquery function you can use this:

$("# dc-container").html("loaded:" + pageData + "(by jquery ajax)");

instead of

document.getElementById("dc-container").innerHTML = 'loaded:' + pageData + '(by jquery ajax)';

to be consistent if you already use the library

;)

Link to comment
Share on other sites

6 hours ago, Pixrael said:

to be consistent if you already use the library

;)

Well, yes indeed. But that was just for a quick result reporting. My main goal is not to use jQuery anymore and completely switch to good old JavaScript. Inspired by UIKit framework ?

Link to comment
Share on other sites

  • 1 year later...

I would like to add that by using vanilla JS only, one has to keep an eye on event listeners in order not to introduce memory leaks, and jQuery does remove "its own" listeners before disposing of a node, which is quite handy. The only issue with a helper like jQuery is that it keeps changing (because it keeps evolving) and it might be problematic to update possible other jQuery dependent components of a website when their new versions start to require different versions of jQuery. Yeah, dependency is always an issue but I do not think it is possible to eliminate it completely anyway.

Link to comment
Share on other sites

Imho the much more compelling reasoning against using jQuery is going up the abstraction ladder and using some library, which handles e.g. DOM manipulation for you and not going down the ladder to do everything in vanilla js. jQuery for one part is a great library if you really want to manually handle changing the DOM, but I much rather deal with templates and data then with the low level "making the DOM behave". What I never really liked is how ajax was bundled with jquery, as it really has nothing to do with the DOM at all. At the time it might have been about "we make things simply work cross-browser", but it could've been packaged more separately.

  • Like 1
Link to comment
Share on other sites

Maybe OT:

I have been thinking of using Dart or TypeScript to write my JS for me ?. Vanilla JS can be a pain at times. Using Dart or TypeScript, I can write in familiar OOP style (yes, I know about ES6, but that's another story) and have them transpile the code into JS.  For small projects it's probably not worth the hassle, but the strongly typed nature of Dart or TypeScript alone is compelling reason enough to steer away from vanilla JS if I can.

OK, I'll now crawl back under my rock...?

  • Like 3
Link to comment
Share on other sites

  • 11 months later...

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...