I am creating a page that a user can click a link and it will $.ajax load the content into a container div. The problem is the source files all have $.ajax requests of there own, so when a user clicks 2 or more links, it begins incrementing the amount of $.ajax requests and the container div is overrun with data. Basically my goal is for the user to click a link and it loads the requested page (and begins $.ajax refreshing from the ajax loaded source). And when they click another link it clears the old $.ajax requests from the previous ajax loaded content.
$(function(){
$("a.text").click(function(){
$("#botscontainer").remove();
$("#botsparent").append("<div id=\"botscontainer\"></div>");
$.ajax({
url: $(this).attr("id") + ".html",
cache: false,
success: function(data){
$("#botscontainer").hide().append(data).fadeIn("slow");
}
});
return false;
});
});
You can see when user clicks link with class text, it will send an ajax request to a page with more ajax content (that is on an interval). So I need to clear the old "data" when the user clicks another link. I even went as far as completely removing the parent element and recreating it, but it won't remove the $.ajax requests from the data. Any help is appreciated.
Abort the previous requests... Try this...
$(function()
{
$("a.text").bind('click', Request);
});
function Request()
{
/* I put try catch so that if the xhr object doesn't exist it won't throw error */
try{
xhr.abort();
}
catch(e){}
xhr = null;
xhr = $.ajax({
url: $(this).attr("id") + ".html",
cache: false,
success: function(data){
$("#botscontainer").hide().html(data).fadeIn("slow");
}
}
return false;
}
Bind links to just one function... You are basically assigning them to their own AJAX.
You could cancel the request
var x;//in the outer scope of ajax call
x.abort();
x = $.ajax(params);
To do this you need to be using setInterval(). Simply make the var that holds the setInterval global, and on the first page you want to load ajax content into, use clearInterval(var) to stop the previous ajax requests.
$(function(){
$("a.text").click(function()
{
clearInterval(refreshId2);
$.ajax({
url: $(this).attr("id") + ".html",
cache: false,
success: function(data){
$("#botscontainer").hide().html(data).fadeIn("slow");
}
});
return false;
});
});
Related
I am using onbeforeunload event to send ajax request to perform some clean up task.
When I am using onbeforeunload, it shows the confirmation dialog on closing the tab.
What I want is not to show any confirmation dialog and just send the clean up request. Following is the script I am using.
window.onbeforeunload = unloadFunction;
function unloadFunction() {
var test_id = $('#test_id').val();
jQuery.ajax({
url: "/test/cleanup/" + test_id,
cache: false
}).done(function () {
return false;
});
return false;
}
Is there any way I can suppress the confirmation dialog?
As per some suggestions, I have tried to change return statement to return ; instead of return false; . But this is also not working.
As per my comments on the original post, the answer is to make the call synchronous by adding async: false in the Ajax call settings, change the last return false to return null;, and remove the done function:
window.onbeforeunload = unloadFunction;
function unloadFunction() {
var test_id = $('#test_id').val();
jQuery.ajax({
url: "/test/cleanup/" + test_id,
cache: false,
async: false
});
return null;
}
When the user closes the page the document is dead, the scripts are dead. You're expecting the script to run after they close. Now if the tab doesn't close it feels like it's frozen waiting for your function to finish. Meaning it's not possible. I believe that's what you want? The clean up request won't send because the document is closed.
I want to count number of click to particular div(#counter) and then redirect to a different site.
I did a ajax call on click event of the div with the id counter. and then on success function i'm doing a redirect on ajax complete. Here is the code
jQuery('#counter').click(function(){
var data = { clicked:'yes'
};
jQuery.ajax({
url:"stat.php",
type:"POST",
data:data
}).done(function(res){
window.location = "http://www.myurl.com";
});
});
The thing is, this is making some time to redirect such that user have to wait until the ajax complete event trigger.
Since am not care of the response i just need a request that initiates user has clicked that(#counter) div so i'll just increment the value in DB. So is there a way to redirect to a different website as soon as the ajax started? I don't want the user to wait for the response and then redirect. because the response is not needed in this case. This is only for site stat or what is the best way to count a button click and then redirect them to a different site.
Edit, updated
Try
jQuery('#counter').click(function(){
data = { clicked:'yes'
};
var redirect = function() {
setTimeout(function() {
window.top.location.href = "http://stackoverflow.com/questions/"
+ "25554598/"
+ "how-to-perform-a-count-statistics-"
+ "without-wait-for-ajax-response/";
}, 1500); };
$.when(jQuery.ajax({
url:"/echo/json/",
type:"POST",
data:{json:JSON.stringify(data)}
}), redirect())
.done(function(_data) {
alert(_data[0].clicked)
})
});
jsfiddle http://jsfiddle.net/guest271314/51g5huvq/
Just move your redirect code outside of the .done callback. This way, when you click, two things are instantly done : an ajax request is sent, and the redirection is fired. You can wrap the redirection in a short setTimeout to make sure the ajax request has been fired before redirecting the client.
jQuery('#counter').click(function(){
var data = { clicked:'yes'
};
jQuery.ajax({
url:"stat.php",
type:"POST",
data:data
}).done(function(res){
});
setTimeout(function(){window.location = "http://www.myurl.com";}, 500);
});
I am building a messaging system for my site. The mailbox is flat, i.e. accessing the inbox, or sending a new message does not move to another page, it just toggles divs. When a user clicks a message, an AJAX call replaces the inbox div with the chosen thread. Inside the thread view, there is a form to reply to the message.
A few problems:
From inside this thread_view, which sends an AJAX response to a div nested inside the entire mailbox div, I don't have access to document objects outside of it. So, I can't manipulate divs outside of this view, such as the one that receives the AJAX beforeSend and Success messages. I think this may be accomplished with some kind of .load(), though I'm not sure exactly how.
My AJAX doesn't fire. I am using the Ajax.Form() plugin. I think this problem might be related to the first, but I can't say for certain. I'm not sure how to begin troubleshooting the Ajax request because I get no errors in the console.
I wonder if the problem has to do with the fact that I am trying to send an ajaxRequest from a view that is itself a response from a previous ajaxRequest, i.e. the entire view for the thread is a result of the following, in the same js file as the next request:
// compose a message function
$('#send_message').on("click", function(e) {
var send_message_options = {
type: 'post',
url: "/users/new_message",
beforeSend: function() {
//Display a loading message while waiting for the ajax call to complete
$('#message').html("Sending message...");
},
// Hide form and display results
success: function(response) {
$('#message').html(response);
}
};
$('#message_form').ajaxForm(send_message_options);
});
My new AJAX request, which does nothing:
$('#reply_in_thread').on("submit", function(e) {
e.preventDefault();
console.log("trying for reply");
var reply_options = {
type: 'post',
url: "/users/reply",
beforeSend: function() {
//Display a loading message while waiting for the ajax call to complete
$('#reply_message').html("Sending message...");
},
// Hide form and display results
success: function(response) {
$('#reply_message').html(response);
}
};
$('#reply_in_thread').ajaxForm(reply_options);
});
I couldn't say why the ajaxForm() plugin failed, but a jquery $.post was successful. The code that worked below:
$('#reply_in_thread').on("submit", function(e) {
e.preventDefault();
var data = $(this).serialize();
$.post('/users/reply',data,function(response){
$('#reply_message').html(response);
})
});
I am pretty new to this, so go easy on me:
I am building an image gallery with a main index page which allows users to select different categories of projects, a sub-index page which allows users to select specific projects within their selected category, and then the gallery page for that project.
The code below is for the main index page. I am trying to pass the value of the src attribute of the first image of the first gallery page to the main index page to use as a thumbnail.
I have effectively been able to load the correct URL into the imageLoc variable, but I need to pass it outside of the Ajax request to pass it into my HTML document.
Simply put, I am trying to pass the value of the imageURL variable to the imageLoc variable.
Thanks for your help.
$('.galleryIndex a img').hide().each(function(){
var destination = $(this).parent('a').attr('href');
var imageLoc = $.ajax({
url: destination,
success: function(data){
var pageLoc = $(data).find('.galleryList a:first').attr('href');
$.ajax({
url: pageLoc,
success: function(data){
var imageURL = $(data).find('.galleryBox img:first').attr('src');
return imageURL
}
});
}
});
alert(imageLoc);
});
This will cause troubles do to the way the callback function is handled. It's a closure block that is called after the request has returned, so it runs apart from your main code in the function. If you want to alert the imageURL variable, alert it inside the callback function, or call another function to handle it. Since it is a callback function for an asynchronous server request, the part that alerts "imageLoc" will have run long before you ever get your async request back.
Edit: The only way to achieve what you're trying to do is to not make the ajax request asynchronously. If you set async:false, then you can call on the "responseText" property like this:
var html = $.ajax({
url: "some.php",
async: false
}).responseText;
But be warned...this will halt browser operation while the request is pending. It's usually best to block user interaction by other means if you don't want them to screw with the page while something is loading.
I was able to get what I wanted as follows:
$('.galleryIndex a img[id!="fp"]').hide().each(function(){
var destination = $(this).parent('a').attr('href');
$.ajax({
url: destination,
context: $(this),
success: function(data){
var pageLoc = $(data).find('.galleryList a:first').attr('href');
$.ajax({
url: pageLoc,
context: $(this),
success: function(data){
var imageURL = $(data).find('.galleryBox img:first').attr('src'); //returns the src for the thumbnails
$(this).attr('src', imageURL);
$(this).load(function(){
$(this).show();
});
}
});
}
});
});
I have a jquery ajax request in my website page, and every page i need to post this request to server to get the status. But it have a issue: after i open the page in browser, before this request return the data, my page all link can't works, they can't click.But it render normal. so anybody have a solution for that? such as: make the page load this script after page loaded or other.
$(function(){
var login_status;
$.ajax({
async:false,
url:<%= url(:login_status_header_session, :from => from_uri).to_json %>,
dataType:"html",
success:function(data, textStatus){
login_status = data;
}
});
if(login_status) {
$(".loginDetails p .login_status").html(login_status);
} else {
$(".loginWrapper").remove();
}
});
this is the login_status_header actin:
self.headers["Cache-Control"] = "no-cache, must-revalidate"
self.headers["Expires"] = "0" partial "session_header",
:format => "html"
First, remove the async:false, line. This way the interface will keep responding while the AJAX request is being processed. Second, move your checking of the result into the success function - otherwise it runs before the request finishes, and so login_status hasn't been set yet (and thus defaults to null, which is treated as false).
$(function(){
var login_status;
$.ajax({
url:<%= url(:login_status_header_session, :from => from_uri).to_json %>,
dataType:"html",
success:function(data, textStatus){
login_status = data;
if(login_status) {
$(".loginDetails p .login_status").html(login_status);
} else {
$(".loginWrapper").remove();
}
}
});
});
Without more information I can only guess, and my guess is that since you're using async: false, the interface is not responding. Is there a reason for doing the request synchronously? If not try removing async:false and see if that works.
Uhm... without examining your code in too much detail, if this is supposed to occur at soon as the page is loaded, why not just put it on the server side, and generate the proper HTML in the first place? i.e. do it with PHP or whatever you're using and forget the AJAX?