Validate automatically on button press - javascript

Hi I am using JQuery Form validator to validate a form, and using knockout js to call a function using a button, What I want is that when the button is clicked the the knockout js function should be called, and also at the same time check if all the fields are validated if not, it should just do nothing till all the fields are validated.
Link for the jquery validator form http://www.formvalidator.net/#advanced_programmatically
Here is a field and the button that calls the function.
<input type="text" name="birthday" data-validation="date" data-validation-format="yyyy-mm-dd" placeholder="yyyy-mm-dd" data-validation-help="You must be more than 20 years old" class="form-control" value="<?php if (isset($user['Birthday'])) {echo $user['Birthday'];} ?>">
<div data-bind="ifnot: (loggedIn() == 'true')">
<button data-bind="click : openUpTwoStepAuth " type="submit" id="openUpTwoStepAuth" class="btn registerbtn">
<?php echo lang("register_continue_btn"); ?>
</button>
</div>
And here is the knockout js function that tries to call the validation as soon as the button is clicked, but in my case it does not check the validation and goes on with the ajax call.
self.openUpTwoStepAuth = function(){
$('#openUpTwoStepAuth').validate(function(valid, elem) {
if(!valid){
return;
}
});
self.emailtokenconfirmation(false);
self.tokenError(null);
self.showTwoStepAuth();
$.ajax({
type: 'POST',
url: BASEURL + 'index.php/myprofile/sendEmailForTwoStepAuth/',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON({customerEmail : self.customerEmail()})
})
.done(function(data) {
if(data.success){
self.emailtokenconfirmation(true);
}else{
self.tokenError(data.result);
}
})
.fail(function(jqXHR, textStatus, errorThrown) {
alert("Error code thrown: " + errorThrown);
})
.always(function(data){
});
}
It works fine if its just a normal button calling the submit function with this piece of code
<script>
$.validate({
modules : 'toggleDisabled',
disabledFormFilter : 'form.toggle-disabled',
showErrorDialogs : false
});
</script>
but for me I want to call a js function and at the same time check the validation of the field.

This seems to be already answered here
Knockout + Jquery Validate
Use submitHandler in validate to call your view model function on successful validation.

Related

Popuating form fields from MySQL using AJAX and Jquery

I followed a tutorial to adapt the code. Here I am trying trying to auto-populate my form fields with AJAX when an 'ID' value is provided. I am new to Jquery and can't get to work this code.
Edit 1 : While testing the code, Jquery isn't preventing the form to submit and sending the AJAX request.
HTML form
<form id="form-ajax" action="form-ajax.php">
<label>ID:</label><input type="text" name="ID" /><br />
<label>Name:</label><input type="text" name="Name" /><br />
<label>Address:</label><input type="text" name="Address" /><br />
<label>Phone:</label><input type="text" name="Phone" /><br />
<label>Email:</label><input type="email" name="Email" /><br />
<input type="submit" value="fill from db" />
</form>
I tried changing Jquery code but still I couldn't get it to work. I think Jquery is creating a problem here. But I am unable to find the error or buggy code. Please it would be be very helpful if you put me in right direction.
Edit 2 : I tried using
return false;
instead of
event.preventDefault();
to prevent the form from submitting but still it isn't working. Any idea what I am doing wrong here ?
Jquery
jQuery(function($) {
// hook the submit action on the form
$("#form-ajax").submit(function(event) {
// stop the form submitting
event.preventDefault();
// grab the ID and send AJAX request if not (empty / only whitespace)
var IDval = this.elements.ID.value;
if (/\S/.test(IDval)) {
// using the ajax() method directly
$.ajax({
type : "GET",
url : ajax.php,
cache : false,
dataType : "json",
data : { ID : IDval },
success : process_response,
error: function(xhr) { alert("AJAX request failed: " + xhr.status); }
});
}
else {
alert("No ID supplied");
}
};
function process_response(response) {
var frm = $("#form-ajax");
var i;
console.dir(response); // for debug
for (i in response) {
frm.find('[name="' + i + '"]').val(response[i]);
}
}
});
Ajax.php
if (isset($_GET['action'])) {
if ($_GET['action'] == 'fetch') {
// tell the browser what's coming
header('Content-type: application/json');
// open database connection
$db = new PDO('mysql:dbname=test;host:localhost;', 'xyz', 'xyz');
// use prepared statements!
$query = $db->prepare('select * from form_ajax where ID = ?');
$query->execute(array($_GET['ID']));
$row = $query->fetch(PDO::FETCH_OBJ);
// send the data encoded as JSON
echo json_encode($row);
exit;
}
}
I don't see where you're parsing your json response into a javascript object (hash). This jQuery method should help. It also looks like you're not posting your form using jquery, but rather trying to make a get request. To properly submit the form using jquery, use something like this:
$.post( "form-ajax.php", $( "#form-ajax" ).serialize() );
Also, have you tried adding id attributes to your form elements?
<input type="text" id="name" name="name"/>
It would be easier to later reach them with
var element = $('#'+element_id);
If this is not a solution, can you post the json that is coming back from your request?
Replace the submit input with button:
<button type="button" id="submit">
Note the type="button".
It's mandatory to prevent form submition
Javascript:
$(document).ready(function() {
$("#submit").on("click", function(e) {
$.ajax({type:"get",
url: "ajax.php",
data: $("#form-ajax").serialize(),
dataType: "json",
success: process_response,
error: function(xhr) { alert("AJAX request failed: " + xhr.status); }
});
});
});

Jquery validation plugin does not send POST data

Update 2: I found out what was wrong! There was a 301 redirect in the .htaccess file. I will post it as an answer once I am allowed to (users under 10 rep have to wait 8 hours).
Update: I have taken Barmar's suggestion and checked the network tab (a tab I'm not too familiar with) and noticed I am receiving a 301 from handle.php See screenshot. I am going to do some searching and post my results.
Original Post: I am using the JQuery validation plugin to validate and send form data via ajax. The problem isn't that the data is being sent, but the form handler is saying there are no elements in the $_POST array. I have tested a few different methods to send ajax, and the data sends, but the form handler does not see any $_POST[] values.
Note: I have to use the JQuery validation plugin so it has to be handled by .validate.submitHandler(). Any $(form).on() won't suffice.
html + js (index.php)
<form action="handle.php" class="sky-form sky-form-modal" id="sky-form-modal" method=
"post" name="sky-form-modal">
<label class="input">
<input name="name" placeholder="Name" type=
"text">
</label>
<label class="input"><input name="company" placeholder="Company" type=
"text">
</label>
<footer>
<button class="button" type="submit">Send request</button>
<div class="progress"></div>
</footer>
</form>
<script>
$("#sky-form-modal").validate({
submitHandler: function(form) {
var $form = $("#sky-form-modal"); //being explicit for testing
var $inputs = $form.find("input, select, button, textarea");
var serializedData = $form.serialize();
request = $.ajax({
url: "handle.php",
type: "POST",
data: serializedData
});
console.log('data: ' + serializedData);
request.done(function(response, textStatus, jqXHR) {
console.log("Response: " + response);
});
},
});
</script>
handle.php:
<?php
if(isset($_POST['name'])) {
echo 'we got it';
} else {
echo 'name not set';
}
?>
Okay, so it seems like everything works, check out the console.log after I fill in the username and leave the company blank:
data: name=testtest&company=
Response: name not set
As you can see, serialize works and grabs all the info, but when handled by handle.php it tells me that the $_POST[] is empty. Looping through it on handle.php proves it:
foreach($_POST as $key=>$value) {
echo "$key: $value
\n";
}
Which doesn't return at all.
I have also tried ajaxSubmit() and form.submit() but I get the same exact results.
This one looks right to me, because I have searched and searched stackoverflow and came across that most of the problems with this is including the 'name' attribute on the input tags, which is already done.
Thanks in advance!!
My issue was irrelevant to my code and ended being a few declarations in the .htaccess. It was redirecting me from a .php file to a directory (for prettier URLS). Now, this is a common technique so:
if you are working on someone else's project and your URL's aren't standard with a file extension, check the .htaccess!
Page.html or .php
<form action="/" id="sky-form-modal" method=
"post" name="sky-form-modal">
<input name="name" placeholder="Name" type="text">
<input name="company" placeholder="Company" type="text">
<button class="button" type="submit">Send request</button>
</form>
<div id="result"></div>
<script>
var request;
$("#sky-form-modal").submit(function(event){
// abort any pending request
if (request) {
request.abort();
}
var $form = $(this);
var $inputs = $form.find("input, input");
// serialize the data in the form
var serializedData = $form.serialize();
// let's disable the inputs for the duration of the ajax request
// Note: we disable elements AFTER the form data has been serialized.
// Disabled form elements will not be serialized.
$inputs.prop("disabled", true);
// fire off the request to /form.php
request = $.ajax({
url: "handle.php",
type: "post",
data: serializedData
});
// callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
// log a message to the console
console.log("Hooray, it worked!");
$("#result").html(response);
});
// callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// log the error to the console
console.error(
"The following error occured: "+
textStatus, errorThrown
);
});
// callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// reenable the inputs
$inputs.prop("disabled", false);
});
// prevent default posting of form
event.preventDefault();
});
</script>
handle.php
<?php
foreach ($_POST as $key => $value) {
echo "POST Key: '$key', Value: '$value'<br>";
}
?>
I removed your labels and classes for the simple look of the form.
i Guess you missed '(' after validation
$("#sky-form-modal").validate {
$("#sky-form-modal").validate ({

Submitting form is not working properly

I'm developing a webpage that creates a form with a number of select tags dynamically by means of some javascript/jquery code. When submitting the form a php file (form_submit.php) must process the submitted form fields. Furthermore I use Netbeans 7.4 for php debugging.
My problem: when I select some values in the form and submit the form the debugger shows empty submitted values (e.g., default values "NOSELECTION" for no selection) within form_submit.php instead of the selected values. The console within the submit function in the code below does show the selected submitted values (and therefore also confirms that the built html form with the select tags is correct).
I do not assume this a is a bug in Netbeans, so where do I go wrong? I suspect there is a bug in the jquery submit function below, but I cant's see it...
Javascript code:
//main function document ready
$(document).ready(function(){
//only part of code here to build the form with a number of <select>'s
ecorp_eproductoptions = '<select id="selected_eproductid'+ff+'" class="eprodtype" name="selected_eproductid'+ff+'">';
ff++;
ecorp_eproductoptions += '<option selected="selected" value="NOSELECTION" > Koppel uw product </option>';
for(var k=0; k< Staticvars.ecorp_nrofeproducts;k++){
ecorp_eproductoptions += '<option value="'+ Staticvars.suppliername[i] +'_'+Staticvars.agreementid[i] +'_'+ supplier_eproductid +'_'+ Staticvars.ecorp_eproductid[k] +'"> '+ Staticvars.ecorp_eproductname[k] +' </option>';
}//for var k
ecorp_eproductoptions += '</select>';
form += '<td> '+ ecorp_eproductoptions +' </td></tr>';
//etc...
//FUNCTION Submit()
$("#myForm").submit(function(){
console.log('SUBMITTED FORM: '+ $( this ).serialize() ); //shows values for select tags!
$.ajax({
type: "POST",
url: "form_submit.php",
data: $("#myForm").serialize(),
dataType: "json",
success: function(msg){
if(msg.statusgeneral == 'success'){
}
else
{
}//else
}, //succes: function
error: function(){
$("#errorbox").html("There was an error submitting the form. Please try again.");
}
});//.ajax
//make sure the form doesn't post
return false;
});//$("#myForm").submit()
}); //$(document).ready
HTML code:
<form id="myForm" name="myForm" action="" method="post">
<div id="wrapper"></div> <!--anchor point for adding set of product form fields -->
<input type="hidden" name="form_token" value="<?php echo $form_token; ?>" />
<input type="submit" name="submitForm" value="Bevestig">
</form>
I'm new to jQuery too, but I think the problem is the fact that your $.ajax call is running asynchronously which allows the submit event handler to continue on and return false before your form sends the values...just a newbie guess. :)
Have you tried adding async: false to your $.ajax call?
i dont know why happens that, but please try this
$("#myForm").submit(function(){
var dataAjax = $( this ).serialize();
console.log('SUBMITTED FORM: '+ dataAjax ); //shows values for select tags!
$.ajax({
type: "POST",
url: "form_submit.php",
data: dataAjax,
dataType: "json",
success: function(msg){
if(msg.statusgeneral == 'success'){
}
else
{
}//else
}, //succes: function
error: function(){
$("#errorbox").html("There was an error submitting the form. Please try again.");
}
});//.ajax
//make sure the form doesn't post
return false;
});//$("#myForm").submit()

jQuery: While ajax request block element

So i have this function in JS, sending a request to insert a new Status message to the database.
function DoStatusInsert(){
var wrapperId = '#statusResponseNow';
$.ajax({
type: "POST",
url: "misc/insertStatus.php",
data: {
value: 'y',
uID : $('#uID').val(),
message : $('#message').val()
},
success: function(msg){
$('#message').val("");
$('#statusResponse').toggle();
$(wrapperId).prepend(msg);
$(wrapperId).children().first().fadeIn('slow');
}
});
}
With this form:
<input name="message" type="text" id="message" value="" size="60">
<input type="hidden" name="uID" id="uID" value="<?php echo $v["id"]; ?>">
<input name="submit" type="submit" id="submit" value="Spara">
<div id="statusResponseNow"></div>
Now I wish to do something like blocking the submit button or the message field to "read-only" until you receive response / success, so you don't have the opportunity to like press submit alot of times so it inserts alot.. (i know you could make a php for checking after doubleĀ“s in DB)
So: when you click on submit then it makes either message field and/or submit button to read only
How should i do it?
function DoStatusInsert(){
$('#IdOfYourSaveButton').attr('disabled', 'disabled');
var wrapperId = '#statusResponseNow';
$.ajax({
type: "POST",
url: "misc/insertStatus.php",
data: {
value: 'y',
uID : $('#uID').val(),
message : $('#message').val(),
success: function(msg){
$('#IdOfYourSavebutton').removeAttr('disabled');
$('#message').val("");
$('#statusResponse').toggle();
$(wrapperId).prepend(msg);
$(wrapperId).children().first().fadeIn('slow');
}
});
}
enabled and disable the button. nice and easy :)
On calling the function, set the disabled property of the button, and then set it back on success.
function DoStatusInsert(){
$('#submit').attr("disabled", "true");
var wrapperId = '#statusResponseNow';
$.ajax({
type: "POST",
url: "misc/insertStatus.php",
data: {
value: 'y',
uID : $('#uID').val(),
message : $('#message').val()
},
success: function(msg){
$('#message').val("");
$('#statusResponse').toggle();
$(wrapperId).prepend(msg);
$(wrapperId).children().first().fadeIn('slow');
$('#submit').attr("disabled", "false");
}
});
}
My initial thoughts would be to insert
$('input[type=submit]', this).attr('disabled', 'disabled');
before the ajax call is started and then removed the disabled attribute with the success function of the ajax request.
Manually toggling the disabled state of the button works well enough, but jQuery has a couple helper events to make that a bit nicer: .ajaxStart() and .ajaxStop(). You can use those two handlers on your submit button and not have to worry about maintaining that manual code around your $.ajax() request.
Just throw this in with your other initialization code, probably in $(document).ready():
$('#submit').ajaxStart(function() { this.disabled = true; });
$('#submit').ajaxStop(function() { this.disabled = false; });
You can use for example jQuery BlockUI Plugin from http://jquery.malsup.com/block/ (see demo on http://jquery.malsup.com/block/#element and http://jquery.malsup.com/block/#demos).
If a div with all your form elements which you need to block has id formDiv then you can call
jQuery('#formDiv').block({ message: '<h1>Just a moment...</h1>' });
before jQuery.ajax and call
jQuery('#formDiv').unblock();
as the first line in both success and error handler of the jQuery.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