How to call a function again and again using knockout - javascript

I have this knockout code.
self.newPatient = ko.asyncCommand({
execute: function(complete) {
var isValid=$('#addPatientForm').parsley( 'validate' );
if(isValid){
var patientJson=ko.toJSON(self.patient());
formdata.append("json",patientJson);
//self.enableButton(false);
var imagepath= $.ajax({
url: projectUrl+"newPatient",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (res) {
formdata = new FormData();
imagepath=res;
var length=self.patients().length;
var patient=self.patient();
// self.enableButton(true);
}
});
}
},
canExecute: function(isExecuting) {
return !isExecuting && isDirty() && isValid();
}
});
This is my html inputfields
<div class="control-group">
<label class="control-label" for="inputIcon">Username :</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-hand-right"></i></span>
<input class="span8" type="text" data-bind="value: username" name="username" data-required="true" data-trigger="change" data-remote="${pageContext.request.contextPath}/isUserNameExists" data-remote-method="GET">
</div>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputIcon">Password :</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-hand-right"></i></span>
<input class="span8" type="password" data-bind="value: password" name="password" data-required="true" data-trigger="change">
</div>
</div>
</div>
and this is my button
<button class="btn btn-primary"
data-bind="command: $root.newPatient, activity: $root.newPatient.isExecuting">
<i class="icon-ok icon-white"></i> Save
</button>
when I press the save button then execute: function(complete){.....} is called and inside this function
var isValid=$('#addPatientForm').parsley( 'validate' );
is called which checks form validity and if the form is invalid then isValid is false and hence the ajax is not called.
I want to call
var isValid=$('#addPatientForm').parsley( 'validate' );
if(isValid){.....}
when any of the input field is changed .So can any body please suggest me how to do?

You could write your own bindingHandler:
ko.bindingHandlers.parsley = {
init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
var isValid = valueAccessor();
var $form = $(element).closest('form');
$(element).change(function() {
isValid($form.parsley('validate'));
});
}
};
And in your ViewModel:
self.isValid = ko.observable(false);
And then:
<form ...>
<input data-bind="parsley: isValid, ..." />
</form>
See http://jsfiddle.net/sjroesink/ksqXx/
Edit
Without being able to reproduce your error, or an actual line where the error occurs, I cannot help you.
Try using Chrome's Developer tools to see where the error occurs:

You could use the subscribe function of your observable to run code:
username.subscribe(function () { isValid=$('#addPatientForm').parsley( 'validate' ); }
password.subscribe(function () { isValid=$('#addPatientForm').parsley( 'validate' ); }
Update after your comment:
Here is what I would do:
<div id='koRoot'>
<input type='text' data-bind='value: username' />
<input type='text' data-bind='enable: enableButton,value: password' />
<input type='button' data-bind='command: newPatient' value='Go!' />
</div>
...
And the js:
var callNewPatient = function () {
if (self.awaitingValidation()) self.newPatient.execute();
}
this.username.subscribe(callNewPatient);
this.password.subscribe(callNewPatient);
this.newPatient = ko.asyncCommand({
execute: function (complete) {
self.isValid(self.username() === 'me' && self.password() === 'pass');
if (self.isValid()) {
self.awaitingValidation(false);
alert("Valid!");
} else {
self.awaitingValidation(true);
}
},
canExecute: function (isExecuting) {
return self.isValid();
}
});
http://jsfiddle.net/nyothecat/LkaEJ/1/

Related

Javascript - After creating a div, Ajax is not working

I have a button for a form. When I click the button, the form is created. After being created, the form is not working with Ajax. My script codes are in here. My #testform is not wrong because it's working without creating form. Do you have any ideas?
function addDiv() {
var panel = document.querySelector(".add_new");
var div = document.createElement("div");
div.innerHTML = '<br> <form id="testform" method="POST"> <div class="row" style="padding-left:10rem;"> <div class="col-md-4"> <input type="text" class="form-control" value="" placeholder="Başlık" name="yeniBaslik" required></div> <div class="col-md-4"> <input type="text" placeholder="Açıklama" name="yeniAciklama" class="form-control" value="" name="" required> </div> <div class="col-md-2 text-left"> <button type="submit" class="btn btn-success btn-animated btn-wide addToDatabase">Add to the Database</button> </div> </row> </form> <br>';
panel.appendChild(div);
}
$("#testform").submit(function(e) {
e.preventDefault();
var formData = new FormData($("#testform").get(0));
$.ajax({
url: 'config.php',
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function() {
setTimeout(
function() {
$(".addToDatabase").html("Successfully.");
}, 1000);
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="addDiv()"> Create a form </button>
<div class="add_new"></div>
Since second statement is executed before "div" is created, submit event is not being listened to on the new <form>
function addDiv() {
/*...*/
panel.appendChild(div);
$("#testform").submit(function(e) { /*...*/ });
}

How to send ID of a row throught submit form / button?

I'm writing a code for the system administrator to be able to reset the users' passwords in their accounts in case they forget said password.
I'm currently having problems passing the target user's ID through Ajax to change said user's password, through debugging tool, the system returns an "undefined" response for "id:", although the "_token" and "password" fields were sent fine.
HTML code for the form
<form id="form-reset-password">
<div class="container my-2">
<div class="row">
<div class="col-md-12">
<div class="form-row">
<input type="hidden" id="token" name="_token" value="{{csrf_token()}}">
</div>
<div class="form-group">
<label>New Password</label>
<input type="text" class="form-control" id="reset-password" name="password" readonly>
</div>
<div class="form-group text-right mt-4">
<button type="button" class="btn btn-dark" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-success btn-confirmreset">Reset</button>
</div>
</div>
</div>
</div>
</form>
Javascript for generating the data-table where it shows the list of User accounts. On the side of the table, the admin can click a button to reset the password of said user.
$(document).ready(function() {
getRoles();
var accounts;
$('#account-management').addClass('active');
accounts = $("#table-accounts").DataTable({
ajax: {
url: "/users/get-all-users",
dataSrc: ''
},
responsive:true,
"order": [[ 7, "desc" ]],
columns: [
{ data: 'id'},
{ data: 'organization_name', defaultContent: 'n/a' },
{ data: 'first_name' },
{ data: 'last_name' },
{ data: 'email'},
{ data: 'student_number'},
{ data: 'role.name'},
{ data: 'created_at'},
{ data: null,
render: function ( data, type, row ) {
var html = "";
if (data.status == 1) {
html += '<span class="switch switch-sm"> <input type="checkbox" class="switch btn-change-status" id="'+data.id+'" data-id="'+data.id+'" data-status="'+data.status+'" checked> <label for="'+data.id+'"></label></span>';
} else {
html += '<span class="switch switch-sm"> <input type="checkbox" class="switch btn-change-status" id="'+data.id+'" data-id="'+data.id+'" data-status="'+data.status+'"> <label for="'+data.id+'"></label></span>';
}
html += "<button type='button' class='btn btn-primary btn-sm btn-edit-account mr-2' data-id='"+data.id+"' data-account='"+data.id+"'>Edit</button>";
html += "<button type='button' class='btn btn-secondary btn-sm btn-reset-password' data-id='"+data.id+"' data-account='"+data.id+"'><i class='fas fa-key'></i></button>";
return html;
}
},
],
columnDefs: [
{ className: "hidden", "targets": [0]},
{ "orderable": false, "targets": 7 }
]
});
Javascript for the random password generator and reset password
function resetPassword() {
$.ajax({
type: 'GET',
url: '/user/get-new-password',
processData: false,
success: function(data) {
$('#reset-password').val(data.password);
}
});
}
$(document).on('click', '.btn-reset-password', function() {
$('#reset-password-modal').modal('show');
resetPassword();
});
$(document).on('submit', '#form-reset-password', function() {
var confirm_alert = confirm("Are you sure you want to reset this account's password?");
if (confirm_alert == true) {
// var id = $(this).attr('data-id');
var id = $('.btn-confirmreset').attr('data-id');
$.ajax({
url: "/auth/reset-password",
type: "POST",
data: $(this).serialize()+"&id="+id,
success: function(data) {
if (data.success === true) {
alert("Password successfully reset!");
location.reload();
}
else {
alert("Something went wrong");
}
}
});
return false;
}
});
Thank you for your help!
<form id="form-reset-password">
<div class="container my-2">
<div class="row">
<div class="col-md-12">
<div class="form-row">
<input type="hidden" id="token" name="_token" value="{{csrf_token()}}">
<input type="hidden" id="user_id" name="user_id" value=""> // initiate the hidden input here
</div>
<div class="form-group">
<label>New Password</label>
<input type="text" class="form-control" id="reset-password" name="password" readonly>
</div>
<div class="form-group text-right mt-4">
<button type="button" class="btn btn-dark" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-success btn-confirmreset">Reset</button>
</div>
</div>
</div>
</div>
</form>
<script type="text/javascript">
$(document).on('click', '.btn-reset-password', function() {
var user_id_value = $(this).attr('data-id'); // Get the user id from attr
$('#user_id').val(user_id_value); // Assign the user id to hidden field.
$('#reset-password-modal').modal('show');
resetPassword();
});
$(document).on('submit', '#form-reset-password', function() {
var confirm_alert = confirm("Are you sure you want to reset this account's password?");
if (confirm_alert == true) {
// var id = $(this).attr('data-id');
//var id = $('.btn-confirmreset').attr('data-id'); // Remove this, it won't work , because this button doesn't contain the data-id
var id = $('#user_id').val(user_id_value); // You can get the value from hidden field
$.ajax({
url: "/auth/reset-password",
type: "POST",
data: $(this).serialize()+"&id="+id,
success: function(data) {
if (data.success === true) {
alert("Password successfully reset!");
location.reload();
}
else {
alert("Something went wrong");
}
}
});
return false;
}
});
</script>
Please refer the above code, You can pass the user id while modal pop up call and set that id to hidden value. then you can access that id from the hidden input. when you submit "form-reset-password" form.
Please look at comments on the above code
Maybe the attr() function is looking for native HTML attribute. So use the following snippet will help.
var id = $('.btn-confirmreset').data('id');

jQuery validate require_from_group error message location

I have successfully been able to use the code in
jsfiddle.net/y3qayufu/2/ to validate a group of fields but how can I display the error message in a specific location. I would like the error message to appear only once after the submit button has been pressed, preferably above the group, but possibly below.
Instead of this:
I would like this:
Thanks
Use jQuery validation errorPlacement function provided:
JsFiddle updated
$("#findproject_form").validate({
rules: {
....
},
errorPlacement: function(error, element) {
$('label.error').remove();
error.insertAfter("#submit_btn");
}
});
HTML:
<div class="searchbg" id="submit_btn" style="margin-right:0px;">
<input class="bgbttn" type="submit" name="submit" value="" />
</div>
Hi here is a fixed fiddle http://jsfiddle.net/bayahiassem/sdx4ru4s/2/
If you can't open it, here the updated code:
html Only added an id to the h3
<form id="findproject_form" method="post" action="{$BASE_URL}findproject">
<div class="bgtrans">
<h3 id="header">Search By</h3>
<div class="div_bg1">
<div class="searchbg">
<div class="seachbginputbg">
<input class="seachbginput validategroup" type="text" placeholder="Profession" id="Profession" name="Profession" value="" />
</div>
</div>
<div class="searchbg">
<div class="seachbginputbg">
<input class="seachbginput validategroup" type="text" placeholder="Location" id="Location1" name="Location1" value="" />
</div>
</div>
<div class="searchbg" style="margin-right:0px;">
<div class="seachbginputbg">
<input class="seachbginput validategroup" type="text" placeholder="Company" id="Company" name="Company" value="" />
</div>
</div>
<div class="clear"></div>
</div>
<div class="div_bg2">
<div class="searchbg">
<div class="seachbginputbg">
<input class="seachbginput validategroup" type="text" placeholder="Name" id="Name" name="Name" value="" />
</div>
</div>
<div class="searchbg">
<div class="seachbginputbg">
<input class="seachbginput validategroup" type="text" placeholder="Key Words" id="KeyWord" name="KeyWord" value="" />
</div>
</div>
<div class="searchbg" style="margin-right:0px;">
<input class="bgbttn" type="submit" name="submit" value="" />
</div>
<div class="clear"></div>
</div>
</div>
</form>
JS using errorPlacement :
$(document).ready(function () {
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$("#findproject_form").validate({
rules: {
Profession: {
require_from_group: [1, ".validategroup"]
},
Location1: {
require_from_group: [1, ".validategroup"]
},
Company: {
require_from_group: [1, ".validategroup"]
},
Name: {
require_from_group: [1, ".validategroup"]
},
KeyWord: {
require_from_group: [1, ".validategroup"]
}
},
errorPlacement: function(error, element) {
console.log(error[0].innerText);
if(error[0].innerText == 'Please fill at least 1 of these fields.' && !errorshowed) {
error.insertAfter("#header");
errorshowed = true;
}
}
});
var errorshowed = false;
$.validator.addMethod("require_from_group", function (value, element, options) {
var $fields = $(options[1], element.form),
$fieldsFirst = $fields.eq(0),
validator = $fieldsFirst.data("valid_req_grp") ? $fieldsFirst.data("valid_req_grp") : $.extend({}, this),
isValid = $fields.filter(function () {
return validator.elementValue(this);
}).length >= options[0];
// Store the cloned validator for future validation
$fieldsFirst.data("valid_req_grp", validator);
// If element isn't being validated, run each require_from_group field's validation rules
if (!$(element).data("being_validated")) {
$fields.data("being_validated", true);
$fields.each(function () {
validator.element(this);
});
$fields.data("being_validated", false);
}
return isValid;
}, $.validator.format("Please fill at least {0} of these fields."));
});
Try this on submit u can put in function definition
var valid=0;
$(this).find('input[type=text], select').each(function(){
if($(this).val() != "") valid+=1;
});
if(valid==0)
{
$('#myDiv').html("please fil atleast one of these");
}

HTML Form Submit does not reach my javascript

I am trying to reach my javascript code when I press the submit button within my form and it is not triggering my javascript code at all.
So I got this form within my Bootstrap Modal using the following code:
<form id="updateUserForm">
<div class="form-group">
<label for="firstName">First name:</label>
<input type="text" class="form-control" id="firstnameModalInput" />
</div>
<div class="form-group">
<label for="middleName">Middle name:</label>
<input type="text" class="form-control" id="middlenameModalInput" />
</div>
<div class="form-group">
<label for="lastName">Last name:</label>
<input type="text" class="form-control" id="lastnameModalInput" />
</div>
<div class="form-group">
<label for="mobileNumber">Mobile number:</label>
<input type="text" class="form-control" id="mobilenumberModalInput" />
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="text" class="form-control" id="emailModalInput" />
</div>
<div class="form-group">
<label for="Enabled">Enabled:</label>
<input type="checkbox" class="form-control" id="enabledModalInput" style="width:34px" />
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-default" data-dismiss="modal" id="submit" value="Apply" />
</div>
</form>
And the javascript code I have:
$('document').ready(function(){
$("#updateUserForm").submit(function (event) {
console.log("Method entered");
event.preventDefault();
var serialize = $("#updateUserForm").serialize();
$.ajax({
type: "POST",
data: serialize,
url: "/Dashboard/UpdateUser",
datatype: JSON,
succes: function (data) {
console.log("succes!");
console.log(data);
},
error: function (data) {
console.log("error");
console.log(data);
}
})
})
})
I have another function in that javascript that is used to populate the input fields and that works fine, so I guess the HTML can reach the javascript file. But it does not reach the javascript submit function (it doesn't do the console.log for example) . Does anyone have an idea what I am doing wrong?
EDIT:
I have been playing around a bit more, and it seems that I can acces the javascript method when I try to reach it from outside of the bootstrap modal, it goes wrong somewhere within the modal.
Use return false instead of prevent default end of the function and change the submit function with on function.
$('document').ready(function(){
$("#updateUserForm").on("submit", function () {
console.log("Method entered");
var serialize = $("#updateUserForm").serialize();
$.ajax({
type: "POST",
data: serialize,
url: "/Dashboard/UpdateUser",
datatype: JSON,
succes: function (data) {
console.log("succes!");
console.log(data);
},
error: function (data) {
console.log("error");
console.log(data);
}
})
return false;
})
})
try this
$("#updateUserForm").on('submit', function (e) {
e.preventDefault();
});
Can you please try below code. and please check post URL"/Dashboard/UpdateUser" is right?
$("#UpdateUserForm").submit(function (e)
{
var isValid = $("#UpdateUserForm").valid();
if (!isValid)
return;
//This is important as it prevents the form being submitted twice
e.preventDefault();
$.ajax({
type: "POST",
url: "/Dashboard/UpdateUser",
data: $("#UpdateUserForm").serialize(),
success: function (response)
{
var status = '';
status = response.Status;
console.log("succes!");
console.log(data);
}
})
.error(function () {
console.log("error");
console.log(data);
});
});
$("#updateUserForm").on('submit', function (e) {
e.preventDefault();
});
Or use action properties in form.

Form Submission does not work

My form submission does not work . Nothing happens when i submit the form. I tried everything but no result.
I have looked at everything on here that I can find and I just can't figure out why I cannot perfect this code.
My code
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('contact_queryf').bind('click', function (event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'Views/query_send.php',
data: $('contact_queryf').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
</script>
my form code
<form role="form" method="post" id="contact_queryf" name="contact_queryf">
<div class="form-group">
<input type="text" class="form-control" id="name" name="name" placeholder="Name" required>
</div>
<div class="form-group">
<input type="email" class="form-control" id="email" name="email" placeholder="Email" required>
</div>
<div class="form-group">
<div class="radio-inline">
<label class="radio-inline">
<input type="radio" name="qtype" id="qtype" value="Android" required>Android
</label>
<label class="radio-inline">
<input type="radio" name="qtype" id="qtype" value="iOS" required>iOS
</label>
<label class="radio-inline">
<input type="radio" name="qtype" id="qtype" value="Web" required>Web
</label>
<label class="radio-inline">
<input type="radio" name="qtype" id="qtype" value="other" required>Other
</label>
</div>
</div>
<div class="form-group">
<textarea class="form-control" rows="3" name="text" id="text" required></textarea>
</div>
<button type="submit" class="btn btn-custom bleft" id="contact_query" name="contact_query">Submit</button>
First thing to try:
data: $('#contact_queryf').serialize()
instead of
data: $('contact_queryf').serialize()
(you were missing the #)
Also, you want to bind the click event to "#contact_query" (the submit button), not to the form itself, so
$('#contact_query').bind(...
instead of
$('contact_queryf').bind(...
$(function () {
$('#contact_queryf').on('click', function (event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'Views/query_send.php',
data: $(this).serialize(),
success: function (response) {
// response
alert('form was submitted');
}
});
});
});
Take a look on the documentation - .on()
You are missing the # in your jquery selector
$('contact_queryf').bind('click', function (event) {
Should be
$('#contact_queryf').bind('click', function (event) {
The selector is incorrect, change the selector's
$(function () {
$('#contact_query').bind('click', function (event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'Views/query_send.php',
data: $('#contact_queryf').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
OR
$(function () {
$('#contact_queryf').submit(function (event) {
$.ajax({
type: 'POST',
url: 'Views/query_send.php',
data: $(event.target).serialize(),
success: function () {
alert('form was submitted');
}
});
return false;
});
});
And in HTML, form close </form> tag is missing
If you're using the <button type="submit" to submit the form you do not need the AJAX.
Or am I missing something?
Right now you're submitting the form when a user clicks the form.
Here you go cat daddy
This can get you jump started in submitting a form via AJAX but at a lower level.
This is really what you're attempting to do.
<button type="submit" class="btn btn-custom bleft" id="contact_query" name="contact_query" onclick="btnSubmitForm(event)">Submit</button>
var btnSubmitForm = function (event) {
event.preventDefault();
var newForm = new FormData(document.forms[0]),
xhr = new XMLHttpRequest(),
that = this;
xhr.onload = function () { /*do something when response is back from server*/ };
xhr.open('GET|POST|PUT|DELETE', 'YOUR URL', true);
xhr.send(newForm);
return false;
};

Categories