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.




4544 posts

Uber Geek

Trusted

#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
1290 posts

Uber Geek


  #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);
  }
 });
});
}); 

 

 

 

 




4544 posts

Uber Geek

Trusted

  #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


 
 
 
 


50 posts

Geek

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.


877 posts

Ultimate Geek

Trusted
Subscriber

  #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.




4544 posts

Uber Geek

Trusted

  #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]


877 posts

Ultimate Geek

Trusted
Subscriber

  #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.




4544 posts

Uber Geek

Trusted

  #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





Twitter and LinkedIn »



Follow us to receive Twitter updates when new discussions are posted in our forums:



Follow us to receive Twitter updates when news items and blogs are posted in our frontpage:



Follow us to receive Twitter updates when tech item prices are listed in our price comparison site:





News »

Chorus completes the build and commissioning of two new core Ethernet switches
Posted 8-Jul-2020 09:48


National Institute for Health Innovation develops treatment app for gambling
Posted 6-Jul-2020 16:25


Nokia 2.3 to be available in New Zealand
Posted 6-Jul-2020 12:30


Menulog change colours as parent company merges with Dutch food delivery service
Posted 2-Jul-2020 07:53


Techweek2020 goes digital to make it easier for Kiwis to connect and learn
Posted 2-Jul-2020 07:48


Catalyst Cloud launches new Solutions Hub to support their kiwi Partners and Customers
Posted 2-Jul-2020 07:44


Microsoft to help New Zealand job seekers acquire new digital skills needed for the COVID-19 economy
Posted 2-Jul-2020 07:41


Hewlett Packard Enterprise introduces new HPE GreenLake cloud services
Posted 24-Jun-2020 08:07


New cloud data protection services from Hewlett Packard Enterprise
Posted 24-Jun-2020 07:58


Hewlett Packard Enterprise unveils HPE Ezmeral, new software portfolio and brand
Posted 24-Jun-2020 07:10


Apple reveals new developer technologies to foster the next generation of apps
Posted 23-Jun-2020 15:30


Poly introduces solutions for Microsoft Teams Rooms
Posted 23-Jun-2020 15:14


Lenovo launches new ThinkPad P Series mobile workstations
Posted 23-Jun-2020 09:17


Lenovo brings Linux certification to ThinkPad and ThinkStation Workstation portfolio
Posted 23-Jun-2020 08:56


Apple introduces new features for iPhone iOS14 and iPadOS 14
Posted 23-Jun-2020 08:28



Geekzone Live »

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


Support Geekzone »

Our community of supporters help make Geekzone possible. Click the button below to join them.

Support Geezone on PressPatron



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.

Alternatively, you can receive a daily email with Geekzone updates.