JS Validate plugin prevent submit form - javascript

Hello this is my code i am trying to prevent form submit when button is clicked, and load ajax. but form continue to submits, I tried to add preventDefault, and onsubmit false parametar but no luck. Is there anyone to help me to fix this problem
$(function() {
$('#submitTest').click(function(e){
var form_test = $('#test_forma').serialize();
e.preventDefault;
jQuery.extend(jQuery.validator.messages, {
required: "Odgovor je obavezan",
});
$( "#test_forma" ).validate({
onsubmit: false,
submitHandler: function(form) {
form.preventDefault();
// e.preventDefault();
if(('#test_forma').valid()) {
$.ajax({
type: "POST",
url: " <?php echo base_url().'home/test';?> ",
data: {form_test:form_test},
beforeSend: function() {
// setting a timeout
$('#g_upozorenje').html('<img src="<?php echo base_url().'images/loading.gif';?>"/>');
},
success: function(response) {
$.each(response.answers, function(i, item){
// if(('#test_odgovori_' + i).val()) == response[i].IdPitanja)
if(response.answers[i].provera ==1) {
$('#test_odgovori_'+response.answers[i].Id).css('color','green');
} else {
$('#test_odgovori_'+response.answers[i].Id ).css('color','green');
$('.test_odgovori_'+response.answers[i].IdPitanja+':checked').next().css('color','red');
}
$('#procenat').html('Odgovorili ste tačno na '+response.result + '% pitanja')
$('#rezultati').dialog();
});
}
});
}
}
});
});
});

You need to use preventDefault as a method and D is uppercase
e.preventDefault();
http://api.jquery.com/event.preventdefault/

You've got to return false;.
Take a look at this example:
<form onsubmit="javascript:doSomething();return false;">
<input type="submit" value="click me">
</form>
Or look here.

e.preventDefault(); is written correctly with brackets, and I think they should be the first after the opening brackets. And try to fire the preventDefault on the form submit and not the click on the button. There are several possibilities to submit a form without pressing the button, you wouldn't handle now.

You need to stop the form from submitting, not preventing default action of the button.
Instead target the form's submit event:
$("form").submit(function (e) {
e.preventDefault(); // this will prevent from submitting the form.
...
Or even use jQuery's on event handler for better performance:
$("form").on('submit', function (e) {
e.preventDefault(); // this will prevent from submitting the form.
...

Related

Clearing a form and closing the div after successful post

I have a script that sends my form via php-ajax. It does return success but what I need it to do when it has been successful is clear all the form data and close the div and load another one. I have tried many different ways to clear form and close div but they just seem to stop it working totally. The id of the div to close is '5box' The working script that i need to add these to is :
$(document).ready(function() {
$('#btn-finish').on('click', function() {
// Add text 'loading...' right after clicking on the submit button.
$('.output_message').text('Processing...');
var form = $(this);
$.ajax({
url: form.attr('action'),
method: form.attr('method'),
data: form.serialize(),
success: function(result){
if (result == 'success'){
$('.output_message').text('Message Sent!');
} else {
$('.output_message').text('Error Sending email!');
}
}
});
// Prevent default submission of the form after clicking on the submit button.
return false;
});
});
Any ideas would be appreciated
To clear the form you can call the reset() method of the underlying Element. I'm not sure what you mean by 'close the div', but you can call hide() to make it disappear. Try this:
success: function(result) {
if (result == 'success') {
$('.output_message').text('Message Sent!');
form[0].reset();
$('#5box').hide();
} else {
$('.output_message').text('Error Sending email!');
}
}
Also note that it would be much better practice to return JSON from the AJAX call. You can then have a boolean flag to show the state of the request.
Update
<button name ='send' value="Send" type='submit' class='btn btn-primary'>Finish</button>
Given that is the code of your button there is another issue - you're not preventing the form from being submit, hence the AJAX request is cancelled. To do this, hook to the submit event of the form instead of the click of the button. From there you can call e.preventDefault() to stop form submission. Try this:
<script>
$(function() {
$('form').on('submit', function(e) {
e.preventDefault();
$('.output_message').text('Processing...');
var form = $(this);
$.ajax({
url: form.attr('action'),
method: form.attr('method'),
data: form.serialize(),
success: function(result) {
if (result == 'success') {
$('.output_message').text('Message Sent!');
form[0].reset();
$('#5box').hide();
} else {
$('.output_message').text('Error Sending email!');
}
}
});
});
});
</script>
Note I used a generic 'form' selector above. You can change that to a class or id selector on the form as required.
For clearing form fields
$("input[type=text], textarea").val("");
cheers
you can also use Triggers as well
$('#form_id').trigger("reset");

jQuery preventdefault submit form doesn't work when submitting form through js function?

I have this basic form:
<form id="myForm" name="myForm" action="index.php" method="post">
<input type="submit" value="Submit" />
</form>
Then my jQuery to attach submit event:
$( document ).ready(function() {
var frm = $('#myForm');
frm.submit(function (ev) {
ev.preventDefault();
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert('ok');
}
});
});
});
When I press the submit button it works fine, I get the alert 'ok'.
But if I change the submit button to an actual button then add an onclick function through javascript, like this:
<input type="button" value="Submit" onclick="submitF(this.form);" />
JS:
function submitF(form) {
form.submit();
}
My jQuery event doesn't trigger, the form submits like it normally would.
If I'm attaching my jQuery function to the form submit event, why doesn't it trigger when javascript submits the form?
It does this because jQuery does not prevent the native submit trigger in javascript.
This is done so a form submit can be prevented, and then the form can be submitted programatically later, for instance
$('form').on('submit', function(e) {
e.preventDefault():
// do stuff
// then submit form
this.submit(); // does not trigger this event handler but submits the form instead
});
If you want to trigger the jQuery event handler, and prevent the form submit, do
function submitF(form) {
$(form).submit();
}

Ajax request being submitted multiple times

Im working on fixing some validation to my forms. The validation works, problem is that when no validation error occur, the form submits as many times the user tried to submit. It is like the requests stacks up on a pile.
Forms has this submit button that calls my ajax function create_new_stuff
<input id='submitButton' onclick='create_new_stuff()' name='submit' type='submit' value='create' />
The function
function create_new_stuff(){
$("#createForm").submit(function(event){
event.preventDefault();
event.returnValue = false;
var input_value = $("#createValue").val();
if(input_value === "" || null){
console.log("Wrong input value");
return;
}
else{
var request;
var $form = $(this);
var serializedData = $form.serialize();
request = $.ajax({
url: "/new_stuff.php",
type: "post",
data: serializedData
});
// callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
console.log("Stuff created!", response);
create_new_stuff_form();
var successDiv = $("<div class='success'>Stuff was created</div>");
$("#responseMessages").html(successDiv);
});
// callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
console.error(
"The following error occured: "+
textStatus, errorThrown
);
});
}
});
}
instead of adding onclick event to submit button, add onsubmit event to form.
<form onsubmit= 'create_new_stuff()'>
</form>
<input id='submitButton' onclick='return create_new_stuff()' name='submit' type='submit' value='create' />
And return false when you don't want to submit the form from your javascript function.
Change button type submit to button or change onclick to onsubmit
Prevents the event from bubbling up by:
event.stopPropagation();
Every time you click on Submit button the onclick calls the create_new_stuff() method to do the required stuff. If you think to do this on form submit or button click both shall show the same behaviour. You can try something like this:
HTML
<label for="formelement">Enter Value Here:</label>
<input type="text" id="formelement" name="formelement">
<input type="submit" id="submitbutton" value="Submit">
JS
$("#submitbutton").on('click', function(e) {
e.preventDefault();
$('#submitbutton').attr('disabled',true);
var x = $("#formelement").val();
if(x=="" || null)
{
console.log("Wrong Input..!!");
return;
}
else {
console.log("Hello" + " " +x);
}
});
Working Demo : DEMO
And you can put a loader here to show server action being done.!!!
I think the best solution specifically for the situation when you are trying to use same code for different forms and you have to use separate function for form submission instead of direct submission
$("#this_is_form_id_string").on('submit', function(e){ });
you can do the trick
function submit_forms(form_id){
var avoid_duplicate_form_submission = 0;
$("#"+form_id).submit(function(e){
e.preventDefault();
avoid_duplicate_form_submission++;
if(avoid_duplicate_form_submission === 1){
// All your code....
}
});
}

CodeIgniter Javascript form submission

I would first want to say that I am very new to javascript and jQuery.
Its a very silly and simple problem I suppose, and I am aware there are plenty of questions on this, and I did try all of them. Though I cant seem to solve my problem.
I have an input field and a submit button. On clicking submit I would like to save the content of the input filed into the database, and continue to remain in the same page with content on page as is.
My Javascript code is as follows:
<script type="text/javascript">
$(document).ready(function()
{
$('#submit').submit(function(e)
{
e.preventDefault();
var msg = $('#uname').val();
$.post("c_test/test_submit", {uname: msg}, function(r) {
console.log(r);
});
});
});
</script>
And my html code as follows ( I use codeigniter):
$this->load->helper('form');
echo form_open();
$data =array ('name'=>'uname','id'=>'uname');
echo form_input($data) . '<br />';
$data=array('name'=>'submit','id'=>'submit','value'=>'Submit');
echo form_submit($data);
echo form_close();
I would be very grateful if anyone could point out my stupidity. Thanks!
You are using
$('#submit').submit(function(e){ ... });
In this case submit is the button/input's id and it has no such an event like submit, instead you can use click event, like
$('#submit').click(function(e){ ... });
or
$('#submit').on('click', function(e){ ... });
Otherwise, you can change the following line
echo form_open();
to
echo form_open('c_test/test_submit', array('id' => 'myform'));
and instead of
$('#submit').click(function(e){ ... });
you can use
$('#myform').submit(function(e){
e.preventDefault();
var msg = $('#uname').val();
var url=$(this).attr('action');
$.post(url, {uname: msg}, function(r) {
console.log(r);
});
});
or
$('#myform').on('submit', function(e){
e.preventDefault();
var msg = $('#uname').val();
var url=$(this).attr('action');
$.post(url, {uname: msg}, function(r) {
console.log(r);
});
});
It seems like the element with an id of "submit" is the submit button for the form - <input type="submit">. However, the submit event is fired by the form, not the submit button, so your bound event handler won't fire.
Either move the "submit" id onto the form, or change the selector when binding the submit event handler:
$('form').submit(function(e) {
// handle submit event from the form
});
You have to do it like this:
<?php
$this->load->helper('form');
echo form_open('', array( 'id' => 'myform'));
..
and:
$('#myform').submit(function(e)
{
e.preventDefault();
var msg = $('#uname').val();
$.post("c_test/test_submit", {uname: msg}, function(r) {
console.log(r);
});
return false;
});
The submit event always goes to the form and not to the form button.
perhaps like this:
$data=array('name'=>'submit','id'=>'submit','value'=>'Submit','onsubmit'=>'return false;');
This will stop the form from posting which will in turn stop the page from refreshing. However, it will require that you submit the form via ajax.

using jquery to make ajax call and update element on form submit

Here is my html form
<div id=create>
<form action=index.php method=get id=createform>
<input type=text name=urlbox class=urlbox>
<input type=submit id=createurl class=button value=go>
</form>
</div>
<div id=box>
<input type=text id=generated value="your url will appear here">
</div>
Here is the javascript im trying to use to accomplish this;
$(function () {
$("#createurl").click(function () {
var urlbox = $(".urlbox").val();
var dataString = 'url=' + urlbox;
if (urlbox == '') {
alert('Must Enter a URL');
}else{
$("#generated").html('one moment...');
$.ajax({
type: "GET",
url: "api-create.php",
data: dataString,
cache: false,
success: function (html) {
$("#generated").prepend(html);
}
});
}return false;
});
});
when i click the submit button, nothing happens, no errors, and the return data from api-create.php isnt shown.
the idea is that the new data from that php file will replace the value of the textbox in the #box div.
i am using google's jquery, and the php file works when manually doing the get request, so ive narrowed it down to this
Because you're binding to the submit click instead of the form's submit.. try this instead:
$('#createForm').submit(function() {
// your function stuff...
return false; // don't submit the form
});
Dan's answer should fix it.
However, if #createurl is not a submit/input button, and is a link styled with css etc., you can do this:
$('#createurl').click(function () {
$('#createForm').submit();
});
$('#createForm').submit(function () {
// all your function calls upon submit
});
There is great jQuery plugin called jQuery Form Plugin. All you have to do is just:
$('#createform').ajaxForm(
target: '#generated'
});

Categories