Jump to content

Ajax jQuery vs. Vanilla JavaScript

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>

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

loadlink.addEventListener('click', function(event) {

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);

function loadJquery(url){ // Load content
      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)';


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


Share this post

Link to post
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.



  • Like 5

Share this post

Link to post
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


Share this post

Link to post
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 😏

Share this post

Link to post
Share on other sites

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.

Share this post

Link to post
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

Share this post

Link to post
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

Share this post

Link to post
Share on other sites

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

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By Majesrse
      Hey i have a problem with the code:
      $('a').click(function(link) { link.preventDefault(); location = this.href; $('body').fadeOut('slow', open); }); function more() { window.location = location; } It's writen in Jquery but i will convert it to vanilla js. Can somone help me with it?
    • By CareerTeam GmbH
      Hi there,
      We are an executive search agency based in Germany looking for a freelancer (2-5 days per week) supporting us with the development and design of our websites. The position will be located in Hamburg, Germany and it would be great if you are on short call. German language knowledge is mandatory. 
      You can reach me via email jobs@careerteam.de.
      Thank you!
    • By michelangelo
      Hello there,
      I am building my website, which has a dozen projects with 10 images each. Basically, I need a filtering system but built in the most efficient and user-friendly way. You can see below that the images flow sideways so being hidden, JS lazy loading was a good tool, but I just wanted to try AJAX. Is it fit for this purpose or it's more for dynamic content?

    • By Orkun
      Hi Guys
      I needed to add extended functionalities for the InputfieldDatetime Module (module is from processwire version 2.7.3) because of a Request of Customer.
      So I duplicated the module and placed it under /site/modules/.
      I have added 3 new Settings to the InputfieldDatetime Module.
      1. Day Restriction - Restrict different days based on weekdays selection (e.g. saturday, sunday) - WORKING

      2. Time Slots - Define Time slots based on custom Integer Value (max is 60 for 1 hour) - WORKING

      3. Time Range Rules per Weekday - Define a minTime and MaxTime per Weekday (e.g. Opening Hours of a Restaurant) - NOT WORKING PROPERLY

      The Problem
      Time Slots and Day Restriction working fine so far. But the Time Range Rules per Weekday doesn't work right.
      What should happen is, that when you click on a date, it should update the minTime and maxTime of the Time Select.
      But the change on the select only happens if you select a date 2 times or when you select a date 1 time and then close the datepicker and reopen it again.
      The time select doesn't get change when you select a date 1 time and don't close the picker.
      Here is the whole extended InputfieldDatetime Module.
      The Files that I have changed:
      InputfieldDatetime.module InputfieldDatetime.js jquery-ui-timepicker-addon.js (https://trentrichardson.com/examples/timepicker/) - updated it to the newest version, because minTime and maxTime Option was only available in the new version  
      Thats the Part of the JS that is not working correctly:
      if(datetimerules && datetimerules.length){ options.onSelect = function(date, inst) { var day = $(this).datetimepicker("getDate").getDay(); day = day.toString(); var mintime = $(this).attr('data-weekday'+day+'-mintime'); var maxtime = $(this).attr('data-weekday'+day+'-maxtime'); console.log("weekday: "+day); console.log("minTime: "+mintime); console.log("maxTime: "+maxtime); var optionsAll = $(this).datetimepicker( "option", "all" ); optionsAll.minTime = mintime; optionsAll.maxTime = maxtime; $(this).datetimepicker('destroy'); $(this).datetimepicker(optionsAll); $(this).datetimepicker('refresh'); //$.datepicker._selectDate($(this).attr("id"),date); //$.datepicker._base_getDateDatepicker(); // var inst = $.datepicker._getInst($(this)); // $.datepicker._updateDatepicker(inst); /*$(this).datetimepicker('destroy'); InputfieldDatetimeDatepicker($(this), mintime, maxtime); $(this).datetimepicker('refresh'); */ // $(this).datetimepicker('option', {minTime: mintime, maxTime: maxtime}); } } Can you have a look and find out what the Problem is?
      Kind Regards
  • Create New...