How to prevent auto form submit - javascript

I have the following input box which takes input from barcode scanner.
<form class="m-form m-form--fit m-form--label-align-right" method="post" action="{{ url('updateInvoice') }}" id="invoice_update">
<div class="form-group m-form__group">
<label for="exampleInputEmail1">Search by item name or barcode</label>
<input type="text" autofocus class="form-control m-input" id="productSearch" placeholder="Item name">
</div>
<button type="submit" name="pdf" class="btn btn-success">Update & print
</button>
</form>
After getting the input from barcode it does following operation (from the input it checks value from database and add to row)
$( "#productSearch" ).change(function(event) {
event.preventDefault();
$.ajax({
type: "get",
context: this,
url: "{!! asset('searchByProductName') !!}",
dataType: 'json',
data: { name:this.value },
success: function(response)
{
if ($('#' + response.id).length !== 0)
{ $(this).val("").focus(); return false; }
var markup = "<tr id="+response.id+"><input type='hidden' name='product_id[]' value="+response.id+"><td><i class='flaticon-delete-1 delete-row' onclick='deleteRow(this)'></i></td><td>"+response.product_name+"</td><td>"+response.product_unit_price+"</td><td><input type='text' name='quantity[]' class='quantity' value='1'></td><td class='total'>"+response.product_unit_price+"</td><td>"+response.notes+"</td></tr>";
$("table tbody").append(markup);
$(this).val("").focus(); return false;
}
});
});
But the problem the form get auto submit ie, i can't add more than one value in the table. How do i prevent the form automatic submit so that more that one input can be taken with the above ajax code?

I'm not sure if the barcode scanner put the "enter key", but how about this one?
$("#form-id").on("submit", function(e) {
if ($("#input-id(productSearch)").is(":focus")) {
e.preventDefault();
}
});

IMO, the easiest way is to add a hidden input
<input type="hidden" />
browser will auto submit if there is one input in a form.

Related

Form not submitting on ajax request

So I'm comparing the value of the input field entered by the user to the value of the mysql DB (using an Ajax request to the checkAnswer.php file). The request itself works fine, it displays the correct "OK" or "WRONG" message, but then it does not submit the form if "OK". Should I put the .submit() somewhere else?
HTML code:
<form id="answerInput" action="index" method="post">
<div id="answer-warning"></div>
<div><input id="answer-input" name="answer" type="text"></div>
<input type="hidden" id="id" name="id" value="<?=$id?>">
<div><button type="submit" id="validate">Valider</button></div>
</form>
</div>
JS code
$("#validate").click(function(e){
e.preventDefault();
$.post(
'includes/checkAnswer.php',
{
answer : $('#answer-input').val(),
id : $('#id').val()
},
function(data){
if(data === '1'){
$("#answer-warning").html("OK");
$("#answerInput").submit();
}
else{
$("#answer-warning").html("WRONG");
}
},
'text'
);
});
I think it is because you set your button type as submit. Why?
When you do $("#validate").click(function(e){, you implicitly replace the default submit behavior of the form.
As you want to interfere in the middle of the process for extra stuff, I suggest you change the button type to button or simply remove the type attribute.
Then the $("#validate").click(function(e){ will alter behavior of click, not the submit of form.
<form id="answerInput" action="index" method="post">
<div id="answer-warning"></div>
<input id="answer-input" name="answer" type="text">
<input type="hidden" id="id" name="id" value="<?=$id?>">
<button onlcick="validate()">Valider</button>
</form>
/******** JS ************/
function validate(){
var post = {};
post['answer'] = $('#answer-input').val();
post['id'] = $('#id').val();
$.ajax({
url: 'includes/checkAnswer.php',
type: 'POST',
data: {data: post},
success:function (data) {
console.log('succsess');
},
error:function (jQXHR, textStatus, errorThrown) {
console.log('failure');
}
});
}

How to get multilevel children

On submit of class post_alternate_category_name I need to make value of input element alternate_category empty and I need to set the text of label .ermsg as saving... The code which I have written is not working:
<form method="POST" class="form-horizontal post_alternate_category_name">
<div class="control-group">
<label class="control-label">Alternate name</label>
<div class="controls">
<input class="m-wrap large alternate_category" name="alternate_category" type="text" value="">
<button type="submit" class="btn blue">Add</button>
<label class="ermsg" style="color: red"></label>
<input type="hidden" name="category_id" value="1">
</div>
<input type="hidden" name="_token" value="Jl3DOrLd0clH5cv17I5JQumqFtJzV8uNjblIZGu3">
</div>
</form>
$('.post_alternate_category_name').on('submit', function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "someurl",
data: "somedata",
beforeSend:function() {
$(this).children('.control-group').children('.controls').children('.ermsg').val('Saving');
$(this).find('.ermsg').html("");
},
success: function(response) {
$(this).children('.control-group').children('.controls').children('input[name="alternate_category"]').val('');
}
});
});
You can use
.find() function to get all children inside element.
jQuery find
Instead of using multiple ".children()" methods, you can reset and update values directly. See code below. Place it anywhere you like.
$('.post_alternate_category_name').on('submit', function(e) {
e.preventDefault();
$('input[name=alternate_category').val('');
$('label.ermsg').text(''Saving...);
)};
a) I need to make value of input element "alternate_category" empty.
$('input[name="alternate_category"]').val('');
b) I need to set the text of label ".ermsg" as "saving.."
$('.ermsg').html("saving..");

Required Field without Submit button after Ajax

I am trying to have my all my text/email input forms have a required attribute before you can "Submit" The email
But since I am using some Ajax to keep the page from refreshing after pressing the button the required attribute will not work.
This is why I am asking for an alternative for required with Javascript or jQuery (trying to prevent email form spam).
HTML (FORM)
<form id="contact">
<div class="form-group">
<label for="name">Voornaam*</label>
<input name="fn" type="text" class="form-control" id="fn" required>
</div>
<div class="form-group">
<label for="name">Achternaam*</label>
<input name="ln" type="text" class="form-control" id="ln" required>
</div>
<div class="form-group">
<label for="email">Email-address*</label>
<input name="email" type="email" class="form-control" id="email" required>
</div>
<div class="form-group">
<label for="message">Bericht*</label>
<textarea name="message" required class="form-control" id="message" rows="6"></textarea>
</div>
<button type="button" onClick="doIets(); this.form.reset();"
name="submit" id="submit" class="btn btn-primary">Verstuur <span id="result"></span></button>
<div id="result2"></div>
</form>
Ajax script
<script type="text/javascript">
function doIets()
{
console.log("doe iets");
var data = {
ck: (new Date()).getTime(),
fn: $("#fn").val(),
ln: $("#ln").val(),
email: $("#email").val(),
message: $("#message").val()
};
$.ajax({
type: "POST",
url: "sendmail.php",/*php file path*/
data: data,
beforeSend: function(){
$('#result').html('<img src="loader" style="height:10px;"/>')
},
success: function(data){
$('#result').hide();
$('#result2').html(data);
}
});
}
</script>
You will need to use e.preventDefault() when they click on the submit button and then validate the form and after that submit it using the ajax call you created above.
since you already read out the data, you can check whether your message is long enough for you via
data.message.length
if it is 0 (or lower than a threshold you defined), you can skip the ajax call and return some info to the user.
You might also want to trim the message first in order to be sure there aren't only whitespace in there.
Here is part from my code, where I bind the submit event to my form and check by looping if any required field is empty or if I want to do any such thing.
This way may help you--
$('.form .contact-form').submit(function(e) {
e.preventDefault();
$('.form .message').eq(0).html("<i>Sending... Please Wait...</i>");
var form = $(this);
var validated = true;
$('input[type="text"]',this).each(function(){
if($(this).val().length < 1){
$(this).addClass('error').focus();
validated = false;
return false;
}
});
if(validated === true){
$.post(__asyn.ajaxurl, $('.form form').eq(0).serialize(), function(data, textStatus, xhr) {
console.log(data);
});
}
});
Just pass the event object to your handler onClick="doIets(event);
and then add
function doIets(event) {
event.preventDefault();
...
}

(button || input) type=submit - missing value in $_POST variable in jQuery AJAX

I have login form where are two buttons - "login" and "forgot password?" And I need to check what button user clicked.
<form id="loginForm">
<div class="login-error" id="login-error"></div>
<input type="text" id="email" name="email">
<input type="password" id="password" name="password">
<input type="submit" name="submit" value="Login">
<button type="submit" name="submit" value="Forgot password?">Forgot password?</button>
</form>
var_dump($_POST) says:
array(2) { ["email"]=> string(0) "" ["password"]=> string(0) "" }
I am trying both ways (input type=submit and button type=submit) but none of them send the "submit" value.
(I am using jquery ajax)
$("#loginForm").click(function(){
/* Stop form from submitting normally */
event.preventDefault();
/* Get some values from elements on the page: */
var values = $(this).serialize();
/* Send the data using post and put the results in a div */
$.ajax({
url: "login.php", /* here is echo var_dump($_POST); */
type: "post",
data: values,
success: function(data){
$("#login-error").html(data);
},
error:function(){
$("#result").html('There is error while submit');
}
});
});
Please do you know where the problem can be? I know, there are lot of threads about value of button but nothing works for me. I also tried this example:
http://www.w3schools.com/tags/tryit.asp?filename=tryhtml_button_value2
The .serializeArray() or .serialize() method uses the standard W3C rules for successful controls to determine which elements it should include; in particular the element cannot be disabled and must contain a name attribute. No submit button value is serialized since the form was not submitted using a button. Data from file select elements is not serialized.
Refer..
http://api.jquery.com/serialize
http://api.jquery.com/serializeArray
jQuery serializeArray doesn't include the submit button that was clicked
This is one way to do it, concatening data string with specific clicked button name attribute:
HTML:
<form id="loginForm">
<div class="login-error" id="login-error"></div>
<input type="text" id="email" name="email">
<input type="password" id="password" name="password">
<button type="button" name="login" class="submit">Login</button>
<button type="button" name="forgot" class="submit">Forgot password?</button>
</form>
JQ:
$("#loginForm").on('click', '.submit', function (event) {
/* Stop form from submitting normally */
event.preventDefault();
/* Get some values from elements on the page: */
var values = $(this).closest('form').serialize() + '&' + this.name;
console.log(values);
/* Send the data using post and put the results in a div */
$.ajax({
url: "login.php",
/* here is echo var_dump($_POST); */
type: "post",
data: values,
success: function (data) {
$("#login-error").html(data);
},
error: function () {
$("#result").html('There is error while submit');
}
});
});
But better would be to target specific server side script depending which button is clicked, e.g:
HTML:
<form id="loginForm">
<div class="login-error" id="login-error"></div>
<input type="text" id="email" name="email">
<input type="password" id="password" name="password">
<button type="button" name="login" class="submit" data-url="login.php">Login</button>
<button type="button" name="forgot" class="submit" data-url="forgot.php">Forgot password?</button>
</form>
JQ:
$("#loginForm").on('click', '.submit', function (event) {
/* Stop form from submitting normally */
event.preventDefault();
/* Get some values from elements on the page: */
var values = $(this).closest('form').serialize();
/* Send the data using post and put the results in a div */
$.ajax({
url: $(this).data('url'),
/* here is echo var_dump($_POST); */
type: "post",
data: values,
success: function (data) {
$("#login-error").html(data);
},
error: function () {
$("#result").html('There is error while submit');
}
});
});
It will be a lot easier to check if you name the submit input and the button differently.
You currently have this set up like this:
<input type="submit" name="submit" value="Login">
<button type="submit" name="submit" value="Forgot password?">Forgot password?</button>
Try changing the name of the button to something like:
name="forgot"
then you can run a check on it such as
if (isset($_POST['submit'])){
stuff here
}
and a separate check for
if (isset($_POST['forgot'])){
stuff here
}
If there is not event in function then it will not prevent the submit function and by default get will be called and and $_POST will be empty for sure
Change
$("#loginForm").click(function(){
/* Stop form from submitting normally */
event.preventDefault();
To
$("#loginForm").click(function(event){
/* Stop form from submitting normally */
event.preventDefault();
Make one more change
data: values,
To
data:$("#loginForm").serialize(),
Remove one submit type there should be only one submit type make it type of button and call onbutton click functiuon to submit via ajax it will work same as submit.

Set error button when i enter repeated invalid email or blank entry in subscribe form in jquery

I have been created subscribe form using php and jquery and sql to store data.
Now it is working fine, but it has some limitation.
When i enter invalid email address, it shows like this,
But i need to remove that message, i need only working effects with error button.
And If i enter blank, that time error button working fine[that is button will be shaken and says error], after that i enter valid address, it also working fine[that is success button].
One more think, if i enter invalid address at first, and second also enter invalid address,, the error button works fine at first time only.
Here is lib.js:
$(document).ready(function () {
$('#newsletter').submit(function () {
var $this = $(this),
$response = $('#response'),
$mail = $('#signup-email'),
testmail = /^[^0-9][A-z0-9._%+-]+([.][A-z0-9_]+)*[#][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/,
hasError = false;
$response.find('p').remove();
if (!testmail.test($mail.val())) {
$('#actbtn').removeClass('btn-error').addClass('btn-error');
//$response.html('<p class="error">Please enter a valid email</p>');
hasError = true;
}
if (hasError === false) {
$response.find('p').remove();
$response.addClass('loading');
$.ajax({
type: "POST",
dataType: 'json',
cache: false,
url: $this.attr('action'),
data: $this.serialize(),
success: function(data){
if(data!=''){
$response.removeClass('loading');
if(data.status == 'success'){
$('#actbtn').removeClass('btn-error').addClass('btn-success');
}
else{
$('#actbtn').removeClass('btn-error').addClass('btn-error');
}
}
}
});
}
return false;
});
});
html:
<div id="newsletterform">
<div class="wrap">
<h3>Get Email Update</h3>
<form action="send.php" method="post" id="newsletter" name="newsletter">
<input type="email" name="signup-email" id="signup-email" value="" placeholder="Insert email here" />
<button id="actbtn" class="btn btn-7 btn-7h icon-envelope">Submit form</button>
<span class="arrow"></span>
</form>
<div id="response"></div>
</div>
</div>
May i know,how to achieve this one, Any idea would be highly appreciated.
Thanks in advance.
You have used the
<input type="email" name="signup-email" id="signup-email" value="" placeholder="Insert email here" />
try to use it as input text because you did the script validation
<input type="text" name="signup-email" id="signup-email" value="" placeholder="Insert email here" />

Categories

Resources