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.
Related
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 am trying to update the description field for a record in a database using a JQuery.change for the input on the view. However, after wiring up my clientside code I am now getting a circular reference exception when trying to stringify the JSON in order to make the ajax call. Any help would be greatly appreciated.
Here's the code:
<div class="divTableCell">
<label for="CheckRunDescription" id="checkRunDescriptionLabel">Description:</label>
<input type="text" id="CheckRunDescription" style="width: 270px;" />
</div>
The JQuery:
$('#CheckRunDescription')
.change(function() {
$(this).data("old", $(this).data("new") || "");
var newDetails = $(this).data("new", $(this).val());
updateCheckRunDetails(newDetails);
});
function updateCheckRunDetails(newDetails) {
var checkRunID = $('#checkRunID').val();
var js = JSON.stringify({ checkRunDetails:newDetails, checkRunID:checkRunID });
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: './PayInvoicesWS.asmx/UpdateCheckRunDetails',
data: js,
dataType: "json",
success: function (data) {
},
error: function (data) {
}
});
}
You are trying to stringify a jQuery object.
var newDetails = $(this).data("new", $(this).val());// returns `$(this)`
I am guessing you want the input value passed to the function
Try
$('#CheckRunDescription')
.change(function() {
var newDetails = $(this).val();
$(this).data("old", $(this).data("new") || "").data("new", newDetails );
updateCheckRunDetails(newDetails);
});
I am working on notification system and loading html notification body from database to views which populate as follows:
<form id="acceptInviteForm" method="POST">
<input type="hidden" name="accountId" value="6">
<input type="hidden" name="operation" value="acceptinvite">
<button class="acceptinvite btn btn-primary" href="/acceptinvite" onclick="acceptingRequest();">Accept Invitation</button>
</form>
and applying jQuery function which I already defined on same page is like this:
// Accept invitation button click
jQuery(document).ready(function() {
function acceptingRequest() {
var formData = jQuery("#acceptInviteForm").serialize();
alert(formData);
jQuery.ajax({
type: "POST",
url: "/acceptinvite",
data: formData,
dataType: "json",
beforeSubmit: function() {
jQuery(this).attr({"disabled":"disabled"});
},
success: function(data) {
alert("Success");
},
error: function() {
alert("Got error while accepting invitation, reload or contact administrator!");
}
});
}
});
So when user click on button it's not work even not showing alert.
But things gets more interesting when I inject above jquery function from chrome console while view is loaded and button start working fine and shows alert too!
I am not getting the point which not letting things work!
It's because your acceptingRequest function is visible only inside anonymous jQuery(document).ready callback.
So when you click the button acceptingRequest is not visible.
Solutions keeping jQuery(document).ready(function() {})
To solve this bind the handler inside the callback using $('button.acceptinvite').on('click',acceptingRequest)
or use an anonymous callback (something like this):
$('button.acceptinvite').on('click',function(){
var formData = jQuery("#acceptInviteForm").serialize();
alert(formData);
//Etc.
});
In both cases remove onclick="acceptingRequest();" since it's no longer needed.
Another option is to make acceptingRequest visible outside using a global variable (it's not a good practice anyway):
acceptingRequest = function () {
var formData = jQuery("#acceptInviteForm").serialize();
alert(formData);
//Etc.
}
Now acceptingRequest is visible outside jQuery().ready and you can do onclick="acceptingRequest();"
Solutions without jQuery(document).ready(function() {})
If you don't need the DOM to be completely loaded (like in this case) you can remove
jQuery(document).ready(function() {}) and just write your function from in head, so they are visible to the button.
<script>
function acceptingRequest() {
var formData = jQuery("#acceptInviteForm").serialize();
alert(formData);
//Etc.
}
</script>
Let me know if this was useful.
I think you are defining the function acceptingRequest() on document ready, but you are not really calling it. Try adding:
acceptingRequest();
just after the definition of the acceptingRequest() function. The result would be:
// Accept invitation button click
jQuery(document).ready(function() {
function acceptingRequest() {
var formData = jQuery("#acceptInviteForm").serialize();
alert(formData);
jQuery.ajax({
type: "POST",
url: "/acceptinvite",
data: formData,
dataType: "json",
beforeSubmit: function() {
jQuery(this).attr({"disabled":"disabled"});
},
success: function(data) {
alert("Success");
},
error: function() {
alert("Got error while accepting invitation, reload or contact administrator!");
}
});
}
acceptingRequest();
});
It is because this string
<button class="acceptinvite btn btn-primary" href="/acceptinvite" onclick="acceptingRequest();">Accept Invitation</button>
will be proceded by the browser earlier than the definition of your acceptingRequest function. 'acceptingRequest' in your code will be defined asynchronously when document ready fired. So browser can't assign it with the click listener. Try to put your script exactly before </body>(and after jQuery script) and without jQuery(document).ready
<script>
function acceptingRequest() {
var formData = jQuery("#acceptInviteForm").serialize();
alert(formData);
jQuery.ajax({
type: "POST",
url: "/acceptinvite",
data: formData,
dataType: "json",
beforeSubmit: function() {
jQuery(this).attr({"disabled":"disabled"});
},
success: function(data) {
alert("Success");
},
error: function() {
alert("Got error while accepting invitation, reload or contact administrator!");
}
});
}
</script>
</body>
Function defined in ready state can be used in it's own scope.So you can use acceptingRequest() method in ready state.
in my view below code is bestpractice in event binding:
<form id="acceptInviteForm" method="POST">
<input type="hidden" name="accountId" value="6">
<input type="hidden" name="operation" value="acceptinvite">
<button class="acceptinvite btn btn-primary" id="acceptInviteButton" href="/acceptinvite" onclick="acceptingRequest();">Accept Invitation</button>
</form>
and in ready state:
jQuery(document).ready(function() {
function acceptingRequest() {
var formData = jQuery("#acceptInviteForm").serialize();
alert(formData);
jQuery.ajax({
type: "POST",
url: "/acceptinvite",
data: formData,
dataType: "json",
beforeSubmit: function() {
jQuery(this).attr({"disabled":"disabled"});
},
success: function(data) {
alert("Success");
},
error: function() {
alert("Got error while accepting invitation, reload or contact administrator!");
}
});
}
$("#acceptInviteButton").on("click",acceptingRequest);
});
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
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