I have an ajax function to calculate and perform a certain validation.
Code is shown below:
function collectFormData(fields) {
var data = {};
for (var i = 0; i < fields.length; i++) {
var $item = $(fields[i]);
data[$item.attr('name')] = $item.val();
}
return data;
}
function calculate(){
var $form = $('#purchase-form');
var $inputs = $form.find('[name]');
var data = collectFormData($inputs);
$.ajax({
url: '${validateUrl}',
type: 'POST',
data: data,
contentType: 'application/json; charset=utf-8',
success: function (response) {
alert(response.status);
},
error: function () {
alert("error");
}
});
}
HTML:
<button id="calculateBtn" class="btn btn-primary" onclick="calculate();">
<spring:message code="button.calculate" />
</button>
However, as soon as the above function called my form is being submitted. What might cause this ?
It is because you have a form with a button, whose default behaviour is to submit the form. If you do not want to submit the form then you need to prevent the default action of the button on click.
Since you are using jQuery I recommend using jQuery to register the click event instead of using onclick attribute and the calculate method has to return false value to prevent the default click event from happening.
Change to
<button id="calculateBtn" class="btn btn-primary">
<spring:message code="button.calculate" />
</button>
function calculate(){
var $form = $('#purchase-form');
var $inputs = $form.find('[name]');
var data = collectFormData($inputs);
$.ajax({
url: '${validateUrl}',
type: 'POST',
data: data ,
contentType: 'application/json; charset=utf-8',
success: function (response) {
alert(response.status);
},
error: function () {
alert("error");
}
});
return false;
}
$(function(){
$('#calculateBtn').click(calculate)
})
Try setting the 'type' attribute on the button to 'button'
<button type="button" id="calculateBtn" class="btn btn-primary" onclick="calculate();">
<spring:message code="button.calculate" />
</button>
The default value of the type attribute is 'submit': https://developer.mozilla.org/en-US/docs/HTML/Element/button
Related
I have a form in HTML where I have used onsubmit to validate input and action to call the URL on form submit. This is my HTML code:
<form method="POST" onsubmit="return validateInput();" action="editConf" id="edit-form">
// HTML Form code
<div class="modal-footer">
<p id = "edit-footer" align="center"> </p>
<button type="reset" onClick="resetForm()" class="btn btn-secondary" data-dismiss="modal" >Cancel</button>
<button type="submit" class="btn btn-primary">Save changes</button>
</div>
This is my script code:
function validateInput() {
// some validation code
$.ajax({
url: "validate_credentials",
type: 'POST',
data: { data: document.getElementById('data') },
dataType: 'json', // added data type
success: function(res) {
if (res && valid) {
$("#bigerror").innerHTML = res;
return true;
} else {
return false;
}
}
});
I am facing the issue that the URL in action completes its execution first so even if the form is not valid it is submitting. How to solve this issue ?
Since $.ajax is asynchronous, you can't use the return value of the success function.
You need to prevent the default submission immediately, then call submit() in the success function.
Also, in the data: option you need to get the value of an input, the input element itself.
function validateInput() {
// some validation code
$.ajax({
url: "validate_credentials",
type: 'POST',
data: {
data: $("#data").val()
},
dataType: 'json', // added data type
success: function(res) {
if (res && valid) {
$("#bigerror").innerHTML = res;
$("#edit-input").submit();
}
}
});
return false;
}
To prevent this from looping infinitely, because submit() runs the same validation function first, remove onsubmit from the form, and move it to the submit button.
<button type="submit" class="btn btn-primary" onclick="return validateInput();">Save changes</button>
You should prevent default event if you want to have custom async validation.
<form id="myForm" method="POST" action="editConf" id="edit-form">
fix your script to
$('#myForm').on('submit', validateInput)
function validateInput(event) {
event.preventDefault(); //Here we stoped defauld submit event
// some validation code
$.ajax({
url: "validate_credentials",
type: 'POST',
data: { data: document.getElementById('data') },
dataType: 'json', // added data type
success: function(res) {
if (res && valid) {
$("#bigerror").innerHTML = res;
return true;
} else {
return false;
}
}
});
Now the form won't be submitted. But now you have to think how you want to send data of the form to the server. There are several variants.
1) You can get form data and send it with ajax imitating the form
2) You can store a flag somewhere marking your form valid and if it is valid don't stop submit the form from your script and don't stop the event.
I would like to get an id from a button. I need this id in my ajax request. This is my button:
<form>
<div class="form-group">
<button class="btn btn-primary" name="deletecar" id="{{$car->id}}">Delete</button>
</div>
</form>
I'm getting the id of the button this way:
<script type="text/javascript">var JcarID = this.id;</script>
Finally my Ajax Request.
$('[name="deletecar"]').click(function (e)
{
var JcarId = this.id;
e.preventDefault();
$.ajax({
type: "POST",
url: '{{ action('CarController#delete', [$user->id, $car->id])}}',
success: function (data)
{
// alert(data);
}
});
});
Thx for reading!
SOLUTION
Changed some bits in my code. I changed the url of my request.
$('[name="deletecar"]').click(function (e)
{
e.preventDefault();
$.ajax({
type: "POST",
url: '/users/{{$user->id}}/deletecar/'+this.id,
success: function (data)
{
// alert(data);
}
});
});
Hard to guess what is your requirement yet either if you want to get the button id value
this.attr('id'); or this.prop('id');
Or if you want to set the id value of button
$('[name="deletecar"]').attr('id', yourvalue)
I think you want to use JcarId rather $car->id in ajax request. Here what you can do rather than directly using PHP code in ajax call.
$('[name="deletecar"]').click(function (e)
{
var JcarId = this.id;
e.preventDefault();
$.ajax({
type: "POST",
url: '/CarController/delete',
data: {'carId':JcarId}
success: function (data)
{
// alert(data);
}
});
});
I'm trying to make a button in ASP.NET that call a ajax function and return another ASP.NET, with a method do search in my database. When I click into the button the ajax function it doesn't trigger, doesn't do anything.This Ajax will take something that the user will digit, like a ZIP-code, and will search in my database.
var cepjs = $('#MainContent_cepBrasil').val();
alert(cepjs);
$('#ButtonCEP').click(function () {
alert('cliquei');
$.ajax({
type: "POST",
url: "CEP.aspx/Consulta_CEP",
data: JSON.stringify({ scep: cepjs}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
$('#MainContent_cepBrasil') = result.CEEP.localCEP;
$('#MainContent_ufEnderecoBrasil') = result.CEEP.localUF;
$('#MainContent_codMunicipioEnderecoBrasil') = result.CEEP.localMunicipio;
$('#MainContent_tpLogradouro') = result.CEEP.localTpLog;
$('#MainContent_descLogradouroBrasil') = result.CEEP.localLogradouro;
$('#MainContent_complementoBrasil') = result.CEEP.localComplemento;
$('#MainContent_bairroBrasil') = result.CEEP.localBairro;
}
});
});
<div class="form-group">
<!--<input Type="button" ID="ButtonCEP" name="btnConsultar_CEP" Class="btn btn-primary btn-sm" value="Consultar" />-->
<button id="ButtonCEP">Consultar</button>
</div>
I've try it to do everything in the ajax, even change the click.function to on('click', function()), but didn't work too, and i try to use some different forms in button style, with button and input type button.
Anyone could help me, I'll appreciate. Thanks
You have 2 errors here, you are not including the jquery source file, and not waiting for the doc to be ready
$( document ).ready(function() {
console.log( "ready!" );
var cepjs = $('#MainContent_cepBrasil').val();
alert(cepjs);
$('#ButtonCEP').click(function () {
alert('cliquei');
$.ajax({
type: "POST",
url: "CEP.aspx/Consulta_CEP",
data: JSON.stringify({ scep: cepjs}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
$('#MainContent_cepBrasil') = result.CEEP.localCEP;
$('#MainContent_ufEnderecoBrasil') = result.CEEP.localUF;
$('#MainContent_codMunicipioEnderecoBrasil') = result.CEEP.localMunicipio;
$('#MainContent_tpLogradouro') = result.CEEP.localTpLog;
$('#MainContent_descLogradouroBrasil') = result.CEEP.localLogradouro;
$('#MainContent_complementoBrasil') = result.CEEP.localComplemento;
$('#MainContent_bairroBrasil') = result.CEEP.localBairro;
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<!--<input Type="button" ID="ButtonCEP" name="btnConsultar_CEP" Class="btn btn-primary btn-sm" value="Consultar" />-->
<button id="ButtonCEP">Consultar</button>
</div>
Can you try invoking the function after DOM is ready by
$(document).ready(function() {
//
});
Thanks guys, I've got the solution, I was calling the .ready function into another .ready function, and that was the problem, i just don't know why , but I put this function out off it in the beginning of the code, and it work. Thanks for the helping.
Form validation works, but I can't get the Ajax call to fire correctly. The submitHandler is being reached, but the Ajax call isn't. I have included a Fiddle at the bottom, but obviously you can't fire ajax calls from there.
$(".player-code, .submit").hide();
//VALIDATION
$(function () {
$("#form").validate({
rules: {
playerClass: {
required: true
}
},
submitHandler: function () {
var accountNumber = $(".accountNumber").val();
var domain = $(".domain").val();
var playerClass = $(".playerClass").val();
var dataString = accountNumber + playerClass;
//Save Form Data........
$.ajax({
type: "POST",
dataType: "json",
url: "/",
contentType: "application/json",
data: dataString,
success: function () {
$(".player-code").show();
$('.render-info').html("<div class='alert alert-success'>You've successfully built your player code</div>");
},
failure: function () {
$('.render-info').html("<div class='alert alert-failure'>Submission Error</div>");
}
});
}
});
});
jQuery.validator.addMethod("domainChk", function (value, element, params) {
if (this.optional(element)) return true;
var regExp = new RegExp("^(?!www\\.|http:\/\/www\.)(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\\.)+([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$");
return regExp.test(value);
}, "Valid hostname required for player code");
jQuery.validator.addClassRules({
domainChk: {
domainChk: true
}
});
$('input[type="text"]').on('click keyup blur', function () {
if ($('#form').valid()) {
$(".submit").show();
} else {
$(".submit").hide();
}
});
//PREPOPULATE ACCOUNT FROM QUERY STRING
var url = window.location.href;
var regex = /=.*/; // match '=' and capture everything that follows
var accountId = url.match(regex);
$(".accountNumber").val(accountId).remove("=");
//
jsFiddle: Link
There is no failure: option for $.ajax(). If you want to see any errors that happen in the ajax call, then use error: to capture the error.
To make form submit you should use
<button class="btn btn-default submit" type="submit">Submit</button>
instead of <div class="btn btn-default submit">Submit</div>
submitHandler will be called only on native form submit.
Fiddle
If i have something like:
<form method="post" id="customForm" action="">
//stuff
<div id="copiar">
<button class="button" href="#" id="btnAdd0">
<span class="icon icon3"> </span>
</button>
<button class="button" href="#" id="btnDel0">
<span class="icon icon58"> </span>
</button>
<button class="submeter">
<span class="label">Send</span>
</button>
</div>
</form>
and:
<script type="text/javascript">
$(document).ready(function() {
$("#customForm").submit(function() {
var formdata = $("#customForm").serializeArray();
$.ajax({
url: "validation.php",
type: "post",
dataType: "json",
data: formdata,
success: function(data, data1) {
//stuff
});
return false;
});
});
</script>
At the moment, the three buttons send the form. My idea is only permit the submit action in this button:
<button class="submeter">
<span class="label">Send</span>
</button>
I already tried $("#customForm > #copiar > button.submeter").submit(function() {
but the page is reloaded. So isn't working.
Any idea ?
You have to stop the other buttons from submitting first and then do your submit. Also when using an ID for your selector there really isn't any need to combine it with another ID like #customForm > #copiar "
Try this:
$(document).ready(function() {
$("#customForm").submit(function(e) {
e.preventDefault();
var formdata = $("#customForm").serializeArray();
$.ajax({
url: "validation.php",
type: "post",
dataType: "json",
data: formdata,
success: function(data, data1) {
//stuff
}
});
});
$("#customForm button").click(function(e) {
var me = $(this);
e.preventDefault();
if(me.hasClass("submeter")) $("#customForm").submit();
});
});
And as has already been pointed out, you don't need/want the href="#"
In order to prevent the default behavior of the form, you must use preventDefault() as follows:
$(document).ready(function() {
$("#customForm").submit(function(e) {
e.preventDefault();
var formdata = $("#customForm").serializeArray();
$.ajax({
url: "validation.php",
type: "post",
dataType: "json",
data: formdata,
success: function(data, data1) {
//stuff
});
});
$("#customForm button.submeter").click(function() {
$("#customForm").submit();
});
});
What is exactly the purpose of first two button element with the href attribute? I suspect you're using a button instead of a regular link only for a formatting/visual reason.
Anyway for your purpose, just add the attribute type="submit" to the last button and remove the submit handler you've defined for this button, it should work fine.
edit. you also need to call the preventDefault() method to stop page reload, as pointed out by phil klein