How to validate form created in bootbox message? - javascript

I am using bootbox.js. It allows user to create a form in it's 'message' part. But, I'd like to do some validation using jquery before I click submit button.
This is the bootbox:
bootbox.confirm({
title : "Choose Item:",
message :
"<?php
echo "<form id='f_item'>";
echo "<h3>Item: </h3><br/>";
foreach($item as $row_item){
echo "<input type='checkbox' name='item' class='cek_item' value='".$row_pic->item."' />";
}
echo "</form>";
?>",
buttons : {
cancel : { label: '<i class="fa fa-times"></i> Batal' },
confirm : { label: '<i class="fa fa-check"></i> OK'}
},
callback: function (result) {
//If OK button is pressed
if(result == true){
/*SENT FORM CODE*/
}
}
});
Without adding some validation form submit is working. But, I do not know where to put the validation script.
This is a test script
$(".cek_item").on('change',function(event){ alert($(this).val()+" is choosen"); });
where do I should put this script?
THe validation I'd like to do is:
If first item is first checked, the rest of the item is cannot be
checked.
If not the first item is first checked, then user cannot check the
first item.

You're kind of abusing the bootbox.confirm function, as it's not really meant to have form content. That being said, you would add your validation where you have /*SENT FORM CODE*/ - if you return false from that callback the modal won't close, so something like:
callback: function (result) {
//If OK button is pressed
if(result == true){
/*SENT FORM CODE*/
$("#f_item").validate();
if($("#f_item").valid()) {
/* form is valid */
}
else {
/* form is not valid */
return false;
}
}
}
This assumes you're also using jQuery Validation.

Related

Not able to submit or not submit form after ajax response

I am trying to submit a form after validation and confirmation. But after the validation the form is not getting submitted. If I do not validate and confirm then the form is being submitted. What am I doing wrong here? Please tell me how to rectify it.
<div class="button secondary" id="contact_submit">
Create/Update <span class="icon-right icon-check"></span>
</div>
function validateFields() {
#some validation operations
if(validated){
if(operation == "Create"){
$("#contact-form")[0].setAttribute("action", "/contact/create_contact/");
$("#contact-form")[0].setAttribute("method", "POST");
}
else if(operation == "Update"){
$("#contact-form")[0].setAttribute("action", "/contact/" + object_id + "/update_contact/");
$("#contact-form")[0].setAttribute("method", "PATCH");
}
$('#contact-form').on('submit', function(e){
e.preventDefault();
$.ajax({
url: '/oms/getIsPrimaryContact/',
type: 'GET',
data: { object_id: object_id },
success: function(data) {
if ($('.element-contact#is_primary_contact').prop("checked") && !data.is_primary_contact) {
var c = confirm('Are you sure you want to change the primary contact?');
if (c) {
return true;
} else {
return false;
}
}
},
error: function() {} });
});
$('#contact-form').submit();
}
}
$(document).ready(function(){
$("#contact_submit").click(function(e) {
validateFields()
});
});
It just shows the confirmation box and if I click on ok or cancel then also the ajax call is being initiated. If the checkbox is not checked then also the form is not being submitted.
On clicking either button in the confirmation box the form should be submitted or not submitted and if the checkbox is not checked then the form should just be submitted.
But instead ajax call is happening on clicking any button.

Javascript working on console, but not onclick event

I'm fairly new with JavaScript, I'm trying to give access to users to update products stock for WooCommerce. I've made "Update" button to run the script, but it won't run, the page only refreshes. But when I execute the script from console, it works (eg. js_update_stock('20');)
I'm working by modifying existing plugin for WordPress, so I'm sorry if the codes are a bit scattered. If you need anything else, please let me know.
HTML side of things:
<input type="number" id="stock'. $postid . '" name="stock'. $postid .'" value="'. get_post_meta( $postid, '_stock', true ) .'">
<button class="button button-primary" style="margin-bottom: 3px; padding-left: 24px; padding-right: 24px;" onclick="js_update_stock(\''. $postid .'\')">'. __('Update','update_button') .'</button>
I put this script on the same page:
echo '<script type="text/javascript">
function js_update_stock(product_id) {
var isnum = /^\d+$/.test(document.getElementById("stock" + product_id).value);
if(isnum){
if(confirm("Do you really want to update the stock of this product?")){
var data = {
action: \'update_stock\',
security: \'' . $ajax_nonce . '\',
id: product_id,
stock: document.getElementById("stock" + product_id).value
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
jQuery.post(ajaxurl, data, function(response) {
if(response == \'true\'){
location.reload(true);
}
});
}
else{
// do nothing
}
}
else{
alert("Please enter a valid stock quantity");
}
}
</script>';
AJAX Callback function:
add_action('wp_ajax_update_stock', 'update_stock_callback');
function update_stock_callback() {
check_ajax_referer( 'blahblah', 'security' );
if(isset($_POST['id'])){
$id = intval( $_POST['id'] );
$stock = intval( $_POST['stock'] );
wc_update_product_stock( $id, $stock );
echo 'true';
}
else{
echo 'false';
}
die(); // this is required to return a proper result
}
Any help is appreciated, as this has been bugging me for 2 days now. Thank you.
By default a button is of type submit so it's submitting your form, thats why your page refreshes.
You want to define button type as button so form doesn't submit.
<button type="button" class="button button-primary" style="margin-bottom: 3px; padding-left: 24px; padding-right: 24px;" onclick="js_update_stock(\''. $postid .'\')">'. __('Update','update_button') .'</button>
The page is refreshing because I guess the button you are using is in a form. So when you click on it, it will launch the request for the form and leave the page.
So to prevent that, you will just need to add the click event to your function and cancel it before the page has unload :
<button class="button button-primary"
style="margin-bottom: 3px; padding-left: 24px; padding-right: 24px;"
onclick="js_update_stock(event, \''. $postid .'\')">
'. __('Update','update_button') .'
</button>
And for javascript :
function js_update_stock(e, product_id) {
e.preventDefault();
// more code...
Javascript event prevent default on W3schools
I hope this solved your problem ;)
For most of the new browsers, default type of button element is "Submit".
That means, when click on it, your form will get submitted before calling your "onclick" function. Also, in your form you may not have specified action attribute, and that's why form is submitting to self.
You can specify type attribute for your button element to "button" specifically and it will now call to your "onclick" function.
For more information on button default type according to browser, visit :
What is the default button type?
Instead of button tag, you can use :
<a href='javascript:void(0);' id='updateBtn' class='btn btn-default'>Update</a>
$(document).ready(function () {
$('#updateBtn').on('click', function () {
// Make AJAX call here.
// Your logic will come here.
$.ajax({
url: 'Add url here',
data: 'Add data which is need to be update in json',
type: 'POST',
dataType: 'json',
success: successCallback,
complete: completeCallback,
error: errorCallback
})
});
var successCallback = function () {
// AJAX success callback
}
var completeCallback= function () {
// AJAX complete callback
}
var errorCallback= function () {
// AJAX error callback
}
});
NOTE: Also make sure you are not redirecting from backend(PHP) and just giving back response with statusCode.

How to check unique username before form submission

I have been trying this for hours now. I want to check if the username already exist in DB or not. If it does, alert and don't submit. If it doesn't, submit. Here is my code.
$(function() {
$("#new_user").on("submit", function() {
var anyFieldIsEmpty = $('.newuser_input').filter(function() {
return $.trim(this.value).length == 0;
}).length > 0;
if (anyFieldIsEmpty) {
alert("There are empty fields!");
return false;
}
else {
check_curr_username();
return false;
}
});
});
function check_curr_username() {
var username = $("#user_username").val();
$.ajax({
"url": "/checkusername",
"data": {"name":username},
"type": "get",
"dataType": "json",
"success": function(data) {
alert('Username'+' '+data.username +' '+'is already taken' );
$("#user_username").focus();
return false;
},
"error": function() {
$("#new_user").submit();
return true;
}
});
}
This is a Rails form. The code is only working when the username already exist. But if not then the form is not submitting.
we need the checkusername page but i think that the form isn't submitted because error isn't triggered (ie: no error happened).
checkusername page should return a specfic value if the username is not already used then you can process the form.
This is how I check for unique username. I may get down-voted because it's not Rails, but PHP.
<style>.nodisplay{display: none;}</style>
<form id="usersigningup" name="usersigningup" method="post" action="">
<input type='text' name='name' id='nose' pattern='[A-Za-z0-9_]{5,20}' required>
<input type='text' name='password' id='password' pattern='[A-Za-z0-9_]{5,20}' required>
<input class="nodisplay" type="submit" id="usersignup" name="usersignup" value="Go!"></form><br>
<span id='response'></span>
In my CSS the default display for the submit button is set to none. next I use a javascript keyup function to collect the input field of id='nose' (which is the username) and send an ajax post to php which then runs a query on my database.
$(document).ready(function(){
$('#nose').keyup(function(){
var name = $('#nose').val();
$.ajax({
type: 'post',
data: {ajax: 1,name: name},
success: function(response){
$('#response').html(response);
}});});});
Next I use a mysqli query.
<?php include ('connect.php'); if( isset($_POST['ajax']) && isset($_POST['name']) ){
$un = $_POST['name'];
$sql51 = mysqli_query($conn, "SELECT username FROM mysite Where username = '$un'");
if (mysqli_num_rows($sql51) > 0) {
echo "<font color='red'>Sorry <b><i>" . $un . "</i></b> has been taken</font><script>document.getElementById('usersignup').style.display='none';</script>";
} else {
echo "<font color='green'><b>The Username <i>" . $un . "</i> is available</b></font><script>document.getElementById('usersignup').style.display='block';</script>";}
exit;}?>
Notice the 'if' statement in the query; this will either run one of two scripts. The first will be to keep the display of the submit button as none if there is an exact match and echo 'Sorry (username) has been taken' in an html element with the id='response'. The second script will echo 'The username (username) is available' and set the display of the submit button style to 'display:block'; making it clickable.
As I said this all happens on a keyup event so the query runs everytime you press a key and let it up you will see the characters you type in the response element; along with seeing the submit button or not.
The PHP in this example is meant as an example and not to be considered safe from hackers; although, there is a pattern attribute set in the form disallowing most characters. I hope this helps.

Why does an ajax request not trigger validation

I have a form which is dynamically generated. Inside the form is a function that executes an AJAX request, and on success, modifies the value( sets it to an empty string) of a hidden field which is used for validation.( The hidden field is set to "required:true" )
However, on successful execution of the function, the hidden field does not trigger jQuery's validation and i am able to submit the form. The validation of the hidden field is only triggered when i trigger the validation of other fields intentionally, and the error message for the hidden field will appear, together with the other error message.
Function:
function DeleteImageDP(){
var itemid=$('#DisplayDeleteItemID').val();
var filepath=$('#DisplayDeleteFilePath').val();
var itempicid=$('#DisplayDeleteItemPicID').val();
var cfm=confirm("Confirm deletion of picture? ( Note: Picture wil be deleted permanently.");
if(cfm == true)
{
$.ajax({
url:"delete/deletedp.php",
type:"POST",
data:"ItemID="+itemid+"&FilePath="+filepath+"&ItemPicID="+itempicid,
success:function(){
alert("Image successfully deleted.");
$('#ImagePreviewDP').prop('src','').hide();
$('#ImagePreviewDPValidate').val('');
$('#DisplayDelete').hide();
},
error:function(){
alert("Image could not be deleted due to an error.");
}
});
return true;
}
else
{
return false;
}
};
Validation:
$('#ItemDetailsContainer').on('change',function(){
//Validation code .....
ImagePreviewDP:{
required:true
},
//More validation code....
});
Form(extract):
//Input and preview for Display Pic
echo"<div class='BizEditItemDetails' >";
//More code above
echo"<img id=ImagePreviewDP name=ImagePreviewDP class='ImagePreview' src=\"$dp\" > ";
echo"<input type='hidden' id='ImagePreviewDPValidate' name='ImagePreviewDPValidate' value=\"$dp\" >";
//More code below
echo"</div>";
Why doesn't setting the value of $("#ImagePreviewDP") to an empty string trigger the on.change?Also how would i get the validation to trigger upon successful execution of the function instead of it only triggering together with other errors?
Programatically setting an elements value with javascript never triggers the onchange event, you have to trigger it yourself
$.ajax({
url:"delete/deletedp.php",
type:"POST",
data:"ItemID="+itemid+"&FilePath="+filepath+"&ItemPicID="+itempicid,
success:function(){
alert("Image successfully deleted.");
$('#ImagePreviewDP').prop('src','').hide();
$('#ImagePreviewDPValidate').val('');
$('#DisplayDelete').hide();
$('#ItemDetailsContainer').trigger('change');
// ^^ trigger event handler
},
...........

jQuery Validation Plugin: same form, different validation submitHandler

I am using a single form in two different scenarios - Create and Edit.
I do something like
<?php
if($status == 'new')
echo '<button id="btnSubmit" type="submit" class="btn">Submit!</button>';
else
echo '<button id="btnEdit" type="submit" class="btn">Edit!</button>';
?>
What I want to achieve on my javascript end is to validate the form and call the correct web service according to which button is pressed. I am using the jQuery Validation Plugin found here.
Javascript
$('#myForm').validate({
submitHandler: function(data) {
$.ajax({
url: "service1.php"
...... other AJAX stuff ..........
});
}
}
$('#btnSubmit').click(function() {
// call service1.php
});
$('#btnEdit').click(function() {
// call service2.php
});
The method for validate can be a single function and you can set a flag(For example you will get an id in the edit page) to identify edit page or add page. So that you can check the flag in submit handler and submit the form to where it needs to be submitted. I'm not familiar with PHP and i hope this might help you.
Based on Marikkani's suggestion, I have implemented the below and it works. Hope it helps someone with a similar problem using Javascript and PHP.
In my form file I used a hidden div to store the type (new or edit).
<input type="hidden" id="type" value="<?php echo $type; ?>" />
Thereafter, in my javascript file I retrieve this value and check before calling the respective ajax.
$('#resForm').validate({
submitHandler: function(form) {
var type = $('#type').val();
if(type == 'new') {
$.ajax({
url: "service1.php"
.... other AJAX stuff
});
} else { // type is edit
$.ajax({
url: "service2.php"
.... other AJAX stuff
});
}
}
});

Categories

Resources