Ajax fires only once,and the javascript file is loaded only once - javascript

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.

Related

How to use information from an API request to interact with a website?

I'm quite familiar with html and css but absolutely not with Javascript and I probably need Javascript to achieve what I want:
Each friday I'm livestreaming at Hitbox.tv. I've embedded the video player on my website. I would like to display an image stored on my server in front of the video player when I'm offline. I always edit the html page manually to show or hide the image, but it would be nice if it works automatically.
At https://api.hitbox.tv/media/status/masta (masta=channelname) I get a response with information of the live-status of my channel at Hitbox.tv. I believe the type of response is called JSON, but how can I use the value of "media_is_live" to show or hide the image on my server?
I searched for a long time on all kind of forums but didn't find an answer that worked out for me. Any help appreciated!
A good thing you can use is something called AJAX. AJAX is a piece of web technology that makes a request to a resource after your page has loaded. In order to do this kind of thing, I use the JQuery AJAX function.
In a script tag, you can do something like this:
<script>
$(document).ready(function() {
$.ajax({
dataType: "jsonp",
url: "https://api.hitbox.tv/media/status/masta",
success: function(data){
var img = $('myImageId');
if(data.media_is_live){
img.style.visibility = 'visible';
} else {
img.style.visibility = 'hidden';
}
});
});
</script>
The $(document).ready(function() { part means that the code inside will execute once the page has loaded.
This answer could be improved with some more information. I am, of course, guessing what the json object you get looks like. If you can post that, I can help more. Remember to import JQuery before the script above.

jQuery stops working after ajax loading

some info
I'm working on a webpage that can load data on multiple layouts, so user can choose which one is best. It can be loaded in a list or a cards like interface, and the data is loaded using ajax.
In this page I also have a notifier for new messages that the user received. The ajax function is new, and when page was loaded by the php scripts, the js script (that add a badge with the number of unread messages to a link on a menu item) was working ok.
I'm using HTML5, PHP, jQuery and a mySQL DB.
jQuery is imported onto the HTML using
<script src="https://code.jquery.com/jquery.js"> </script>
So it's a recent version.
the problem
Now, when I load the data onto the page using ajax, the js script won't work anymore. I had the same issue with another js script and I managed to solve it by using the delegate event binder.
But my unread messages updater runs on a time interval, using
<body onload="setInterval('unread()', 1000)">
the unread() js is quite simple:
function unread() {
$(document).ready(function(){
$('#menu_item').load('ajax_countNewMsgs.php');
});
}
it calls a php script which grabs the unread msgs count from the DB and echo into a element that jQuery will point. Hope I'm being clear.
The problem is that I cannot figure out how I would call a timed event using delegate. Without much hope I've tried
$(document).on('ready()','#menu_item', function () {
$(this).load('ajax_countNewMsgs.php');
});
That didn't work.
I read many posts about js stop working after changes in the DOM, but, again, I couldn't figure out a way to solve that, nor found a similar question.
Any help or tips would be highly appreciated.
EDITED to change second php script's name
2nd EDIT - trying to make things clearer
I tried the way #carter suggested
$(document).ready(function(){
function unread(){
$.ajax({
url: 'ajax_countNewMsgs.php',
type: 'GET',
dataType: 'html',
success: function(response){
$('#menu_item').html(response);
},
error: function(response){
//no error handling at this time
}
});
}
setInterval(unread(), 1000);
});
the ajax_countNewMsgs.php script connects to the DB, fetch the unread messages, and echoes the number of unread messages.
If I try to apply the ajax reponse to another element, say, the <body> the results are as expected: at each 1 sec , the body html is changed. So the function is working.
As I said, none of my JS changes the #menu_item. Actuallly this element is part of another php scritp (menu.php) which is imported to the top of the page.
the page structure is this way:
<html>
<head>
some tags here
</head>
<body>
<?php include (php/menu.html); ?>this will include menu with the #menu_item element here
<div id='wrapper'>
<div id='data'>
here goes the data displayed in two ways (card and list like). Itens outside div wrapper are not being changed.
</div>
</div>
</body>
</html>
Even though the elemente is not being rewritten js cannot find it to update it's value.
It's not the full code, but I think you can see what is being done.
$(document).on('ready()','#menu_item', function () {
is an invalid event listener. If you wanted to be made aware of when the DOM is ready you should do this:
$(document).ready(function () {
However I don't think that is actually what you want. Your function unread will fire repeatedly but it attaches an event listener everytime. Instead if you want to make an ajax call every so many seconds after initial page load, you should do something like this (dataType property could be html, json, etc. pick your poison):
$(document).ready(function(){
function makeCall(){
$.ajax({
url: 'ajax_countNewMsgs.php',
type: 'GET',
dataType: 'html',
success: function(response){
//handle your response
},
error: function(response){
//handle your error
}
});
}
setInterval(makeCall, 1000);
});
remove that on your unread function:
$(document).ready(function(){
WHY?
The Document is already "ready" and this document state will only fired 1x - After that the "ready state" will never ever called. Use follwing syntax:
jQuery(function($){

Javascript for CActiveForm isnt available after renderPartial

I am loading a form (depending on the selected option of a dropDownList) with an ajaxcall (which triggers a renderPartial)
The ajaxcall looks like:
$("#dropDownList").change(function() {
var selected = $(this).val();
$.ajax({
url: "index.php?r=item/update&category="+selected,
cache: false,
success: function(html){
$("#inputs").html(html);
}
})
});
The action "update":
public function actionUpdate($category){
$model = new Item;
$this->renderPartial($category, array(
'model'=>$model,
), false, true);
}
The form will be renderd in the div "input" without any problems, but there is still no javascript available for the form. I have already used
Yii::app()->clientScript->scriptMap['jquery.js'] = false;
to prevent, that jquery will be loaded twice. But there is still no js available for my form (jquery.yiiactiveform.js).
Edit: I have checked my firebug, that jquery.yiiactiveform.js will be loaded after the ajaxcall (again?). - If I am using:
Yii::app()->clientScript->scriptMap['jquery.yiiactiveform.js'] = false;
jquery.yiiactiveform.js isnt available anymore, so it shouldnt be loaded twice?
Your problem is mostly with scripts being reloaded. The jQuery mess everything a lot, but other scripts like YiiActiveForm also can mess up with your application. It will be best if you could preload all needed scripts on the page you call ajax and disable scripts on the pages you load with ajax. You might want to look at EUpdateDialog extension (disclaimer: written by me) it might give you some additional ideas.
The extension #Andrew mentioned is NLSClientScript.

How to refresh a Div every 10 seconds without refreshing the entire page?

I'm working on a website platform that doesn't allow for any server sided scripting, so jquery and javascript are pretty much all I have to work with. I am trying to create a script to work with the site that will update a div that contains an inbox message count every 10 seconds. I've been successful with making the div refresh every ten seconds, but the trouble lies in the page views count. My script is refreshing the whole page and counting for a page view, but I only want to refresh just the one div. An example of the trouble my script causes is when viewing anything on the site that has a page view counter (forum posts, blog posts, ect...), the page views go crazy because of the script refreshing. I'm pretty new to Javascript, so I'm not entirely sure there is a way around this.
What I'm working with is below:
<div id="msgalert" style="display: none"; "width: 100px !important">
You have $inbox_msg_count new messages.
</div>
$inbox_msg_count is a call that grabs the message count, and provided by the platform the site is on. It displays the message count automatically when used.
Then the script that does all the work is this:
<script>
setInterval(function(facepop){
var x= document.getElementById("SUI-WelcomeLine-InboxNum");
var z = x.innerText;
if(x.textContent.length > 0)
$("#msgalert").show('slow');
}, 1000);
facepop();
</script>
<script>
setInterval(function() {
$("#msgalert").load(location.href+" #msgalert>*","");
}, 1000); // seconds to wait, miliseconds
</script>
I realize I've probably not done the best job of explaining this, but that's because I'm pretty confused in it myself. Like I mentioned previously, this code function just how I want it, but I don't want it to refresh the entire page and rack up the page views. Any help is much appreciated.
You might try to look into iframe and use that as a way to update/refresh your content (div). First setup an iframe, and give it an id, then with JS grab the object and call refresh on it.
well your prob seems a little diff so i think submitting a from within the div might help you so ...
$(document).ready(function()
{
// bind 'myForm' and provide a simple callback function
$("#tempForm").ajaxForm({
url:'../member/uploadTempImage',//serverURL
type:'post',
beforeSend:function()
{
alert(" if any operation needed before the ajax call like setting the value or retrieving data from the div ");
},
success:function(e){
alert("this is the response data simply set it inside the div ");
}
});
});
I think this could probably be done without a form, and definitely without iframes (shudder)..
Maybe something like this?
$(document).ready(function()
{
setInterval(function(facepop)
{
var x= document.getElementById("SUI-WelcomeLine-InboxNum");
var z = x.innerText;
if(x.textContent.length > 0)
$("#msgalert").show('slow');
$.ajax({
type: "POST",
url: location.href,
success: function(msg)
{
$("#msgalert").html(msg);
}
});
},1000);
It's not entirely clear exactly what you're trying to do (or it may just be that I'm ultra tired (it is midnight...)), but the $.ajax() call in the above is the main thing I would suggest.
Encapsulating both functions in a single setInterval() makes things easier to read, and will extinguish the 1 second gap between showing the msgalert element, and "re-loading" it.

.click function not working for me

I have lots of jquery functions in my script but a particular one is not working, this is my function
$('#delete').click(function() {
var id = $(this).val();
$.ajax({
type: 'post',
url: 'update.php',
data: 'action=delete&id=' + id ,
success: function(response) {
$('#response').fadeOut('500').empty().fadeIn('500').append(response);
$(this).parent('tr').slideUp('500').empty();
}
});
});
a similar function like this is working
<!-- WORKING FUNCTION -->
$('#UpdateAll').click(function() {
$.ajax({
type: 'post',
url: 'update.php',
data: 'action=updateAll',
success: function(response) {
$('#response').fadeOut('500').empty().fadeIn('500').append(response);
$('#table').slideUp('1000').load('data.php #table', function() {
$(this).hide().appendTo('#divContainer').slideDown('1000');
});
}
});
});
I checked with firebug, the console doesnt show any errors, i checked html source the values are loading correct, i checked my php file 5times it is correct can't figure out the problem. Please Help.
I struggled with the EXACT SAME PROBLEM for 6hr straight! the solution was to use jquery 'live'.
And that is it.
$('#submit').live('click',function(){
...code...
});
With the first one, I'd put a quick and nasty alert() within the click anonymous function, to ensure that it is being fired. Eliminate reasons why it may not be working. Also, try using Live HTTP headers or Firebug's console to see if the AJAX request is being sent.
If the click is not being fired, see if you have the selector correct. I often do this (quite nasty)
var testSelector = 'p:first ul li:last';
$(testSelector).css( { border: '1px solid red' } );
It won't always be visible, but if you see style="border: 1px solid red"` in the generated markup, you know your selector is on the ball.
Perhaps you have another click that is overwriting it? Try using
$('#delete').bind('click', function() {
// do it
});
I just had the same problem with a quick example I was working on. The solution was to put the click inside $(document).ready. I was trying to use my element before it was actually ready to be used.
It's basic JavaScript to wait until the DOM is ready before you try to use an element, but... for whatever reason I forgot to do that, so maybe the same happened to you.
$(document).on('click', '#selector', function(){
// do something
});
jQuery 1.7+ has depreciated .live() and now uses .on() instead :)
I don't know if this applies in your context, but if you have parts of the page that are getting loaded by AJAX then you'll need to bind the click handlers after that content is loaded, meaning a $(document).ready isn't going to work. I've run into this problem a number of times, where certain events will fire fine until parts of the page are reloaded, then all the sudden the events seem to stop firing.
Just use your .click with $(document).ready(function(){ ... }); because you are trying to apply the click event on a non-existent element.
1) just before the last }); you should add return false;
2) Are you sure that #delete exists? Also, are you sure is UNIQUE?
This is a long shot, but it's good to be aware of.
http://code.google.com/p/fbug/issues/detail?id=1948
May not be an issue if you're not on Firefox 3.5.
Instead of id=delete i changed it to class=delete in html and in js ('.delete') and it is working fine now but when again tried with id it doesnt work.
Thank You all for Help, i dont have any problem whether it is id or class just the function works now.
There is few things you can do:
like Elmo Gallen and Shooz Eh suggested, put your code in $(document).ready(function(){...});
code your $('#delete').click(function(){...}); event handling AFTER your <button> tag,
use $('#submit').live('click',function(){...}); like Parikshit Tiwari suggested.
Everyone of these should work ok.
EDIT: oops, didn't see that this was asked '09 :D
I think you must use .on() function for dynamically code run in jQuery like this:
$(document).on("click","#delete",function(){ });

Categories

Resources