Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

show and Hide loading with Ajax / PHP

I try to do something basic but i block.

I want to add a class to a div for loading when i click on "GO" and remove the class when i get the answer.

My code is :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 $.ajax({
          url: "/send_email",
          type: "POST",
          data: $('form').serialize(),
          beforeSend: function() {
           $('div.loading').classList.add('d-block');
          },
          })
          .done(function(response) {
            $('div.loading').classList.remove('d-block')
            $('div.message').html(response);
          });   
      return false;
  };

The HTML is :

<div class="loading">Loading</div>

What im doig wrong ?

Actualy the page reload and in the console i get:
Cannot read properties of undefined (reading ‘add’)

i try to find my div seperatly and i get it !

I want to show and hide the loader

>Solution :

You’re mixing up jQuery code and non-jQuery code. You can use .toggleClass() instead:

$('div.loading').toggleClass('d-block');

classList is part of the element itself, not the jQuery object. Which you can access from jQuery:

$('div.loading').get(0).classList.add('d-block');

But it doesn’t make much sense to do so. Since you’re already using jQuery, you might as well remain consistent with that.


Actualy the page reload

That sounds like a separate problem entirely, and one that exists outside of the code shown. This may be helpful, but all we can do is guess since the code shown doesn’t demonstrate this specific problem.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading