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($){
Related
I really want to know if there is a shorter alternative to writing this code. I have attempted to shorten it to 2 or 1 functions and achieved miserable failure. I'm seeking constructive feedback!
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
function f_solar_1() {
$.get("f_solar_1.php");
return false;
}
</script>
<script type="text/javascript">
function refresh(){
location.reload(true);}
</script>
<script type="text/javascript">
function both(){
f_solar_1()
setTimeout(refresh, 5);
}
</script>
Activate
Details:
This code is an excerpt from my php page that displays a table from my mysql database (I'm using wamp).
The "Activate" text at the bottom is supposed to UPDATE a variable on that table, and does so via the f_solar_1.php file.
The issue is the table reflecting the database does not automatically reflect this change.
So I made a "reload()" function to refresh the page, and the "both()" function to time the refresh after updating the database.
I have known basic html for a while, but I am new to mysql, ajax, and php as of this morning, and this is my attempt to dive into it.
My code works fine, it just bothers me not knowing if I can accomplish the same thing within one function.
Thank you in advance!
UPDATE: Thankyou to Dat Pham for pointing me in the right direction!
<script type="text/javascript">
function newfunc(){
$.get( "f_solar_1.php", function( data ) {
location.reload(true);
});}
</script>
<span onclick="newfunc();">newfunc</span>
The code is all in one function (well...) and without causing a refresh and php recall timing conflict.
Making 1 function do all the thing is considered bad practice, a function should do and only do an atomic task. Your code is fine except some minor points:
ajax call $.get() and location.reload should not be used with each other as this destroy the meaning of ajax call. You can pass a callback function to handle data from backend server like
$.get( "f_solar_1.php", function( data ) {
alert( "Load was performed." );
});
Combine all your script tags into 1 with all your function declare
Regards,
Have you checked the database through the backend (phpmyadmin for example) and verified if the changes are being made even though it's not displaying?
i'm wondering if your page isn't really refreshing, and simply going to "#". Check the "return false" - it's not really applying to the "A" link, you would have to put "return false" in the 'both' function for that to cancel the link. But you might not want to do it that way after taking a minute to read this: The return false onclick anchor not completely working
additionally, I'd recommend using the jquery add event listener to trigger your function calls, and get the onClick out of your html tag. Bonus if you learn how to do it without jquery. Read this real quick jquery href and onclick separation
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.
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 am using a jQuery ticker which is pretty cool. It works well with predefined content, but I want to build my tags dynamically by getting the data from a feed via the $.ajax method.
http://progadv.uuuq.com/jStockTicker/
The problem is when I do this the ticker wont work, as it looks like the function might be loading before my page content has loaded. Can anbody think of a way around this?
$(function() {
$("#ticker").jStockTicker({interval: 45});
});
$(document).ready(function() {
$("#ticker").jStockTicker({interval: 45});
});
You need to call the jStockTicker function from within the success method with the Ajax call, because like you say, jStockTicker is calculating the dimensions for scrolling before the content has been added to the page.
$.ajax({
url: 'ajax/test.html',
success: function(data) {
//Populate $('#ticker') with data here, e.g...
$('#ticker').html(data);
//Now call jStockTicker
$("#ticker").jStockTicker({interval: 45});
}
});
Something like that ought to do it.
Rich
I have never used the jStockTicker; however with another plugin you can change the data dynamically. For example for the jQuery webTicker you can simply replace the content with the list items using javascript and the rotation will continue without halt. I have used this method on a financial website and works like a charm updating the data every few seconds to show the latest exchange rates. The scrolling and dimensions id done automatically per item; once it moves out of screen it is popped back in at the end of of the list. So the list should not break at any point in time
$("#ticker").jStockTicker({interval: 45});
from calling the jStockticker inside success method the scrolling stops and restarts from the begining.
I have a page that has multiple links with various attributes (these attributes will be pulled in from a database):
index.php
<html>
<head>
<script type='text/javascript' src='header.js'></script>
</head>
<body>
My_Link_1
My_Link_2
<div id='my_container'> </div>
</body>
</html>
My header.js file has:
$(document).ready(function(){
$('.link_click').click(function(){
$("#my_container").load("classes/class.project.php", {proj: $(this).attr('id')} );
return false;
});
});
class.project.php is pretty simple:
<?php
echo "<div id='project_container'>project = ".$_POST['proj']." : end project</div>";
?>
This loads and passes the ID variable (which actually comes from a database) to class.project.php. It works fine for the first link click (either link will work). Once one link is clicked no other links with this div class will work. It feels like javascript loads the class.porject.php and it will not refresh it into that #my_container div.
I tried running this as suggested by peterpeiguo on the JQuery Fourm, with the alert box for testing wrapped inside .each:
Copy code
$(document).ready(function() {
$('.link_click').each(function() {
$(this).click(function() {
alert($(this).html());
});
});
});
This seems to work fine for the alert box. But when applying it to .load() it does not reload the page with the new passed variable. As a matter of fact, it doesn't even reload the current page. The link performs no function at that point.
The example site can be viewed here: http://nobletech.net/gl/
I looked at the link you posted, and the problem is that when you're doing load you're replacing the elements on the page with new ones, thus the event handlers don't work anymore.
What you really want to do is target the load. Something like:
$("#project_container").load("classes/class.project.php #project_container", {proj: $(this).attr('projid')} );
This only loads stuff into the proper container, leaving the links and other stuff intact.
Ideally, the php script should only return the stuff you need, not the whole page's markup.
BTW- Caching shouldn't be an issue in this case, since .load uses POST if parameters are passed. You only have to worry about ajax caching with GETs
Sounds like the request is getting cached to me.
Try this:
$.ajaxSetup ({
// Disable caching of AJAX responses */
cache: false
});
Sorry but this might be completely wrong but after examining your XHR response I saw that you are sending back html that replaces your existing elements.
So a quick fix would be to also send the following in your XHR response (your php script should output this also):
<script>
$('.link_click').each(function() {
$(this).click(function() {
alert($(this).html());
});
</script>