Jump to content
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 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

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By louisstephens
      I have been messing around with creating pages from ajax requests, and it has gone swimmingly thus far. However, I am really struggling with creating a page and saving an image via ajax. 
      The form:
      <form action="./" role="form" method="post" enctype="multipart/form-data"> <div> <input type="text" id="preview" name="preview" placeholder="Image Title"> </div> <div> <input type="file" id="preview-name" name="preview-name"> </div> <div> <select id="select-tags" name="select-tags"> <?php $tags = $pages->find("template=tag"); ?> <option value="">Select Your Tags</option> <?php foreach ($tags as $tag) : ?> <option value="<?= $tag->name; ?>"><?= $tag->name; ?></option> <?php endforeach; ?> </select> </div> <div> <button type="button" id="submit-preview" name="submit" class="">Upload Images</button> </div> </form>  
      The ajax in my home template:
      $('#submit-preview').click(function(e) { e.preventDefault(); title = $("#preview").val(); image = $("input[name=preview-name]"); console.log(title); console.log(image); data = { title: title, image: image //not sure if this is actually needed }; $.ajax({ type: 'POST', data: data, url: '/development/upload-preview/', success: function(data) { console.log("Woo"); }, error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); } }); }); And finally in my ajax template:
      $imagePath = $config->paths->assets . "files/pdfs/"; //was from an older iteration $title = $sanitizer->text($_POST['title']); $image = $sanitizer->text($_POST['image']); $p = new Page(); $p->template = "preview"; $p->parent = $pages->get("/previews/"); $p->name = $title; $p->title = $title; $p->save(); $p->setOutputFormatting(false); $u = new WireUpload('preview_image'); $u->setMaxFiles(1); $u->setOverwrite(false); $u->setDestinationPath($p->preview_image->path()); $u->setValidExtensions(array('jpg', 'jpeg', 'gif', 'png', 'pdf')); foreach($u->execute() as $filename) { $p->preview_image->add($filename); } $p->save(); I can complete the file upload but just using a simple post to the same page and it it works well, but I was really trying to work out the ajax on this so I could utilize some modals for success on creation (and to keep my templates a little cleaner). When I do run the code I have, a new/blank folder is created under assets, and a new page is created with the correct title entered. However, no image is being processed. I do get a 200 status in my console. I have searched google for help, but everything seems to be slightly off from my needs. If anyone could help point me in the right direction I would greatly appreciate it. 
    • By louisstephens
      So I am using ajax to upload an image, but I am getting the error "Method WireUpload:: save does not exist or is not callable". I am not quite sure how to go about fixing this (at the moment).
      elseif($config->ajax && $input->urlSegment1 == "upload-preview") { $u = $config->paths->assets . "files/pdfs/"; $title = $sanitizer->text($_POST['title']); $p = new Page(); $p->template = "preview"; $p->parent = $pages->get("/previews/"); $p->name = $title; $p->title = $title; $p->save(); $p->setOutputFormatting(false); $u = new WireUpload('preview_image'); $u->setMaxFiles(1); $u->setOverwrite(false); $u->setDestinationPath($p->preview_image->path()); $u->setValidExtensions(array('jpg', 'jpeg', 'gif', 'png', 'pdf')); foreach($u->execute() as $filename) { $p->preview_image->add($filename); } $u->save(); } I compared my code to something I did previously (though previously I just posted to the current template file, not through ajax) which works, but this doesnt seem to be working. I have the _init.php file prepending as well. Does anyone have any ideas of what might be happening?
    • By Brian Scramlin
      I just wanted to share that I added an AJAX-powered gallery to an artist website that I developed and host: https://jackpinecreations.com/gallery/

      There were two things that frustrated me about creating this. Perhaps you can show me a better way.
      1. After creating my processing script, which I placed under /templates/scripts/get-items.php, I realized that I would get a 403, due to ProcessWire's routing and security. This forced me to have to create a template and page for this little script. This was frustrating simply because it seemed unnecessarily confusing. But worse, see #2.
      2. I usually use config.php to prepend and append each of my templates with a head.inc and foot.inc, which keeps my templates easy to use and I don't have to go and use the GUI to do so on each template separately. However, since I realized I needed to create a new template and page so as to access it, whenever I sent POST params to it, I would get the header and footer along with it!!! I could find no workarounds and had to remove the pre/append calls in config.php and use the GUI on each template individually.  
      Code Below if you're interested:
      HTML and JavaScript (forgive my sad JavaScript skills, I know this can be tightened up)
      <!-- Begin Grid --> <div class="container mt-4"> <div id="gallery" class="row"> <?php foreach ($page->children("limit=9") as $child): ?> <div class="col-6 col-md-4 gallery-item"> <a href="<?= $child->url ?>" title="View <?= $child->title ?>"> <img class="gallery-item" src="<?= $child->item_featured_image->size(640, 640)->url ?>" alt="<?= $child->title ?> Image"> </a> </div> <?php endforeach; ?> </div> </div> <!-- End Grid --> <div class="center-block text-center"> <button id="get-more-items" type="button" name="get-more-items" class="btn-vintage">Load More</button> </div> <script type="text/javascript"> var buttonGetItems = document.getElementById("get-more-items"); var indexStart = 0; buttonGetItems.addEventListener("click", function() { indexStart += 9; $.ajax({ url: '<?= $pages->get(1186)->url ?>', type: "POST", dataType:'json', // add json datatype to get json data: ({page_id: <?= $page->id ?>, index_start: indexStart}), success: function(data){ console.log(data); if (data[1]) { //for each element, append it. $.each(data, function(key, value) { $("#gallery").append(value); }); } else { $("#get-more-items").after('<p class="center-block text-center">There are no more items to load.</p>'); $("#get-more-items").remove(); } } }); }); </script> Processing Script
      <?php $items_array = []; $i = 0; foreach ($pages->get($input->post->page_id)->children->slice($input->post->index_start, 9) as $child) { $i++; $items_array[$i] = "<div class='col-6 col-md-4 gallery-item'> <a href='$child->url' title='View $child->title'> <img src='{$child->item_featured_image->size(640,640)->url}' alt='$child->title Image'> </a> </div>"; } echo json_encode($items_array); I love ProcessWire for hundreds of reasons, but I've been using AJAX more and more, and I'm not liking having to create templates to access scripts. 
      Any advice?
    • By celfred
      Hello,
      I'm facing a weird issue here. I have a page loaded with this code inside (my comments in line ends) :

      if ($session->allPlayers) { // Set in a head.inc file. I have also a $session->set('allTeams', $allTeams); in my head.inc   $allPlayers = $session->allPlayers; } else {   $allPlayers = getAllPlayers($user, false);   $session->set('allPlayers', $allPlayers); } bd($session->getAll()); // HERE, I get a number of 11 variables which is what I expect In the same page, I have a link pointing to ajaxContent.php that loads stuff via Ajax.
      I just write this in my ajaxContent.php to test :

      bd($session->getAll()); // HERE, I get only 9 variables. All my newly set $session variables ($allTeams and $allPlayers) are not conveyed to ajaxContent.php ??? Would you have any idea why is that ??? Another thing : I have a $session->headMenu set in my head.inc, and this one works fine. I can retrieve it in my ajaxContent.php page.
      I've tried cleaning all caches but it doesn't change anything 😞 
      At first, I expected it to be a 15-minute update to my site... It turns out to be a 2-hour issue and I'm still  stuck.
      Thanks for your ideas ! 
×
×
  • Create New...