making ajax call fire only once - javascript

I have an ajax call that is being fired multiple times.
I have used e.stopImmediatePropagation() and return false to prevent it from firing more than once. Is there another sure shot way to prevent ajax call more than once.
$(document).on('click', '#button1', function(e){
$.ajax({
url: 'http://www.page.com',
data: data,
method: 'POST',
success: function(data){
},
error: function(err){
}
});
e.stopImmediatePropagation();
return false;
});

You can use jQuery .one()
$(document).one('click', '#button1', function(e){
$.ajax({
url: 'http://www.page.com',
data: data,
method: 'POST',
success: function(data){
},
error: function(err){
}
});
});
var n = null;
$(document).one('click', '#button1', function(e){
$.ajax({
url: 'https://gist.githubusercontent.com/anonymous/9a6997f09de9b68c59b2/raw/f7d7b756005ad6d2b88cf0211f78a2990d7d2dc7/content.json',
data: {},
method: 'HEAD',
success: function(data, textStatus, jqxhr) {
console.log(jqxhr.getAllResponseHeaders())
$("body").append("<br>textStatus: " + textStatus + "<br>count: " + ++n)
},
error: function(err){
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="button1">click</button>

You can use jquery.data() to store a boolean to indicate whether your function has been run before.
$(document).on('click', '#button1', function(e) {
$button = $("#button1");
if ($button.data("pressed") !== true) {
$.ajax({
url: 'http://non-existentpage',
data: {},
method: 'POST',
success: function(data) {
alert('ajax');
$button.data("pressed", true);
},
error: function(err) {
alert('ajax');
$button.data("pressed", true);
}
});
}
});
#button1 {
border: 1px solid #000;
display: inline;
padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="button1">ajax</div>

You could also add a condition checking if the button has already been clicked by setting a variable to true after it has been clicked:
window.document_clicked = false;
$(document).on('click', '#button1', function(e){
if(!window.document_clicked){
$.ajax({
url: 'http://www.page.com',
data: data,
method: 'POST',
success: function(data){
window.document_clicked = true;
},
error: function(err){
}
});
}
});

Adding async: false to your current function
or USE .click
$('#button1').click(function(e){
});

Setting async to false means that the statement you are calling has to complete before the next statement in your function can be called.
$(document).on('click', '#button1', function(e){
$.ajax({
url: 'http://www.page.com',
data: data,
async: false,
method: 'POST',
success: function(data){
},
error: function(err){
}
});
e.stopImmediatePropagation();
return false;
});

Try this instead
$('#button1').click(function(e){
$.ajax({
url: 'http://www.page.com',
data: data,
method: 'POST',
success: function(data){
},
error: function(err){
}
});
Much simpler and it should fix that issue of multiple ajax calls.
You also shouldn't have to return false.

Related

Select only the clicked button JQuery

I have this ajax function, which should change the style of the clicked button, but for some reason it does not work. I'm not getting any errors in the console and the ajax call is successful Any idea what's wrong here?
function AcceptOffer(id)
{
var json = {
id : id
};
$.ajax({
type: 'POST',
url: "#Url.Action("AcceptOffer", "Product")",
dataType : "json",
data: {"json": JSON.stringify(json)},
success: function() {
$(this).text("Accepted");
$(this).css("background-color", "green");
$(this).css("color", "white");
$(this).attr('disabled', true);
},
error: function(data) {
alert('Some error');
window.location.reload();
}
});
}
</script>
Html:
Accept
Your issue is with using this incorrectly. The way you are using it, it is going to reference the object you pass into the ajax command
function AcceptOffer(id)
{
var json = {
id : id
};
var elemYouWantToChange =...;
$.ajax({
type: 'POST',
url: "#Url.Action("AcceptOffer", "Product")",
dataType : "json",
data: {"json": JSON.stringify(json)},
success: function() {
$(elemYouWantToChange).text("Accepted");
$(elemYouWantToChange).css("background-color", "green");
$(elemYouWantToChange).css("color", "white");
$(elemYouWantToChange).attr('disabled', true);
},
error: function(data) {
alert('Some error');
window.location.reload();
}
});
}
-- Edit --
In javascript, you listen for a click like so:
elem.addEventListener('click', function(e) {
console.log(e.target); // You need to get e.target to AcceptOffer so it can style the correct element
AcceptOffer(...);
});
In your code this is not pointing to the anchor tag you just need to pass this reference to your function.
function AcceptOffer(ele, id)
{
var json = {
id : id
};
$.ajax({
type: 'POST',
url: "#Url.Action("AcceptOffer", "Product")",
dataType : "json",
data: {"json": JSON.stringify(json)},
success: function() {
$(ele).text("Accepted");
$(ele).css("background-color", "green");
$(ele).css("color", "white");
$(ele).attr('disabled', true);
},
error: function(data) {
alert('Some error');
window.location.reload();
}
});
}
So the anchor tag will be:
Accept

Jquery ajax loading with async

Jquery Ajax Loading not working with async
Code below
$('#pagination').on('click','a',function(e){
e.preventDefault();
var data = $(this).attr('data-pagination-page');
var selector=$('.frmTable');
var response=getData(selector,data);
});
Ajax Function
function getData(selector,data){
var result="";
var frmAction=$(selector).attr('action');
$.ajax({
url: frmAction+'/'+data,
type: 'post',
data: $(selector).serialize(),
async: false,
beforeSend: function(){
console.log("Request Submiting....");
$('#loading').css('display','block');
},
success: function(response){
result = response;
},
complete:function(data){
$('#loading').css('display','none');
console.log("Request Complete....");
}
});
return result;
}
Can you provide me suggestion how deal with ajax loading icon.
Using setTimeout problem is solve
function getData(selector,data){
var result="";
var frmAction=$(selector).attr('action');
$.ajax({
url: frmAction+'/'+data,
type: 'post',
data: $(selector).serialize(),
async: false,
beforeSend: function(){
console.log("Request Submiting....");
$('#loading').css('display','block');
},
success: function(response){
result = response;
},
complete:function(data){
console.log("Request Complete....");
setTimeout(function(){
$('#loading').css('display','none');
}, 500);
}
});
return result;
}

Submitting form with ajax and jQuery

I have a simple form with one select box and two options in it. Here is the related jQuery code:
$('.myCssClass').on('change', function() {
alert("This is executed");
$(this).parent().submit(function(e) {
alert("This is NOT executed");
$.ajax({
type: "POST",
url: "script.php",
data: $(this).parent().serialize(),
success: function(data)
{
alert(data);
}
});
e.preventDefault();
});
Form is a parent of a select box. So the first alert is executed when I change the select box option, but then next one is never reached. Any idea why?
This should do it. Don't bother with the submit event - it will not be triggered by a select box.
$('.myCssClass').on('change', function() {
$.ajax({
type: "POST",
url: "script.php",
data: $(this).parent().serialize(),
success: function(data)
{
alert(data);
}
});
});
You have to create the submit event listener outide the other event:
$('.myCssClass').parent().submit(function(e) {
$.ajax({
type: "POST",
url: "script.php",
data: $(this).serialize(),
success: function(data){
alert(data);
}
});
e.preventDefault();
});
$('.myCssClass').on('change', function() {
$(this).parent().submit();
});
Or as chain:
$('.myCssClass').on('change', function() {
$(this).parent().submit();
})
.parent().submit(function(e) {
$.ajax({
type: "POST",
url: "script.php",
data: $(this).serialize(),
success: function(data){
alert(data);
}
});
e.preventDefault();
});
But why two events? Just send the data on change:
$('.myCssClass').on('change', function() {
$.ajax({
type: "POST",
url: "script.php",
data: $(this).parent().serialize(),
success: function(data){
alert(data);
}
});
});
Try the following:
$('.myCssClass').on('change', function() {
alert("This is executed");
$(".form-with-class").submit();
});
$(".form-with-class").on('submit', function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "script.php",
data: $(".form-with-class").serialize(),
success: function(data){
alert(data);
}
});
});
$('.myCssClass').on('change', function() {
alert("This is executed");
$(this).parent('form#id').submit(); // improve performance by reducing the traversal
});
$("#form-with-id").on('submit', function(e){
e.preventDefault();
var data = $(this).serialize();
$.ajax({
type: "POST",
url: "script.php",
data: data,
success: function(data){
alert(data);
}
});
});
Hope this works.
when a handler is provided it just registers the handler but it does not perform the actual submit.
You may want to call:
$(this).parent().submit();
after your handler is registered. Furthermore, within your handler, you have to refer to the form just by "$(this)" (not: "$(this).parent()"), since the handler belongs to the form.
But since you'd call the submit explicit, there is no point in registering a handler which you then invoke. You could fire your ajax-request directly:
$('.myCssClass').on('change', function() {
alert("This is executed");
$.ajax({
type: "POST",
url: "script.php",
data: $(this).parent().serialize(),
success: function(data)
{
alert(data);
}
});
});

javascript function with jquery

I have a little function, im trying pass 2 parameters for her, but dont works...
Any idea/sugestion?
Don't have problems with ajax, i have tested this code without parameters, putting direct on the function, but calling her, not works, sorry about the terrible english!!
function myfunction(var_data, var_field)
{
$(function()
{
$.ajax
({
url : "myscriptajax.php",
type: "POST",
data: var_data + $(this).val(),
dataType:"json",
success: function(data)
{
if(data.status)
{
$(var_field).val(data.somevar);
}
}
})
})
}
$("#medicocrm").change
(function()
{
myfunction("crm=","#mediconome");
})
// edited after here for best explanation about.
That works:
$(function()
{
$("#medicocrm").change
(function()
{
$.ajax
({
url : "abertura.ajax.php",
type: "POST",
data: "crm=" + $(this).val(),
dataType:"json",
success: function(data)
{
if(data.status)
{
$("#mediconome").val(data.nome);
}
}
})
return false;
})
$("#participantematricula").change
(function()
{
$.ajax
({
url : "abertura.ajax.php",
type: "POST",
data: "matricula=" + $(this).val(),
dataType:"json",
success: function(data)
{
if(data.status)
{
$("#participantenome").val(data.nome);
}
}
})
return false;
})
\i tried this with first answer...
and that not works:
function verifica(dados,campoid,camponome){
$.ajax({
url : "abertura.ajax.php",
type: "POST",
data: dados + campoid,
dataType:"json",
success: function(data){
if(data.status){
$(camponome).val(data.nome);
}
}
});
return false;
};
$("#medicocrm").change(function(){
verifica("crm=",this.value,"#mediconome");
});
$("#participante_id").change(function(){
verifica("id=",this.value,"#participante_nome");
});
Just do a revamp.
function myfunction(var_data, var_field, elementValue){
$.ajax({
url : "myscriptajax.php",
type: "POST",
data: var_data + elementValue,
dataType:"json",
success: function(data){
if(data.status){
$(var_field).val(data.somevar);
}
}
});
};
$("#medicocrm").change(function() {
myfunction("crm=","#mediconome", this.value);
});
Here we removed the DOMContentLoaded listener and passed the value of the element through to the function..
You can use $(this).val(); in place of this.value whatever floats your boat.
You have a whole lot of wrappers going on, and your use of $(this) is likely breaking it. Something like this should work:
function myfunction(var_data,$var_field,whatever_this_is_val){
$.ajax({
url : "myscriptajax.php",
type: "POST",
data: var_data + whatever_this_is_val,
dataType:"json"
}).done(function(data){
if(data.status){
$var_field.value = data.somevar;
}
});
}
$("#medicocrm").on('change',function(){
myfunction("crm=",this,document.getElementById(whatever_this_is).value);
});
Changes:
Unnecessary wrappers removed
Passing of $(this) ... you need to specifiy it
Cleanup syntax to modern use of .done().
Using vanilla JS where easily applied
You should also consider explicitly declaring the page that it calls to be JSON, rather than saying dataType:'json' in your call. Its bulletproof this way, and less work performed on all sides.
EDIT
If you are really just passing the value of the item changed, easiest way to do it:
function myfunction(var_data,$var_field){
$.ajax({
url : "myscriptajax.php",
type: "POST",
data: var_data + $var_field.value,
dataType:"json"
}).done(function(data){
if(data.status){
$var_field.value = data.somevar;
}
});
}
$("#medicocrm").on('change',function(){
myfunction("crm=",this);
});
That way worked!!!!!! With many wrappers, but... Worked!
callajax = (function(origem,dados,campo)
{$.ajax({
url : "abertura.ajax.php",
type: "POST",
data: origem + "=" + dados,
dataType:"json",
success: function(data){
if(data.status){
$(campo).val(data.nome);
}
else{
$(campo).val("");
alert('Não encontrado');
}
}
})
});
$(function(){$("#medicocrm").change
(function(){
callajax('crm',this.value,"#mediconome");
});
});
$(function(){$("#participantematricula").change
(function(){
callajax('matricula',this.value,"#participantenome");
});
});
$(function(){$("#prestadorcodsoc").change
(function(){
callajax('codsoc',this.value,"#prestadornome")
});
});

double calls ajax using jquery

two calls:
$('#add').live('click', function() {
$('.simplebox').slideUp(200, function() {
$('html, body').animate({scrollTop:140}, 350, function() {
$('#loading-add').slideDown(300, function() {
$.ajax({
type: "POST",
url: "..",
data: getDataToPost(),
cache: false,
success: function(data){
alert(data);
$('#loading-add').delay(1000).fadeOut(200, function() {
$('#successfull-add').fadeIn(200);
});
}
});
});
});
});
})
But if i call to the ajax immediately after the live event, it calls on time (as it should be):
$('#add').live('click', function() {
$.ajax({
type: "POST",
url: "..",
data: getDataToPost(),
cache: false,
success: function(data){
alert(data);
$('#loading-add').delay(1000).fadeOut(200, function() {
$('#successfull-add').fadeIn(200);
});
}
});
})
There are any ideas why it happens? really strange..
Thank you.
Try using queue():
$('.simplebox').slideUp(200);
$('.simplebox').queue(function() {
$('body').animate({scrollTop:140}, 350);
$('body').queue(function() {
$('#loading-add').slideDown(300);
$('#loading-add').queue(function() {
//ajax call
});
});
})

Categories

Resources