Home > Software design >  Why javascript doesn't execute the querySelector inside AJAX?
Why javascript doesn't execute the querySelector inside AJAX?

Time:12-04

I am trying to handle an HTML part inside the ajax success:function(data){} but for some reason the code won't execute when I am calling it. Below is the code I tried:

$.ajax({
  url:"../new/php/posts.php",
  method:"POST",
  data:{limit:limit, start:start},
  cache:false,
  success:function(data)
  {
   //$('#activitystream').append(data);
   var data_parse = JSON.parse(data);
   for (var i in data_parse){
        var divData = '<a id="default-like-' data_parse[i].ID '" href="#/"  style="display: none;">\n' 
        '<span>Like</span>\n' 
        '</a>';
                  $('#activitystream').append(divData);
   }
   if(data == '') {
     //Do nothing
     action = 'active';
   }else {
     $('#activitystream-loading').css("display", "block");
       action = 'inactive';
       console.log(action);
       console.log(data);
          var els1 = document.querySelectorAll(".post__action--reaction");
          for (var x = 0; x < els.length; x  ){
            alert("Hey there")
            els1[x].style.display = 'block';
          }
  }
 }
 });

So, I also tried two ways. First of all, I tried to execute the code inside the complete:function(){} of AJAX and secondly, I tried to add the code inside this window.onload = function(){} but still nothing happening. There is not even any errors in the console, it just shows nothing. Do you know how can I handle the generated html part? Thanks in advance!

CodePudding user response:

One possible reason why your code is not executing as expected is that you are using the wrong variable name in the for loop. In the line:

for (var x = 0; x < els.length; x  ){

you are using the variable "els" instead of "els1". This might be causing the loop to not execute at all, thus leading to no output.

Try changing the variable name in the for loop to match the variable name used earlier in the code, like this:

for (var x = 0; x < els1.length; x  ){

This should fix the issue and allow your code to execute properly.

  • Related