JQuery submit form without page reload

I am not very familiar with jQuery. I am trying to create a form that will be sent in the background without reloading the page.

I have a hidden div that shows and hides the click, inside the div there is a form.

I have two problems:

1) If the form verification fails, the form is still submitted. I tried to put the verification and sending codes in the state if(validation == valid) { $.ajax.... } , but it does not work properly.

2) After submitting the form, the div is automatically hidden, so a successful message is not displayed.

Here is the code:

 $().ready(function() { // Validate the form when it is submitted, using validation plugin. var validator = $("#contactform").validate({ errorContainer: container, errorLabelContainer: $(), onkeyup: false, onclick: false, onfocusout: false, errorPlacement: function (error, element) { error.insertBefore(element); } }); }); $(function() { //This submits a form $('input[type=submit]').click(function() { $.ajax({ type: "POST", url: "contact.php", data: $("#contactform").serialize(), beforeSend: function() { $('#result').html('<img src="loading.gif" />'); }, success: function(data) { $('#result').html(data); } }) }) }) //This shows and hides div onclick $(document).ready(function(){ $(".slidingDiv").hide(); $(".show_hide").show(); $('.show_hide').click(function(){ $(".slidingDiv").slideToggle(); }); }); 
+10
source share
3 answers

Instead of binding to the click event ( input[type=submit] ), you should bind to the submit event for the form.

 $("form").on("submit", function (e) { e.preventDefault(); 

I am also not sure about validation. If it runs asynchronously, a callback is required. If it works synchronously, when does it start? It seems like it needs to be done when the form is submitted, if your validation plugin does not do it on its own:

 $("form").on("submit", function (e) { e.preventDefault(); if ($(this).validate(options)) { $.ajax 

Using e.preventDefault prevent a reboot and should allow your success div to display.

+22
source

1) Use event.preventDefault(); to save the form from submitting - http://api.jquery.com/event.preventDefault/

2) There is nothing in this script that could hide #result, but you can try $('#result').show() and see if that returns it back

+1
source

Check which version of jQuery you are using, because after jQuery 1.8.2 the "success" function from jQuery Ajax is deprecated.

Use e.preventDefault() to prevent the actual sending event.

+1
source

Source: https://habr.com/ru/post/955440/


All Articles