Hi make one html from which submitting without refresh by jquery. Problem is that I am beginner and I dont know how to add validation for html form. I need changes in script so first form will validate by jquery or ajax then it will submit by jquery witout page refresh.. have look in my code. Please provide me working solution in that first form validate by ajax jquery then submit by jquery without refresh.. Thanks in advance
JQUERY:
<script type="text/javascript">
$(document).ready(function(){
$("form#form").submit(function() {
// we want to store the values from the form input box, then send via ajax below
var uno = $("#uno").val();
var name = $("#name").val();
var licence = $("#licence").val();
var email = $("#email").val();
var phone = $("#phone").val();
var dataString = 'uno=' + uno + '&name=' + name + '&licence=' + licence + '&email=' + email + '&phone=' + phone;
$.ajax({
type: "POST",
url: "addd.php",
data: dataString,
success: function(){
$('form#form').hide(function(){$('div.success').fadeIn();});
}
});
return false;
});
});
</script>
HTML FORM:
<form id="form" method="post" name="form" action="">
<fieldset id="opt">
<legend>Driver Information</legend>
<label for="choice">Name : </label>
<input type="text" id="name" name="name" value=""> <br />
<label for="choice">Licence No : </label>
<input type="text" id="licence" name="licence" value=""> <br />
<label for="choice">Email : </label>
<input type="text" id="email" name="email" value=""> <br />
<label for="choice">Phone : </label>
<input type="text" id="phone" name="phone" value=""> <br />
<input type="hidden" name="uno" id="uno" value="" />
<br />
</fieldset>
<div align="center">
<input id="button2" type="submit" value="Add Driver" />
<input id="button2" type="reset" />
</div>
</form>
I found multiple errors/mistakes on your HTML form too. some of them I want to mention..
for attribute of label have same value of the next input/select id, read:
http://www.w3schools.com/tags/att_label_for.asp
Dont assign name for name and id attribute, it's misleading.( good practice)
Don't write value ="", if you there is no initial value of any input box.
If u want to validate a hidden field then write some value for that on form intialization, otherwise it wud be always empty and your validation never works.
If u want to validate all input field together for emptyness then use :input selector ,read :
http://api.jquery.com/input-selector/
Don't forget to validate email address
If you want to post a form via ajax then there is no need to write method and action attribute in your form
Your reset button shoud have some value, otherwise its takes default value.
A very useful and handy article for newbie for jquery ajax validation
http://jorenrapini.com/blog/css/jquery-validation-contact-form-with-modal-slide-in-transition
OR you can use jquery validator plugin :
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
here is your neat and clean form
<form id="driverForm" name="driverForm">
<fieldset id="opt">
<legend>Driver Information</legend>
<label for="lname">Name : </label>
<input type="text" id="lname" name="lname" > <br />
<label for="licence">Licence No : </label>
<input type="text" id="licence" name="licence" ><br />
<label for="email">Email : </label>
<input type="text" id="email" name="email" ><br />
<label for="phone">Phone : </label>
<input type="text" id="phone" name="phone" > <br />
<input type="hidden" name="uno" id="uno" /><br />
</fieldset>
<div align="center">
<input type="submit" id="submitForm" name="submitForm" value="Add Driver" />
<input type="reset" value="clear" />
</div>
</form>
Hope this will be useful for you.
UPDATE
put it insdie submit() and before ajax like this
$("form").submit(function() {
if($('#lname').val() == '')
return false;
});
$.ajax({
NOTE: dont create dataString Manually there is inbuilt function in jQuery.
serialize
Please note that ,this is not matter that your form is submitting or not. most thing is it a valid form or not.
Happy to help :)
Related
I have this form here I am trying to send data to the controller using Ajax but something keeps failing and ajax is not working at all. I am trying to insert a question and sending the quiz id through the form and to the controller
<div id="form_two" class="container col-sm-8">
<div class="row card border-secondary align-items-center">
<div class="form-group col-sm-7">
<br><br>
<form id="report">
#csrf
<input type="hidden" name="quizTest" value="{{ \Illuminate\Support\Facades\Session::get('testID') }}">
<input class="form-control" id="question" type="text" name="question" placeholder="Question" size="40" required><br>
<input class="form-control" id="answerA" type="text" name="answerA" placeholder="Option A" size="40" required><br>
<input class="form-control" id="answerB" type="text" name="answerB" placeholder="Option B" size="40" required><br>
<input class="form-control" id="answerC" type="text" name="answerC" placeholder="Option C" size="40" required><br>
<input class="form-control" id="answerD" type="text" name="answerD" placeholder="Option D" size="40" required><br>
<input class="form-control" id="correct_answer" type="text" name="correct_answer" placeholder="Correct Answer" size="40" required><br>
<button class="btn btn-primary" id="registraion-form" >ADD A QUESTION </button>
</form>
</div>
</div>
</div>
Here is my ajax code that I am trying to send data to the /test endpoint, but when I am submitting the form nothing is printing on the console.log and nothing is being returned from the response from the controller which leads to the conclusion that ajax is not working. When I am pressing the submit button only the URL is changing, what I am doing wrong?
$('#registraion-form').click(function (e) {
e.preventDefault();
let question = $("input[name=question]").val();
let answerA = $("input[name=answerA]").val();
let answerB = $("input[name=answerB]").val();
let answerC = $("input[name=answerC]").val();
let answerD = $("input[name=answerD]").val();
let quizTest = $("input[name=quizTest]").val();
let correct_answer = $("input[name=correct_answer]").val();
$.ajax({
type: "POST",
url: "/test",
data : {
quizTest: quizTest,
question : question,
answerA:answerA,
answerB:answerB,
answerC:answerC,
answerD:answerD,
correct_answer : correct_answer
},
success: function(response) {
console.log(response);
console.log(response.message);
$("#report")[0].reset();
},
error : function (error) {
console.log(error);
}
})
})
just because you have added #csrf to your form, doesn't mean that you're ok on everything.
Since AJAX is submitting a POST request, also that request should have with it the csrf token, otherwise it won't work.
Check for example this question.
I am trying to apply ajax with my spring mvc, but couldn't find where I make thing wrong. I try to follow several tutorials but couldn't customize mine to work. It always falls to error state.
So this is my ajax call
function doAjax() {
var username = $('#username').val();
var email = $('#email').val();
var password = $('#password').val();
var json = {
"username" : useranme,
"email" : email,
"password" : password
}
//alert("username: " + username + " email: " + email + " password: " + password);
$.ajax({
type: "POST",
url: $('form').attr('action'),
data: JSON.stringify(json),
dataType: "JSON",
success: function(data) {
},
error:function(data, status, err) {
alert("error");
}
});
};
And this is my form:
<div class="form">
<spring:url var="registerUrl" value="http://localhost:9004/Project/register" htmlEscape="true" />
<form method="post" action="${registerUrl}">
<div class="form_field">
<label for="username">Username</label><br/>
<input class="field" id="username" type="text" name="userName" autocomplete="off"/>
</div>
<div class="form_field">
<label for="email">Email</label><br/>
<input class="field" id="email" type="email" name="email" autocomplete="off" />
</div>
<div class="form_field">
<label for="password">Password</label><br/>
<input class="field" id="password" type="password" name="password" />
</div>
<div class="form_field prefix_clear">
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
<input id="submit" class="action_button" type="submit" value="Register"/>
</div>
</form>
Click me
</div>
So if I submit the form using the input, it works perfectly. But it doesn's work when I try to submit it using anchor tag. Please help.
To make your ajax call work exactly as a form submit, you should, instead of using the JSON, just replace your data:JSON.stringify to
data:$("form").serialize();
If you have to make a request with JSON data, than you'll have to edit your question with the mapping method and command object to get help, but one thing that is obviously wrong with your code, is that you're not including the _csrf parameters in your ajax request
Received http://examle.com/ajax/login.html:
<form method="post" action="/login.html" name="formLogin" data-ng-model="formLogin" data-ng-submit="submitLogin($event)" novalidate="novalidate" >
<input type="hidden" csrf="csrf" data-ng-model="formLogin.csrf" value="" name="LoginForm[csrf]">
<input type="text" data-ng-minlength="2" data-ng-required data-ng-model="formLogin.email" placeholder="e-mail" autofocus="autofocus" name="LoginForm[email]"></div>
<span class="error" ng-show="formLogin['LoginForm[email]'].$error.required">Required!</span>
<input type="text" data-ng-minlength="2" data-ng-required data-ng-model="formLogin.password" placeholder="password" autofocus="autofocus" name="LoginForm[password]"></div>
<span class="error" ng-show="formLogin['LoginForm[password]'].$error.required">Required!</span>
<button ng-disabled="formLogin.submitted" name="login-button" class="btn btn-primary" type="submit">OK</button>
</form>
The directive code looks as below:
app.directive('formLogin', function(){
return {
require: 'ngModel',
link: function(scope, element, attrs, ngModelCtrl) {
var inputs = element[0].querySelectorAll('input');
}
};
});
In a classic example, if specify the name of the form, the form controller will be published into related scope, under this name. Is it possible to do for AJAX-loaded form, something like?
The problem is in the validation inputs after loading form.
Hi I've a page with two textboxes and I wanted to apply required validator to both controls. But when I run my code it is applying to only first control. Even though I've given both text boxes as blank, it is showing first text box as required.
Here is my code and not getting where do I missed the second one.
<input type="text" name="firstname" id="firstname" required validationmessage="First name required" />
<input type="text" name="lastname" id="lastname" required validationmessage="Last name required" />
<button class="k-button" id="btnAdd" onclick="addDetails();">Add</button>
function addDetails() {
var validator = $("#btnAdd").kendoValidator().data("kendoValidator");
if (validator.validate()) {
// Add details to db
}
}
Kendo Validator has to be applied to the input that you are validating not to the button. The HTML should be something like:
<div id="my-form">
<div>
<label>
Firstname:
<input type="text" name="firstname" id="firstname" required validationmessage="First name required"/>
</label>
</div>
<div>
<label>
Lastname :
<input type="text" name="lastname" id="lastname" required validationmessage="Last name required"/>
</label>
</div>
</div>
<button class="k-button" id="btnAdd">Add</button>
And the validation function:
$(document).ready(function () {
var validator = $("#my-form").kendoValidator().data("kendoValidator");
$("#btnAdd").on("click", function () {
if (validator.validate()) {
// Add details to db
console.log("good");
} else {
console.log("bad");
}
});
});
I have some mvc frameworks that extend my .net application. Their task is mainly to deliver partials to the .net applications interface.
The funny thing is that chrome strips the very necessary
Here is how I fetch and render the data from the framework
$.ajax({
url: "/mvc/UserProfile/AddressForm?datatype=shipping",
dataType: "text", // text html script
method: "get",
cache: false,
success: function (data) {
console.log(data);
//var userProfileAdd = document.getElementById("userProfileAdd");
var userProfileAdd = $("#userProfileAdd")[0];
userProfileAdd.innerHTML = "<div>" + data + "</div>";
}
});
Firefox, IE and so on does retrieve all data. Does anyone know why chrome behaves like this?
Thanks
EDIT
This is the code sent to the data variable printed by console.log
<script src="/scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="/scripts/MicrosoftMvcValidation.js" type="text/javascript"></script>
<form OnSubmit="return false;" action="/mvc/UserProfile/AddressFormPost" id="frmUserAddress" method="post"><div class="validation-summary-valid" id="validationSummary"><ul><li style="display:none"></li>
</ul></div>
<input name="__RequestVerificationToken" type="hidden" value="8Vkd039Wc3825G6CTEomJ/aXfrCyjuEY3sV/ty4znHi9yO0Th535p8VNxqvBwhJ12AREQhvTMhRVNEO6Ke3O87jDAjREg3I3dFYp2Y5geutbEOLk6KHmn6hLb4a5CFaZ3uCOm8uYgr/U4au33yaUFw==" />
<div>
Select country:
<select id="Countries" name="Countries"><option value="029">Caribbean</option>
<option value="AE">U.A.E.</option>
<option value="AF">Afghanistan</option>
<option value="AL">Albania</option>
<option value="AM">Armenia</option>
<option value="AR">Argentina</option>
</select>
</div>
<div>
Postal Code
<input class="formField textBox" id="PostalCode" name="PostalCode" type="text" value="" />
<span class="field-validation-valid" id="PostalCode_validationMessage"></span>
</div>
<div>
City
<input class="formField textBox" id="City" name="City" type="text" value="" />
<span class="field-validation-valid" id="City_validationMessage"></span>
</div>
<div>
State
<input class="formField textBox" id="State" name="State" type="text" value="" />
<span class="field-validation-valid" id="State_validationMessage"></span>
</div>
<div>
First name
<input class="formField textBox" id="FirstName" name="FirstName" type="text" value="" />
<span class="field-validation-valid" id="FirstName_validationMessage"></span>
</div>
<div>
Email
<input class="formField textBox" id="Email" name="Email" type="text" value="" />
<span class="field-validation-valid" id="Email_validationMessage"></span>
</div>
<div>
<input type="submit" value="Send!" id="btnAddressForm" class="button" />
</div>
</form><script type="text/javascript">
//<![CDATA[
if (!window.mvcClientValidationMetadata) { window.mvcClientValidationMetadata = []; }
window.mvcClientValidationMetadata.push({"Fields":[{"FieldName":"PostalCode","ReplaceValidationMessageContents":true,"ValidationMessageId":"PostalCode_validationMessage","ValidationRules":[{"ErrorMessage":"Please enter your postal code","ValidationParameters":{},"ValidationType":"required"}]},{"FieldName":"City","ReplaceValidationMessageContents":true,"ValidationMessageId":"City_validationMessage","ValidationRules":[{"ErrorMessage":"Please enter your city","ValidationParameters":{},"ValidationType":"required"}]},{"FieldName":"State","ReplaceValidationMessageContents":true,"ValidationMessageId":"State_validationMessage","ValidationRules":[{"ErrorMessage":"Please enter your state","ValidationParameters":{},"ValidationType":"required"}]},{"FieldName":"FirstName","ReplaceValidationMessageContents":true,"ValidationMessageId":"FirstName_validationMessage","ValidationRules":[{"ErrorMessage":"Please enter your first name","ValidationParameters":{},"ValidationType":"required"}]},{"FieldName":"Email","ReplaceValidationMessageContents":true,"ValidationMessageId":"Email_validationMessage","ValidationRules":[{"ErrorMessage":"Please enter your first name","ValidationParameters":{},"ValidationType":"required"}]}],"FormId":"frmUserAddress","ReplaceValidationSummary":false,"ValidationSummaryId":"validationSummary"});
//]]>
</script>
Chrome will strip out the form element if there is a surrounding form element. JUST the form tag disappears, all of its contents remain.
Check to make sure that there isn't a parentNode for "userProfileAdd" that is a form.