Matze

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

 

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.

xhttp.getAllResponseHeaders();

 

  • Like 4

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

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 awebcreature
      Hello there
      I need a field with realtime percent calculation (without page save)  with values from other fields in admin template. I think about jQuery with onChange methods on corresponding fields but this is not clear for me how to do this in module. Any help with some advice or example will be highly appreciated! 
      Thanks in advance! 
       
    • By FrancisChung
      Long but well written, detailed and informative article written by an Engineering Manager for Google Chrome about the true cost of Javascript and what you can do to alleviate some of that cost.
      Must read!

      https://medium.com/@addyosmani/the-cost-of-javascript-in-2018-7d8950fbb5d4
    • By louisstephens
      So I was going to build a todo tracking app for myself to test/broaden my knowledge of processwire, and so far it has been taxing 😓.  My Site structure is:
      - Project One - Phase One - Task - Task - Task - Phase Two - Task - Task - Task So far it was pretty easy, I can easily foreach through the Project and get the phases with their tasks. However, it gets a bit muddled when I have more than one project as I was trying to have a dashboard where the content switches out to the selected project as opposed to accessing each project via their own url. How would yall handle this?
      My next hurdle is each task has a select field (for project status) that I want to update via ajax (for the smooth transitioning).
      Scenario: You finish a task, change the option from "new" to "completed", and an onclick changes the status drop down background to green (which I have working), but then posts/saves a field on the backend to the new option.
       
      I have a page called "Actions" set up with url segments using
      if ($config->ajax && $input->urlSegment1 == 'change-status') { //save update field on admin } However, I am a little fuzzy on how to actually pass the current page along with the new selected status to actually update the page (task). I guess I am not very far into my endeavor. Any help would be greatly appreciated.
    • By louisstephens
      So I have a project where multiple pages are sending POST data to 1 single template page.  All was working well (well, at least with one ajax post), but now I have hit a stumbling block. I figured  the "best" way to handle the request were to use url segments and then use the following in the status page:
      if ($config->ajax && $input->urlSegment1 == 'add-bookmark') { // some code here } However, this doesnt seem to really work (as I assume the the request isnt being posted to /status/ but rather to /status/add-bookmark/). What is the best way to actually handle this?
    • By louisstephens
      Currently, I have a page set up listing all child pages using a foreach loop and outputting some information (thus far, it is all gravy). However, I ran into a slight problem. I have a "button" on each item being rendered that when clicked needs to send the page id to another page for processing via ajax. I thought I could just save the item id like :
      <?php $itemId = $item->id; ?> And then encoding it below in my javascript:
      var itemId = <?php echo json_encode($itemId); ?>; var data = { itemId: itemId, }; $.ajax({ type: "POST", url: "/intra/status/", data: data, success: function(){ console.log(itemId); } }); However, it is only posting the last page's id rendered by the foreach. Have I just overlooked something simple on this?