disable all click events till ajax request is completed - javascript

So I have a listing page something like this:
//start loop
<div id ='row-prd-<number>'>
<strong>product Name</strong>
<a href='#' id='edit-prd-<number>'>Edit</a>
<a href='#' id='delete-prd-<number>'>Delete</a>
</div>
//end loop
In my javascript, I do something like:
$('#delete-prd-<number>').click()
{
//change style of the row to show its being deleted..
$('row-prd-<number>').addClass('deleting');
//make ajax call to delete
ajaxDeleteRecord(prd-<number>);
}
Now, this works fine. My concern is that in a lower connection speed scenario, the delete ajax call takes a few seconds to complete. I am concerned about what happens if the user clicks on an edit or delete button of another record. So I have three questions:
1. Should I disable all click events on the page until the ajax call returns?
To me this does not seem like a good option - suppose the ajax call errored out...in that case the user now is in a state where s/he cannot click on anything in the page anymore!
2. How then should I handle this?
...I am kinda just lost as to what to do. I guess this is the most important of the three questions I have.
1. If I had to disable and re-enable clicks on the elements on the page (edit/delete/new) is there an easy way to do it?
...just curious...

your scenario 1 will do the trick in order to do disable all the other events. It will be kind of neat as well.
You can have another thing to have the ajax call be synchronous rather than being asynchronous by setting
async:false
in the call.
The syntax would look something like this:
$.ajax({
url: 'your url',
global: false,
type: 'POST',
data: {},
async: false,
success: function() {},
error: function() {}
});

Related

Ajax success code not loading in synchronous manner

We are expecting the below things:
Would like to show the page with updated values.
Then show the session attribute.
What is happening for the below code, session message displayed first and then the page is getting reload.
$.ajax({
type: "POST",
url: "startSelectedServer",
data: { selectedJvmHostIp : selectedJvmHostIp, selectedJvmPort : selectedJvmPort },
success: function(result){
1. location.reload();
2. $("#save-message-div").show();
},
error : function(e) {
}
});
<div id="save-message-div" style="background-color: #DFF2BF; padding: 8px;display:none">
<h2 id="save-message" style="color: #4F8A10"></h2>
</div>
But we are expecting to show message after reloading the page.
In above 2 is executing first then 1 is executing.
ok it appears to me that you are trying to perform a server-side functionality and then refresh the page and have a message appear that the functionality has occurred.
This is fine as far as it goes but will not work the way you have it. To do it closest to the way you invision you will want to put in conditional logic on page load to determine if it is appropriate to show the div.
Even if your page did not show the div prior to reloading, the way it is written, when the page reloads it will not still be executing the same piece of script - it is a blank slate with only what you pass to it.
I am not sure why you want to reload the page at all actually; you can, and should [to make use of ajax], just use the information client-side that is returned from the server asynchronously.

JQuery call not working after Ajax call succeeds

I have an Ajax call that looks like this:
$("#start-upload-btn").click(function(){
$.ajax({
type: "post",
url: "",
data: {
newProjectName: $('#project-name').val(),
csrfmiddlewaretoken: csrfToken
},
success: function(data){
$("#file-upload").click();
}
})
});
Upon success I want to perform a click on the element with id #file-upload to launch the file selection dialogue, but putting the code in success function fails to work. It works anywhere else. Is there something special about the scope of the Ajax success function? I really cannot figure this out.
Thanks
There is nothing inherently problematic about issuing a click on any normal element (including a button) from an ajax success callback.
The problem is that a file-input dialog is not a "normal element". It has some specific security limitations - one of which clearly limits your interaction with it.
This is demonstrated by the following fiddle: https://jsfiddle.net/qhfwobpz/
You'll see that issuing a click on the file-upload directly works without a problem. Doing it from an ajax callback yo'll see the callback is called, but the file dialog never shows.
This answer gives more detail as to the "why" and it boils down to you can open the dialog from an event issued by the user but not purely programatically.

Commenting System - Showing posted comment without page reload

working on a commenting system using PHP.
Everything works, the insert, the validation and also the ajax call.
Currently i am doing a .load() on the container that holds the page content.
However, this causes issues when trying to post comments again. The javascript doesnt work, some of the javascript functions linked with the comments also dont work and little things like that.
How should i be dealing with comments, every time a user posts one.
Like on facebook for example, you post a comment and the new one is just placed underneath the last.
The only thing i can think of i using .append() and appending the new comment to the list.
In my PHP page i could set a JSON return of the username, the comment, the users profile picture etc and then append all of that data back?
Otherwise is there a better method of simply 're-loading' the div container after the success ajax call?
Thanks, what i have works... but i want to be learning things the CORRECT way.
Craig.
You can use $.ajax to load new comments and use .append() or prepend() to insert the new comments in the container. If you wrap the call in a function you can call the function over and over (for instance every 2 seconds) to check for new comments.
If I remember correctly .load() will only execute when the element is ready after browser refresh.
What things are not working? Remember that events and data must be bound after succesful AJAX call. Meaning if you bound events to links when the page loaded they are obviously still in effect. But if you insert a link later on it does not have any events.
What I would normally do is something like this:
$.ajax({
url: 'ajax.php',
data: { 'parameters': 'yada yada' },
dataType: 'json',
success: function( data ) {
$('.links').unbind().click(function() { alert('hello!'); });
}
});
The reason for the .unbind() is that you will otherwise bind several events on the existing links - and you don't want that ;-)

Check for page refresh or close with jQuery/javascript

I am looking to check if a page has been refreshed or closed with jQuery or javascript.
What I have currently is I have some database values that I want to delete if the user either navigates away or refreshes the page.
I am using AJAX calls to delete the values.
Right now, I have the following code:
The handler:
window.beforeunload = cleanUp;
The cleanUp() method:
function cleanUp() {
// Check to see if it's an actual page change.
if(myActualLeave) {
$.ajax({
type: "POST",
url: "/api/cleanup",
data: { id: myLocalId },
success: function (data) {
console.log(myLocalId + " got removed from the database.");
}
});
}
// Reset the flag, so it can be checked again.
myActualLeave = true;
}
Where myActualLeave is a flag that I set to false when AJAX calls are made, so they don't trigger the beforeunload handler.
The problem I am running into is that when I click a link on my page, so for instance a link to Google, the window.beforeunload doesn't trigger. I may have a misunderstanding of this, but I have tried using jQuery's $(window).unload(...); and the onbeforeunload trigger as well.
What should I use to call javascript when:
the user refreshes the page,
when the user navigates away from the page, or
when the user closes the page?
Edit: It came up in a comment that I could use a click() jQuery handler to detect navigating away. I should have made it more specific that I don't mean when the user clicks a link only then I want it to proc. I want it to trigger when they change pages in any way. So if the address bar gets typed in, for instance.
You should try "onbeforeunload" :
window.onbeforeunload
But i think you can't put "active" (ajax call) code in this callback function. All you can do is defining a confirm modal window that will be displayed to the user before leaving like :
Are you sure you want to leave because...
So you should do as #Leeish said : put a code in the .on('click') of the link so it can launch the ajax call before sending to another page.
But for the "refresh" or "close" scenario, you can consider marking your database row as "draft" (or whatever) and if not saved when on the next page, delete the draft line.

Ajax page load in div halts browser even if it is async?

I am trying to do async page open inside div with $.ajax but i am still having about 3sec delay after clicking link and that time page is jammed. Happens at least chrome and sasfari. Where am i going wrong way..?
$.ajaxSetup({
async: true
});
$(document).ready(function() {
$("#Button").click(function(evt) {
$('#change').html('<p><img src="ajax-loader.gif" width="15" height="15" /></p>');
$.ajax({
url: "reg.php",
cache: false
}).done(function( html ) {
$("#change").html(html);
});
});
});
No, asynchronous ajax requests like that don't hold up the browser. The problem is elsewhere, in code you haven't shown. The code you've shown will correctly do an async request.
Speculating on possible issues with what we can't see:
If the link has an href, you're not cancelling the default action, so it could be loading the page. You can prevent the default by calling evt.preventDefault() within your click handler, or by doing return false; at the end of it (which does that and also stops propagation).
If you have other code elsewhere setting async: false as the default, perhaps your ajaxSetup changing it back isn't getting called.
If you are using PHP sessions then the script will halt the browser until reg.php is completely finished.
In reg.php you will need to add this somewhere:
session_write_close();
This will allow you to read the session data but not write to it.
This is the case because you would probably never want two ASYNC scripts trying to write to the session at the same exact time.

Categories

Resources