Geekzone: technology news, blogs, forums
Guest
Welcome Guest.
You haven't logged in yet. If you don't have an account you can register now.


chevrolux

4962 posts

Uber Geek
+1 received by user: 2638
Inactive user


#269813 9-Apr-2020 09:36
Send private message

So I'm taking this more relaxed time to play around a bit with some coding... basically learnt that javascript sucks (it makes no sense, you can't tell whats a object/variable/function/etc, its just confusing. PHP is waaay easier haha), but is crucial to pretty much any web app.

 

I have a form built using bootstrap styling, and I want to use the client-side validation styling bootstrap has built in. This was simple when submitting directly to PHP using their example here.

 

But in this instance, I don't want to reload the page, I want to submit the form via AJAX, and then load in some new HTML from that AJAX response.

 

So far, I have this....

 

 

 

$("#runAssesment").submit(function(event){
 event.preventDefault();
    // cancels the form submission
 var forms = document.getElementsByClassName('needs-validation');
 var validation = Array.prototype.filter.call(forms, function(form) {
  form.addEventListener('submit', function(event) {
   if (form.checkValidity() === false) {
    event.preventDefault();
    event.stopPropagation();
   }else {
      submitForm();
   }
   form.classList.add('was-validated');
  }, false);
 });
});

 

 

 

submitForm() is my AJAX request. This works fine without trying to do the validation check before hand so I thought it easiest to just leave it in a function.

 

The submit button is like this:

 

<button type="submit" class="btn btn-primary" id="runAssesment"><i class="far fa-save"></i> Submit</button>

 

Currently, it takes two clicks of the submit button for the "non validated" styling to load in to the form. If i don't have that "event.preventDefault();" right at the top the form submits immediately (through defaults, as no method/action is set).

 

Where am I going wrong?


Create new topic
SirHumphreyAppleby
2938 posts

Uber Geek
+1 received by user: 1860


  #2458019 9-Apr-2020 10:22
Send private message

I share your view of Javascript, although C is my language of choice for the backend.

 

At the risk of sounding stupid, is there a reason why you're adding events?

 

I am currently working on a contact form and mailing list subscriptions for for my Website. The only client-side validation I do is using the options provided by the <input> tags, however if I wanted to do more, I would simply do so before deciding to call .ajax(), and skip it if validation failed.

 

$(function() {
 $('#submit').click(function() {

 

 $("#submit").attr("disabled", true);
 $('#results').empty();
 var msg = {};
 msg.name = $('#name').val();
 msg.email = $('#email').val();
 msg.subject = $('#subject').val();
 msg.msg = $('#msg').val();

 

 $.ajax({
  async: true,
  type: 'POST',
  dataType: 'json',
  data: JSON.stringify(msg),
  url: '/contact',
  success: function(res) {

 

...

 

  },

 

  error: function(err) {
              $("#submit").attr("disabled", false);
  }
 });
});
}); 

 

 

 

 




chevrolux

4962 posts

Uber Geek
+1 received by user: 2638
Inactive user


  #2458036 9-Apr-2020 10:44
Send private message

At the risk of sounding stupid, is there a reason why you're adding events?

 

Because I have no idea what I'm doing and just grasping at straws from stack overflow posts!

 

I think I get what you're saying though... back to the drawing board


bigmacpaddy
72 posts

Master Geek
+1 received by user: 7

Subscriber

  #2458042 9-Apr-2020 10:56
Send private message

chevrolux:

 

$("#runAssesment").submit(function(event){

 

Where am I going wrong?

 

 

I'm just guessing but i would try not using the .submit() function when you click the button but use a .click() function. You can still use preventDefault so it doesn't submit and then do validation and submit the form.




ShinyChrome
1603 posts

Uber Geek
+1 received by user: 686

ID Verified
Trusted

  #2458048 9-Apr-2020 11:06
Send private message

For a start, I wouldn't use a type="submit" button or submit() operation; a submit operation is meant to be a whole client-server page load operation, so not helpful when you just want to submit an AJAX request. You will just be trying to fight the default operation all the way down.

 

I would just make a button like:

 

<button title="Submit form" type="button" id="runAssesment" class="btn btn-primary">Submit form</button>  

 

Then with an attached jQuery listener like:

 

$('runAssesment').on({

 

   click : function({

 

      $.ajax(... AJAX operation here like above in SirHumphreyAppleby's answer )

 

   })

 

});

 

Then for validation, you could attach a 'on' listener to each input element that validates based on user input using a 'keyup'/'keydown' or 'change' event for better UX; or just have a global validator that is called before your AJAX call above and checks all inputs.

 

Happy to provide examples by PM if needed, I had to mangle Bootstrap recently for making the validation work for a project.


chevrolux

4962 posts

Uber Geek
+1 received by user: 2638
Inactive user


  #2458085 9-Apr-2020 11:41
Send private message

Sorted.... all came down to when the 'was-validated' was applied to the form - that's what styles the fields red/green on validation.

 

And yea, that submit event was causing issues. Ended up put it in my '(document).ready' script with the following...

 

[code]

 

//submit initial risk assesment form
 $("#runAssesment").click(function(){
  var forms = document.getElementsByClassName('needs-validation');
  var validation = Array.prototype.filter.call(forms, function(form) {
   if (form.checkValidity() === false) {
    event.preventDefault();
    event.stopPropagation();
    form.classList.add('was-validated');
   } else {
    form.classList.add('was-validated');
    var form = $('#riskAssesmentForm')[0];
    var fd = new FormData(form);

 

    $.ajax({
     url: 'process_assesment.php',
     type: 'post',
     data: fd,
     contentType: false,
     processData: false,
     success: function(response){
      $('#assesModalContent').html(response);
     },
    });
   }
  }, false);
    });

 

[/code]


ShinyChrome
1603 posts

Uber Geek
+1 received by user: 686

ID Verified
Trusted

  #2458228 9-Apr-2020 13:30
Send private message

Sorry, I know you aren't asking for a full code review here, but curiosity has gotten the better of me, and I am seriously bored of the amount of non-dev support work I am doing at the moment for people that can't read the instructions...

 

I see you are using the bootstrap forms example; a lot of that is tailored for a standard form submit, so you can clean out some of the crunk from yo trunk. It's hard to tell from here what the intent of your code is, but unless you have multiple form elements you are submitting through multiple calls, you can probably get rid of all the array iteration. In that case, you would be better to grab the root form element by using a jQuery selector ie. var form = $('riskAssesmentForm')'; then do your validations on it. You can also get rid of the event calls as those only apply if you in scope of a 'submit' event.


 
 
 

Shop now on AliExpress (affiliate link).
chevrolux

4962 posts

Uber Geek
+1 received by user: 2638
Inactive user


  #2458359 9-Apr-2020 14:09
Send private message

Ahhh good to know! And certainly welcome any best practice advice.... can you tell I'm just copy/pasting haha!

 

Yea it's just a single form. So I don't need to do the getElementsByClassName and just select the form itself based on ID, and get rid of the event stuff.


Create new topic








Geekzone Live »

Try automatic live updates from Geekzone directly in your browser, without refreshing the page, with Geekzone Live now.



Are you subscribed to our RSS feed? You can download the latest headlines and summaries from our stories directly to your computer or smartphone by using a feed reader.