I have this ajax request script:
function SendData(){
$( "#Submit" ).click(function() {
$('#Submit').attr("disabled", true);
$.ajax({
type:"POST",
url:"assets/process.php",
data: {
Years : $('#Years').val()
},
success: function(Response){
if (Response.Status == 'Error') {
swal("Ups!", "Nemo' zebavaš", "error");
} else if (Response.Status == 'Error0') {
swal("Ups!", "Servis 'Misterije' mogu koristiti samo rođene osobe!", "error");
}
else if (Response.Status == 'Error120') {
swal("Ups!", "Žao nam je! Niste podobni za korišćenje WEB Servisa 'Misterije'!", "error");
}
else if (Response.Status == 'Success') {
swal("USPEŠNO!", 'Rođeni ste: '+Response.Calculated+' godine!', "success");
}
$('#Submit').attr("disabled", false);
}
});
});
}
When I load page in browser, add data to input and click on button nothing happens, but on second and all clicks after until I refresh page all working OK.
How I can slove this problem?
Don't call the function
Put your code in $(document).ready function
Presumably you're calling this SendData() function when you click the button?
This function isn't doing what you think it's doing. It's not invoking the AJAX request. All this function does is attach the click handler to the button. Nothing more. Then the next time you click the button, that handler will execute.
(Not to mention that it would also again attach another click handler. So the third click would invoke the handler twice. And so on...)
There's no need to wrap all of this in a function. Instead of this:
function SendData(){
$( "#Submit" ).click(function() {
// your code
});
}
just do this:
$( "#Submit" ).click(function() {
// your code
});
This will attach the click handler, not invoke it. Any time afterward when you click the button the handler will be invoked.
At worst, you'd have to do this if the button doesn't exist yet when this code executes:
$(function () {
$( "#Submit" ).click(function() {
// your code
});
});
This would wait until the document.ready event and then attach the handler.
(Note: You'll also want to remove any reference to SendData() once you've removed that function. I'm assuming you're calling it in-line from the button. But you don't need to do that when you're attaching a click handler with jQuery.)
Related
I have a clickable <td> which does some action. However, strange things happen when I quickly make double click. Thus, I want to prevent it and make sure it is only single clickable event.
$.each(response, function(index) {
$('#myID').append('<tr><td onclick="select(this)" >'+ response[index] +'</td></tr>');
});
function select(element){
...
}
I tried to use jQuery's .one() function, but this code above is a product of another event. So, I cannot use $(document).ready(); here. In my knowledge I have to make it like onclick="select(this)"... And it works. But here I need to disable double clicking.
Any help?
So add a check that the Ajax request is active....
function select(element){
var elem = $(element);
if(elem.hasClass("active")) { // is ajax call active?
return false;
}
elem.addClass("active"); // set it that it is active
$.ajax({
url: "foo"
})
.done(function(){})
.always(function(){
elem.removeClass("active"); // call is done, so remove active state
})
}
You can simply disable button until ajax finishes its operation
function select(element){
$(element).prop('disabled', true);
$.ajax({
url'url',
success:function(response){
$(element).prop('disabled', false);
}
});
}
Given my below code Is there a way i can get alert when my ajax process is still in progress?
as you have already noticed code for alert will never get executed because of obvious reason that async ajax will keep happening but the value of click false will come before that and i will never be able to get alert during ajax call. Is there any way i can get alert when ajax request still in process?
<html>
<body>
<button type="button" id="submit-catalog" class="btn btn-primary">Activate</button>
</body>
</html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
var clicked = false;
$(document).on('click', '#submit-catalog', function() {
clicked = true;
//doing some ajax call which is taking time
});
if(clicked){ // never get executed
alert("button clicked")
//i am executing some function only if that button clicked
}
});
</script>
Your logic is off; here's how to do this:
var clicked;
$(document).ready(function() {
$(document).on('click', '#submit-catalog', function() {
if (clicked) {
console.log("ajax still in progress");
return false;
}
clicked = true;
console.log("starting ajax");
setTimeout(function () {
clicked = false;
console.log("ajax done");
}, 3000);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="submit-catalog" class="btn btn-primary">Activate</button>
I'm not sure if this is what you're looking for, but this will prevent the ajax from firing again and again based on the variable which keeps track of the ajax progress.
It's not about Ajax. Code is getting executed top to bottom, you declared event listener on the document and it waits for action, while your 'if' statement was already processed.
This 'Alert' or any other action should be done within event listener
Also, if you want to do any action before executing ajax request you simply use beforeSend: ()=>{/*your actions*/}, and then after ajax request is done success: callback=>{/*do when done*/}
which may look like that:
$.ajax({
url: url,
method: 'POST',
beforeSend: ()=> { alert('clicked') },
success: callback=> { console.log(callback) }
})
You can also use : one() instead of on() only if you don't use the clicked variable somewhere else. You attach the event for only one trigger. At the end of the callback you reattach it.
$(document).ready(function() {
function foo(e){
setTimeout(function () {
console.log("ajax done");
$(e.delegateTarget).one('click', '#submit-catalog', foo)
},1000)
}
$(document).one('click', '#submit-catalog', foo);
});
Other solution : add class to stop the propagation thanks to delegate event
$(document).ready(function() {
$(document)
.on('click', '#submit-catalog.prevent', function(e){
e.stopImmediatePropagation();
}
.on('click', '#submit-catalog', function(){
$(e.currentTarget).addClass('prevent');
setTimeout(function () {
console.log("ajax done");
$(e.currentTarget).removeClass('prevent');
}, 1000)
});
});
I know about event.preventDefault() and event.stopImmediatePropagation(). But it doesn't work for me. In my case I have such ajax call:
$('#templateConfirmDialog').on('show.bs.modal', function (event) {
$(this).find('.modal-yes').click(function(){
var form = form2js('search_form', '.', true, function (node) {}, false);
var requestData = JSON.stringify(form, replacer);
var $formErrors = $('.search_form').find('.alert-danger');
event.preventDefault();
event.stopImmediatePropagation();
$.ajax({
type: 'POST',
contentType : "application/json",
url: '/fraud/template/testCreate',
data: requestData,
dataType: 'json',
success: function (data) {
$formErrors.text('');
//if no errors just reload
if (data === undefined || data.length === 0) {
location.reload();
}
else {
//else bind error messages
data.forEach(function(error) {
$('#new-' + error.field + '-error').text(error.defaultMessage);
})
}
}
});
});
My problem is that the ajax call is prevented as much times as I made attempts to input data. If I entered invalid data once - ajax is called twice. If twice - 3 times. What may be a reason of such behavior?
Every time this event happens:
$('#templateConfirmDialog').on('show.bs.modal', function (event) {
You bind a new click event handler:
$(this).find('.modal-yes').click(function(){
So if you show.bs.modal twice, then you have two click event handlers both submitting the AJAX request. Instead, just bind the click event handler once to the target clickable element, instead of binding it every time the modal is displayed.
Replace this:
$('#templateConfirmDialog').on('show.bs.modal', function (event) {
$(this).find('.modal-yes').click(function(){
//...
});
});
With this:
$('#templateConfirmDialog').find('.modal-yes').click(function(){
//...
});
Or, if that element is dynamically added to the DOM, this:
$(document).on('click', '#templateConfirmDialog .modal-yes', function(){
//...
});
That way there's just a single click event handler created when the page loads, rather than adding a new handler every time you display the modal.
I've got this function:
$(document).ready(function() {
$('.post_button, .btn_favorite').click(function() {
//Fade in the Popup
$('.login_modal_message').fadeIn(500);
// Add the mask to body
$('body').append('<div class="overlay"></div>');
$('.overlay').fadeIn(300);
return false;
});
My page loads content with favourite buttons, but after Ajax call and generated additional new content the function doesn't work when you click new content's buttons. What could be not right?
That is because you are using dynamic content.
You need to change your click call to a delegated method like on
$('.post_button, .btn_favorite').on('click', function() {
or
$("body").on( "click", ".post_button, .btn_favorite", function( event ) {
Instead of this:
$('.post_button, .btn_favorite').click(function() {
do this:
$(document).on('click','.post_button, .btn_favorite', function() {
on will work with present elements and future ones that match the selector.
Cheers
class-of-element is the applied class of element. which is selector here.
$(document).on("click", ".class-of-element", function (){
alert("Success");
});
If you know the container for .post_button, .btn_favorite then use
$('#container_id').on('click', '.post_button, .btn_favorite', function () { });
so if '.post_button, .btn_favorite' are not found then it will bubble up to container_id
else if you don't know the container then delegate it to document
$(document).on('click', '.post_button, .btn_favorite', function () { });
Reference
I am not sure if I am getting your question right but you may want to try..
$.ajax({
url: "test.html"
}).done(function() {
$('.post_button, .btn_favorite').click(function() {
//Fade in the Popup
$('.login_modal_message').fadeIn(500);
// Add the mask to body
$('body').append('<div class="overlay"></div>');
$('.overlay').fadeIn(300);
return false;
});
Just try to paste your code inside done function.
Hope it helps :)
EDIT:
I also notice you are missing }); on your question.
The following worked for me
$(document).ready(function(){
$(document).bind('contextmenu', function(e) {
if( e.button == 2 && jQuery(e.target).is('img')) {
alert('These photos are copyrighted by the owner. \nAll rights reserved. \nUnauthorized use prohibited.');
return false;
}
});
});
You need to bind the jQuery click event once your ajax content is replaced old content
in AJAX success block you need to add code like here new response html content one a tag like
Click Me
So you can bind the new click event after change the content with following code
$("#new-tag").click(function(){
alert("hi");
return false;
});
Goal:
Disable links before ajax:success is received. (then i'll tell my app server thing to enable the links. I'm writing a simple board game, and don't want to be recieving multiple ajax requests before the first one is responded to, because it messes with the game logic.
<script type="text/javascript">
var disableLinks = false;
$("a").click(function(e){
if (disableLinks){
e.preventDefault();
}
});
$("a").ajaxStart(function(){
disableLinks = true;
});
$("a").ajaxStop(function(){
disableLinks = false;
});
</script>
And here are what the links look like:
<a href="/board/take_turn?id=313&x=1&y=2" data-remote="true">
<div class="ttt_square">
</div>
</a>
This is because your AJAX start and finish events never fire. Why? Because simply clicking a link isn't an AJAX request, and doesn't trigger the global AJAX events. To use the global AJAX events, you need to use an AJAX function such as .get( ), .load( ), or $.ajax( )
The code below, is mostly yours... I've just added 2 lines (which could even be reduced to 1, but I think it looks better this way)
var disableLinks = true;
$('a').click( function( e )
{
if( disableLinks )
{
e.preventDefault( );
}
var self = $(this);
$.ajax( { "url": self.attr( 'href' ) } );
} );
$('a').ajaxStart( function( )
{
disableLinks = true;
} );
$('a').ajaxStop( function( )
{
disableLinks = false;
} );
You've got a typo. e.prevenDefault(); should be e.preventDefault();
And this should be enough for disabling the default action. So you can rid of your onclick.
$("a").click(function(e){
e.preventDefault();
});
Edit:
Maybe this: jQuery - How can I temporarily disable the onclick event listener after the event has been fired?
or this: jQuery - How can I temporarily disable the onclick event listener after the event has been fired?
should solve your problem (if understand you correctly)
try this:
$('a').click(function(){
if (!this.hasClass('disabled')) {
this.addClass('disabled');
var self = this;
$.ajax({url: this.attr('href'),
complete: function(jqXHR, textStatus)
self.removeClass('disabled');
}
});
}
return false;
});