I'm creating script where I use AJAX from jQuery. I've got a problem, as on my website I've got hidden object. Moreover I use setInterval to frequently refresh a piece of my script. Everything works well, but until I click on link to set this hidden object to be visible. When I click on link and make object visible, setInterval stops refreshing page. This is my code to AJAX:
$(document).ready(setInterval(function() {
$.ajax({
type: "POST",
url: "score.php",
success: function(html){
$("#loadplace").hide().show().html(html);
}
});
return false;}, 60000));
and this is code for link:
$('div#bar a#squad1').click(function(e) {
e.preventDefault();
$('div#s1 table.events1').hide();
$('div#s1 table.index_players1').fadeIn();
});
$('div#bar a#events1').click(function(e) {
e.preventDefault();
$('div#s1 table.index_players1').hide();
$('div#s1 table.events1').fadeIn();
});
is there any solution in jQuery for my problem ?
P.S. I hope you understand what I wrote, I know that my English is not so good as I wish it to be.
Related
I have a cshtml page that has a link, and a div to display some content.
<a href="#" onclick="Show_New_Page('#First_Div')>My Link</a>
<div id="First_Div">
#Html.Partial("General_Page") <- This is the default page that gets displayed on load.
</div>
When you click on the link, the javascript function Show_New_Page gets called and the string '#First_Div' gets passed as a parameter. I pass the name of the div I wish for the ajax in Show_New_Page to put its success value. That function looks like this:
function Show_New_Page(div) {
$.ajax(
{
type: "POST",
url: url, //Declared above globally, unimportant
data: data, //Declared above globally, unimportant
success: function (result) {
$(div).html(result);
}
});
}
When you click on this link in Internet Explorer, the new page gets displayed fine with no issues. However, when you click on this link in FireFox, the entire page turns white and never successfully loads.
There are plenty of posts about issues with Ajax and different browsers, but I was unable to see one that helped me. Any hints or tips I can try are much appreciated. I am very unsure of why this is happening, so if I have left out any information I will certainly do my best to provide it.
There seems to be a missing closing ) when you are calling the Show_New_Page function. Also it's recommended to return false from click handlers to cancel default action:
My Link
Also you might prefer to give this anchor an id:
My Link
and then unobtrusively AJAXify it in a separate file to avoid mixing markup with javascript:
$(function() {
$('#myLink').click(function() {
$.ajax({
type: 'POST',
url: url, //Declared above globally, unimportant
data: data, //Declared above globally, unimportant
context: { id: $(this).data('id') },
success: function (result) {
$(this.id).html(result);
}
});
return false;
});
});
The issue here was the fact that my ajax views that were being passed down after clicking on a link were using document.write() statements. I have learned that this is strange to do after the page has already loaded. I've moved these statements up to the files that were not being loaded with ajax, and that fixed the problem. Thank you to everyone who commented and suggested ideas to me. It was the investigation of these ideas that lead me to the core issue!
The lesson: be careful with excessive document.write() statements in firefox!
I have a div block i want it to be automatically referrshed once or twice during when page is loading .
How can refresh/reload the div once or twice using jquery or javascript?
Where is it gonna reload from, what does the block look like ?
I would use jQuery ajax and reload content into the the div
but thats a much as I can say without having any idea about what the content is to look like , what the current content looks like or what you would receive back from an ajax call
hth
I don't know exactly what you mean but try to look this example
$(function () {
setInterval(function () {
$.ajax({
type: "POST",
cache: false,
url: "Ajax/funk.cshtml",
dataType: "text",
success: function (data) {
$('#divId').text(data);
alert('Load completed.');
}
});
}, 2000);
});
here:
setInterval performs the action every 2000 milliseconds;
jax/funk.cshtml - the file which will give you some text as a result(it may contain only #DateTime.Now for example in asp.net and will return time)
if you want renew the div only once you may use the same function for $(#somedive).onload();
or something like that.
Hope it will help!
I've made this to illustrate my issue:
http://jsfiddle.net/michaelhart/mUMHZ/
(Only tested in Chrome.)
In summary: I don't want the ajax activity indicator to go crazy when users tab away and come back.
I've tried
$("#notification").clearQueue();
$("#notification").hide();
$("#notification").clearQueue();
$("#notification").show();
before
$('#notification').fadeOut();
but that just makes the indicator stop functioning completely after a tab out.
I'm not sure if this is a bug in the way Google Chrome handles inactive tabs or in the way jQuery works when Chrome puts it to "sleep."
Any ideas?
The bug is noted in the jQuery bug tracker. The suggested fix is to, instead of using setInterval blindly, use the callback function of the animation to trigger restart with a setTimeout.
E.g.
$(document).ready(function() {
fetchAjax();
});
function fetchAjax() {
var randomnumber=Math.floor(Math.random()*10001);
$('#number').html(randomnumber);
$.ajax({
type: 'POST',
url: '/echo/html/',
data: {
'html': randomnumber
},
dataType: 'text/html'
});
}
$(document).ajaxStart(function(){
$('#notification').fadeIn();
}).ajaxStop(function(){
$('#notification').fadeOut(function(){
setTimeout(function(){ fetchAjax(); }, 5*1000);
});
});
Basically, I am trying to load the html and JavaScript file for each subpage on my website with ajax. However, the JavaScript file only loads for the first subpage that is clicked on. If I click on the next subpage, only the html document for that loads, but the javascript does not. This is from looking at the firebug console: Clicking on about first, then clicking on contact:
GET http:..../about.html?t=0.19504348425731444
GET http:..../about.js?t=0.8286968088896364
GET http:..../contact.html?t=0.8467537141462976
(!!!NO GET FOR contact.js!!!)
Anyways, I tried using live() to bind the click event but it still doesn't work.Here's the relevant snippets of my code:
$('.subpage').live('click',function(){
$('#main').css({'cursor':'crosshair'});
navsubpage = true;
subpage = $(this).attr('id');
$('.subpage').each(function(index) {
$('#'+$(this).attr('id')).fadeOut('500');
$('#'+$(this).attr('id')+'select').fadeOut('500');
});
$('#'+subpage+'h').css({'background-color':'#000','display':'block'});
$('#'+subpage+'h').animate({'width':'375px','top':'120px','left':'100px','font-size':'400%'},'500');
subtop = $('#'+subpage+'h').css('top');
subleft = $('#'+subpage+'h').css('left');
$('#pane').css({'border-left-width':'0px'});
$('#nav').css({'background':'url("images/'+$(this).attr('id')+'.jpg") no-repeat 0px 0px'});
$('#nav').animate({'left':'0px'},'4000','swing',function(){
$('#reload').show().delay(500).queue(function(){
alert("made it");
$.ajax({
url: subpage+".js?t=" + Math.random(),
dataType: 'script',
type: 'get',
});
});
});
reload(subpage);
});
$('#main').click(function(){
if(navsubpage==true){
$('#main').css({'cursor':'auto'});
$('#reload').hide();
$('#pane').css({'border-left-width':'10px'});
$('#'+subpage+'h').animate({'width':'150px','top':subtop,'left':subleft,'font-size':'200%'},'2000',function(){
$('#'+subpage+'h').css({'display':'none'})});
$('#nav').animate({'left':'415px'},'3000','swing', function(){
$('.subpage').each(function(index) {
$('#'+$(this).attr('id')).fadeIn('3000');
$('#'+$(this).attr('id')+'select').fadeIn('3000');
});});
navsubpage = false;
}
});
the reload function loads the html and is working correctly.
I am really new to ajax, javascript...etc. If any of you can help me out, that'll be great.
It's confusing that you have both the "?t=" + Math.random() combined with cache: true.
The practice of appending a timestamp to a URL is a common method to prevent caching, but then you explicitly tell it that you want it to cache. You might try removing the cache: true option, as it looks to be totally superfluous and can only cause problems (the likes of which would resemble what you're describing here).
I would reccomend trying out a jQuery ajax shortcut function $.get()
It is farly simple and might cut out a lot of uneccesary options you are setting using the full $.ajax() function
Thanks for the help guys - in the end I just decided to not mess with the queue stuff. I still don't understand why it works, but I just took out the ajax and placed it outside of $('#reload').show().delay(500).queue(function(){, eliminating the delay and queue stuff and making the ajax a separate snippet of code. now it loads correctly.
I want to make a few divs on the same page work similar to iframes. Each will load a URL which contains links. When you click on those links I want an AJAX request to go out and replace the div's html with new html from the page of the clicked link. It will be very similar to surfing a page inside an iframe.
Here is my code to initially load the divs (this code works):
onload:
$.ajax({
url: "http://www.foo.com/videos.php",
cache: false,
success: function(html){
$("#HowToVideos").replaceWith(html);
}
});
$.ajax({
url: "http://www.foo.com/projects.php",
cache: false,
success: function(html){
$("#HowToProjects").replaceWith(html);
}
});
This is a sample of code that I'm not quite sure how to implement but explains the concept. Could I get some help with some selectors(surround in ?'s) and or let me know what is the correct way of doing this? I also want to display a loading icon, which I need to know where the right place to place the function is.
$(".ajaxarea a").click(function(){
var linksURL = this.href; //
var ParentingAjaxArea = $(this).closest(".ajaxarea");;
$.ajax({
url: linksURL,
cache: false,
success: function(html){
$(ParentingAjaxArea).replaceWith(html);
}
});
return false;
});
$(".ajaxarea").ajaxStart(function(){
// show loading icon
});
Assuming you want to listen to click events for all anchor tags inside all elements with class ajaxarea, then your selector works fine:
$(".ajaxarea a").click(function(){ .. });
And this line of code, while not a selector (you're just accessing a property on the DOM element that was clicked), should work fine as well:
var linksUrl = this.href;
As for ParentingAjaxArea, you'll need to use $(this).closest() with a selector to determine which parent you want, but it's hard to give a specific example without knowing your HTML structure. It looks like you want ParentingAjaxArea to be either the element with id #HowToProjects or #HowToVideos, so you could write:
var ParentingAjaxArea = $(this).closest("#HowToProjects, #HowToVideos");
As for the loading dialog, I think this answer explains a good method (using ajaxStart and ajaxStop).
Edit: I also noticed you're using the click event--If you plan on being able to attach event handlers to links that will be inserted into the DOM via AJAX later, look at delegate or live.
$(".ajaxarea a").live('click',function(e){
e.preventDefault(); //*
var URL = $(this).attr('href');
var parentFrame = $(this).parent(".ajaxarea"); //**
$.ajax({
url: URL,
cache: false,
success: function(html){
parentFrame.replaceWith(html); //***
}
});
});
* - added preventDefault to prevent click action (see e in function's arguments)
** - instead of closest, i used parent – like it more for it's descriptive qualities
*** - the var containing parent AJAX frame should be jQuery object, no need to wrap it in $(..)
This should work fine, but beware, it's untested.
edit:
You probably need a live (okay, I'm sure you need it). what click() does it's that it adds to all elements at the time in DOM an onClick event. What live() does, it's that it waits for any change in DOM and runs used selector (.ajaxarea a) again and if it fits for any of new elements, it adds the action. In pseudocode, it does basically this:
DOM.hasChanged{
$('selector').click(..)
}
I used this example for my own web page:
http://www.queness.com/post/328/a-simple-ajax-driven-website-with-jqueryphp
It works quite well and uses hash tags and jQuery.history.js for the history of your browser. It works very nice, because you can let something like a media player just continue playing. Take a look at my own site elsewise, where you can find the javascript file: ajaxpages.js. I haven't used live(), but maybe I should.
Figured it out! The problem was I was using the function ".replacewith()" which was removing my AJAXed div(class="ajaxarea") entirely instead of replacing the content. The proper function to use here was ".html()".
Here is my working code to make an AJAXed div work like an iframe:
//onload to initialize the div
$.ajax({
url: "http://www.foo.com/projects.php",
cache: false,
success: function(html){
$('#HowToProjects').html(html);
}
});
$(".ajaxarea a").live('click',function(e){ // must use live instead of .click()
e.preventDefault();
var URL = $(this).attr('href');
var parentFrame = $(this).closest(".ajaxarea");
$.ajax({
url: URL,
cache: false,
success: function(html){
parentFrame.html(html);
}
});
});