Ajax calls getting incremented every time after the content is loaded - javascript

I m loading some content using ajax call, Inside that contents there are some hyperlinks which when user clicks it loads the content in the same div the problem is when the user clicks the back botton(another ajax call) the content of the div is repalced with the old content(having hyperlinks) ,now when u again click the Hyperlink its functions smoothly but its goes to the action twice, and this phenomenon keeps on increasing the no of time u press the back button and click on some Hyperlink.
Please anyone help me know what exactly happening to the process which is causing increment in action call every time the user clicks it
UPDATE
$(document).on("click",".selector",function(){
var link=($(this).parent().find("td a").attr("href"));
$.ajax({
type : "POST",
async : true,
url : link,
statusCode : {
404 : function() {
alert("Error in Application");
}
},
cache : false,
success : function(data) {
alert(data);
$('#load').html('');
$('#load').html(data);
}
});
});

Try with Call event.stopPropagation(); after successfull ajax request

Related

Jquery / Javascript: Is there a way to check if ajax is still in progress when user revisits a page?

I have a page that will generate details of a record. When the user comes to this page, he/she will have to press a 'generate' button to create the details of the record. Since it will take some time to generate the record, the moment the user clicks the button, it will trigger an ajax request.
$("#generate_record_button").on("click", function() {
$(this).addClass('disabled');
// Show some loading messages, and spinner
$.ajax({
url: "<generate-record-url/>",
method: 'get',
data: {id: <recordID>},
cache: false
}).success(function (data) {
// Do something on success
// Show some success messages
// Remove spinner
}).fail(function (data) {
// Do something on failure
// Show some error messages
// Remove spinner
$(this).removeClass('disabled');
});
});
In the code, currently when the user presses the button, the button will be disabled to prevent from potential multiple ajax requests being triggered if user keeps pressing the button. By right, user should only press the button once and just let the ajax handles the request accordingly.
My question is, is there a way to check if the ajax request is still running in the event when the user leaves the page? (Eg: refresh the page, navigate to other page, etc etc). What I would hope to achieve is that if the user re-visits back this page while the ajax is still processing the record (for that particular record ID), the button will remain disabled so that user can't press it and will see some loading messages. Is this possible?
Your user should not leave the page while ajax is running since it will be cancelled.
How about
$(window).on('beforeunload', function(){
if ($("#generate_record_button").hasClass("disabled"))
return 'Are you sure you want to leave?';
})

Data appended to title tag after ajax call is not displaying on first hover

Hi I have a ajax request that will fetch username, email and user_id. After ajax call success I am appending data using jquery to title tag, main issue I am facing is data getting appended but it is not showing on first attempt, but showing on second time hover.
Here is my code
function showProfile(i)
{
var user = $("#user_id_"+i).html();
var business = <?php echo $this->identity()->getBusiness()->getId() ?>;
$.ajax({
'url': '/user/account/external/profile',
'type':'GET',
'data':{
businessId:business,
userId:user,
},
'success': function (data) {
var message = "Fullname : "+data.first_name+" "+data.last_name+" Email : "+data.email;
$("#user_id_"+i).attr('title',data.first_name+'\n'+data.last_name+'\n' +data.email);
},
});
}
Here is my html code which initiating ajax call
<a id="user_id_btn_'.$k.'" class="user_id_btn" onmouseover="showProfile('.$k.')" onmouseout="hideProfile('.$k.')"><span id="user_id_'.$k.'">'.$iResult[$k][4].'</span></a>
can anybody tell me how to improve this? I want to show data on hover on first attempt only not second.
onmouseover="showProfile('.$k.')" means, that when your mouse moves over this element, the function is called.
So if you would make an ajax request when the mouse hovers, the call starts and the data isn't loaded, when the browser processes the tooltip.
On second hover, the data is written from the first call.
Try to set the tooltip before hovering and then you don't need onmouseover because the tooltip is just shown when hovering ;)

How to wait for task to finish before moving on to next part of the code

I have a "Save" button that I need to trigger when the user clicks Next/Previous buttons on my page. When the user clicks next to move onto another window I trigger a "save" button that saves the changed the user had mad and some other functionality. The problem is when I click the next or previous button the save button is triggered but needs time to save the changes and the code keeps on executing. Is there a way I can tell whether the save has finished or delay my code somehow? I know I can do a time delay but it could be different for every user and inefficient. Here is an example:
function prev_next(){
$('#save').trigger('click'); //This line could take 2-5 seconds to finish
//Other code here that opens next window
}
Any advice will be appreciated.
You will have to edit the function that gets triggered by clicking the save button, to allow for a callback function. (I assume there is an ajax request that is sent to some server to save).
Example:
Save function:
function saveEdits(callback){
$.ajax({
url: 'urltosavepage.php',
method: 'post',
data: {
somevar: 'somevalue'
},
success: function(response)
{
callback();
}
});
}
prev_next function:
function prev_next()
{
saveEdits(function(){
// Code that is here will not get executed until after the ajax request is completed, and the success function gets called.
//Other code here that opens next window
});
}

jQuery function to sometimes redirect after an AJAX Request is completed and to sometimes remain on the page?

I have a page that lets you Add/Edit/Delete "Project Tasks" and Save the data to a database using jQuery's AJAX function to save the POST data.
I currently have 2 buttons on the page.
Button 1 .save-tasks-ajax-redirect - You click it and it makes a regular non-ajax POST to my backend and you are redirected to another Project page. This button does not have a click event yet. Perhaps the best way might be to simply create a new click event for this button class and then have it call my save function but it could pass in a variable to indicate that it needs to redirect? Before I posted this questions I was sort of hoping to have both button share the same click event and everything but perhaps this is a better idea?
Button 2 .save-tasks-ajax - You click it and it uses AJAX to Save the data and you can remain on the page editing more.
Now my goal is to modify how Button 1 works. Instead of making a regular HTTP POST, I would like for it to also make an AJAX save but when it is done, I would like it to redirect to a project page.
So below I have my 2 button HTML codes. Below that I have my jQuery Click event for my AJAX save button (Button 2) and below that I have my ajaxSaveTasks() function that my button calls to make the save.
I would like to modify this function and perhaps all of this code so that my Button 1 can use the same function to make an AJAX save but somehow it needs to differentiate itself so that it can also do a redirect after the AJAX save is complete.
Looking at the basic code below, how could I modify this to do that?
<button type="submit" class="save-tasks-ajax-redirect">Save Tasks and Return to Project</button>
<button type="submit" class="save-tasks-ajax">Save Tasks and Continue Editing</button>
$(window).load(function () {
// AJAX Save and Continue editing
$('#content').on('click', '.save-tasks-ajax', function () {
console.log('AJAX Save and Continue Editing Button Clicked!');
ajaxSaveTasks();
return false; // avoid to execute the actual submit of the form.
});
});
function ajaxSaveTasks(){
console.log('ajaxSaveChanges() Ran and Tasks Saved.');
// Reset Flag that Triggers Un-Saved Alert on page exit
window.unsavedChanges = false;
// Show a Loading/Saving Spinner
jQuery('#project_tasks').showLoading();
// Display a message to the user that we are Saving
flipNotify.show({
message: 'Project Tasks Saved!',
icon: 'tick',
delay: 2,
sticky: false
});
var url = "index.php?module=apoll_Web_Projects";
$.ajax({
type: "POST",
url: url,
data: $("#editTasksForm").serialize(), // serializes the form's elements.
success: function(data)
{
// Hide Header Un-Saved Changes Div
hideTaskUnSavedChangesHeaderBar()
// Hide Loading/Saving Spinner
jQuery('#project_tasks').hideLoading();
}
});
};
$(window).load(function () {
// AJAX Save and Continue editing
$('#content').on('click', '.save-tasks-ajax', function () {
console.log('AJAX Save and Continue Editing Button Clicked!');
ajaxSaveTasks();
return false; // avoid to execute the actual submit of the form.
});
// AJAX Save and redirect
$('#content').on('click', '.save-tasks-ajax-redirect', function () {
console.log('AJAX Save and Redirect Button Clicked!');
ajaxSaveTasks(function(){ window.location.assign("project.php"); });
return false; // avoid to execute the actual submit of the form.
});
});
function ajaxSaveTasks(callback){
... your code ...
$.ajax({
...
success: function(data)
{
// Hide Header Un-Saved Changes Div
hideTaskUnSavedChangesHeaderBar()
// Hide Loading/Saving Spinner
jQuery('#project_tasks').hideLoading();
if (callback)
callback();
}
});
};

Call Ajax on unload if user clicks "OK"

I'm designing a rather long form that will auto-save every couple minutes (i.e., using Ajax, the form data will be inserted or updated into the MySQL database). However, if the user decides to exit the page before submitting the form, I want to make sure I delete the row that was inserted into the database. This is easily do-able if the user simply clicks another link or the form's Cancel button. But I'm concerned about what happens when the user: 1) closes the page, 2) reloads the page, or 3) hits the browser's back (or forward) button. I know how to use the unload event to create a confirmation dialog asking the user to confirm they want to leave the page. But what I don't know is how to make an Ajax call (to delete that row from the database) if the user clicks OK ("Press OK to Continue"). Is there any way to call a function if a user clicks the OK button during the unload event?
window.onbeforeunload = function() {
if ($('#changes_made').val() == 'yes') //if user (partially) filled out the form
{
return "Are you sure?"
if (/*user clicks OK */) //What should the if statement evaluate here?
{
//make Ajax call
}
}
};
$(document).ready(function() {
$(':input',document.myForm).bind("change", function() {
setConfirmUnload(true);
}); // Prevent accidental navigation away
});
function setConfirmUnload(on) {
// To avoid IE7 and prior jQuery version issues
// we are directly using window.onbeforeunload event
window.onbeforeunload = (on) ? unloadMessage : null;
}
function unloadMessage() {
if(Confirm('You have entered new data on this page. If you navigate away from this page without first saving your data, the changes will be lost.')) {
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
}
}
Make sure you have upgraded version of jQuery. jQuery version 1.3.2 had a bug:
Ticket #4418: beforeunload doenst work correctly
Or use native function:
window.onbeforeunload = function() {....}

Categories