I'm new with Jquery and payed someone to developed a script for me. I notice when I add this script to my website my bandwidth jumps from 1mb's to 5mb's. I have a lot of users on so it leaves me to believe the Jquery part is refreshing to quickly. My question is what do I need to change so it will stop using so much bandwidth in the script below.
Thank you!
<script>
current_time = 1342987067;
start_at = 1342986987;
waiting_time = 120;
break_time = 9999;
view_1 = 'Text removed for example<br>';
view_2 = 'Text removed for example<b><span id="countdown-value"></span></b> seconds.<br>';
view_3 = 'Text removed for example... currently in progress...<br>';
winner = "Text removed for example";
function changeView() {
if (start_at + waiting_time > current_time) {
if (break_time < waiting_time) {
return view_1 + "\n" + winner;
} else {
return view_2 + "\n" + winner;
}
} else {
return view_3 + "\n" + winner;
}
}
function setView() {
$("#countdown-holder")[0].innerHTML = changeView();
}
function reload() {
current_time ++;
break_time = start_at + waiting_time - current_time;
setView();
if (break_time <= waiting_time) {
if ($("#countdown-value")[0] != null)
$("#countdown-value")[0].innerHTML = break_time;
} else {
if ($("#countdown-value")[0] != null)
$("#countdown-value")[0].innerHTML = break_time - waiting_time;
}
setTimeout("reload()", 1000);
}
setTimeout("reload()", 1000);
setView();
</script>
<script>
function setBreakTimeCountdown() {
breakTimeCountdown = parseInt($("#countdown-value")[0].innerHTML);
breakTimeCountdown --;
if (breakTimeCountdown < 0) {
breakTimeCountdown = 0;
reload();
}
$("#countdown-value")[0].innerHTML = breakTimeCountdown;
setTimeout("setBreakTimeCountdown()", 1000);
}
setTimeout("setBreakTimeCountdown()", 1000);
</script>
None of the calls in that piece of javascript appear to be triggering any requests directly.
However, if any of the variables view_1, view_2, view_3, and winner were to contain HTML that has references to other media resources in them, that could trigger more requests to your server, which would increase bandwidth utilization.
Nothing in the script seems to be calling back to your site, so I'm guessing it's loading jQuery itself that's the issue?
Easiest solution would be to use the Google Libraries API. Scroll down and get the jQuery link, and replace your local jQuery with that. It will use Google's bandwidth instead.
Related
Little problem about sending PHP array to javascript function, i did homework looked everywhere and i know its not reliable to do this, but at this moment i do not know any other way , so try to just advice me how to finish it anyway.
I got php code executing first , idea is on page load i get some data from MySQL , i filled php array with IDs from that select statement.
<?php
include('config.php');
$TicketExist = "select BetSlipID,probatip1.betslips.MatchID as GameID,
TipID,tim1.Name AS HomeTeam ,tim2.Name AS AwayTeam, UserID
from probatip1.betslips
inner join probatip1.matches matches on probatip1.betslips.MatchID = matches.MatchID
inner join probatip1.teams tim1 on matches.HomeTeamID = tim1.TeamID
inner join probatip1.teams tim2 on matches.AwayTeamID = tim2.TeamID
where UserID = 1";
$TicketResult = mysql_query($TicketExist);
$TicketNum = mysql_numrows($TicketResult);
mysql_close();
if($TicketNum != 0)
{
$s=0;
while($s < $TicketNum)
{
$GameID = mysql_result($TicketResult,$s,"GameID");
$TipID = mysql_result($TicketResult,$s,"TipID");
$ArrayIDs[$s] = $GameID;
echo "<script>window.onload=GetInfo($GameID,$TipID); </script>";
$s++;
}
}
?>
So i got it everything i want filled and wrote on my page , idea now is on user click , to call javascript to take this '$ArrayIDs' and execute code from script
Here is code im calling script
<ul>
<li
id="ConfirmButton" name="Insert" method="post"
onclick="GetAllIDs(<?php $ArrayIDs ?>)"><a>POTVRDI</a></li>
</ul>
And my script code
function GetAllIDs(Ticket) {
$("td.ID").each(function () {
var MatchID = $(this).attr('id');
var lab = "Label";
var Label = lab + MatchID;
var Final = document.getElementById(Label);
var TipID;
if (Final.innerHTML == '1') {
TipID = 1;
}
else if (Final.innerHTML == 'X') {
TipID = 2;
}
else if (Final.innerHTML == '2') {
TipID = 3;
}
else {
return;
}
var request_type;
var browser = navigator.appName;
if (browser == "Microsoft Internet Explorer") {
request_type = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
request_type = new XMLHttpRequest();
}
var http = request_type;
var AlreadyPlayed = false;
if (Ticket != null) {
var TicketExists = Ticket;
for (var i = 0; i < TicketExists.length; i++) {
if (TicketExists[i] == MatchID) {
AlreadyPlayed = true;
break;
}
}
}
if (http != null) {
if (AlreadyPlayed == true) {
http.open('get', 'update.php?MatchID=' + MatchID +
'&TipID=' + TipID + '&UserID=' + 1, true);
}
else {
http.open('get', 'insert.php?MatchID=' + MatchID +
'&TipID=' + TipID + '&UserID=' + 1, true);
}
http.send(null);
}
});
if (Ticket == null) {
alert('Tiket je napravljen');
}
else {
alert('Tiket je promenjen');
}
}
With this posted code when i am debugging code with firebug in mozzila i get that my 'Ticket' parameter that suppose to be '$ArrayIDs' is undefined.
Reason why i want to make array and send it to javascript onclick event is to check if user already placed a bet on some game , if he did i want to send all data for update and if he did not yet placed bet on some game to send data for insert in database.
So i need array and before anything just to check MatchID with all IDs in my array, so i know what to do.
Thanks all in advance for helping out
Your script could do with a bit of cleanup, but in essence you need to change
onclick="GetAllIDs(<?php $ArrayIDs ?>)">
to
onclick="GetAllIDs(<?php echo json_encode($ArrayIDs) ?>)">
I'd also reccomend not outputting
"<script>window.onload=GetInfo($GameID,$TipID); </script>";
for each row in mysql, instead create a single array of the values and create one script after the loop. Using mysql_fetch_row instead of mysql_numrows and mysql_result is probably neater.
while ($row = mysql_fetch_row($result)) {
//...do things here...
}
You need to output the array as valid JavaScript, use json_encode
GetAllIDs(<?php echo json_encode($ArrayIDs); ?>)
I am fairly new to Javascript and what I am trying to do is have a cookie set as soon as I click on a link. When I return back to the previous page from the link, I want the page to auto refresh and notify the user by color to show what link they just clicked. I used this example to guide me http://webdesign.about.com/od/cookies/a/aa083198.htm. But I am still not getting it.
The code below is what I have. The problem is that as soon as I click on the link firebug brings up the error "getLink not defined". Also through web developer on Firefox, it seems that my cookie is not actually being set even though I am calling it from the Html.I am also showing gave the most important part in my Html that calls the function.
The videoId i have in setCookie is a php variable that is defined somewhere else in my code. I would really appreciate it if someone can point me in the right direction. Thanks!
<head>
<script language="text/javascript">
var cookie_name = "watched";
function setCookie(cookie_name,cookie_value)
{
if (document.cookie!="") {
index = document.cookie.indexOf(cookie_name);
} else {
index = -1;
}
if (index == -1) {
var finish = 7200;
var cookie_value = videoId + "; expires=" + finish;
document.cookie=cookie_name + "=" + cookie_value;
}
}
function getLink(cookie_value) {
if (document.cookie) {
index = document.cookie.indexOf(cookie_value);
if (index != -1) {
colorLinks;
}
else{
//alert("No color");
}
}
return colorLinks;
}
function colorLinks()
{
$('#' + videoId).css('background-color: pink');
}
</script>
</head>
<body onLoad=window.refresh>
<div id="page">
echo '<a href="' . $link . '" onclick="setCookie(); return true;">' . $this->Links
This does not make sense:
function getLink(cookie_value) {
if (document.cookie) {
index = document.cookie.indexOf(cookie_value);
if (index != -1) {
colorLinks; // you mean colorLinks(); ???
}
else {
//alert("No color");
}
}
// why return a function that sets color instead of just calling it?
return colorLinks;
}
and there is luckily nothing called window.refresh (unless you have created it yourself) or you would loop forever
In the code i don't see where videoId is given a value
You don't call the function setCookie(cookie_name,cookie_value); to set the cookie.
Please read about cookies: http://www.quirksmode.org/js/cookies.html
<script type = "text/javascript">
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
</script>
So i'm working on a javascript/php chatbox. Everything works except for it updating the contents of my div (this works once, but after that it doesn't keep updating it when a new message has been put into the database). Here is my code:
Javascript part:
<script language=javascript type='text/javascript'>
setInterval(function () {
var arrayOfObjects = <?print_r(getChatArray());?>;
var chat = "";
for (var i = 0; i < arrayOfObjects.length; i++) {
var object = arrayOfObjects[i];
chat += "["+object.date+"]"+object.op+": " + object.msg + "</br>";
}
$('#chat').html(chat);
}, 10);
</script>
Php part:
<?php
function getChatArray() {
$result = mysql_query("SELECT * FROM shouts ORDER BY id DESC");
$to_encode = array();
$count = mysql_num_rows($result);
$size = 0;
if($count > 0) {
while($row = mysql_fetch_assoc($result)) {
$to_encode[$size]['id'] = $row['id'];
$to_encode[$size]['msg'] = $row['msg'];
$to_encode[$size]['op'] = $row['op'];
$to_encode[$size]['date'] = $row['date'];
$size += 1;
}
} else {
return "None";
}
return json_encode($to_encode);
}
?>
Any ideas as to why it isn't continually updating it?
Thanks.
Because every 10 milliseconds your JS is parsing the original chat room contents, you're not fetching any new contents. You'll need to implement an ajax call, and I'd highly recommend changing that setInterval to a recursive setTimeout with a more realistic delay of say 500ms so you don't kill the client.
Instead of this:
setInterval(function() {
var arrayOfObjects = <?print_r(getChatArray());?>;
...
You would use something like this:
(function updateChat(){
var arrayOfObjects,
chat,
max,
_object,
i = 0;
$.ajax({
url : '/getChatArray.php', // php echoes the json
success: function(arrayOfObjects){
for (max = arrayOfObjects.length; i < max; i++) {
_object = arrayOfObjects[i];
chat += "["+_object.date+"]"+_object.op+": " + _object.msg + "</br>";
}
$('#chat').html(chat);
setTimeout(updateChat, 500);
}
});
}());
Obviously you would populate that ajax handler to your needs, add some more params like dataType, etc, and some error handling.
Your database contents will only be output to the page on initial navigation to it.
This code:
var arrayOfObjects = <?print_r(getChatArray());?>;
Will only output the contents of getChatArray()'s return when PHP renders the page. So the script can only see one state of that functions return at the time of rendering.
You need to use AJAX to retrieve the content from your database asynchronously.
I suggest you:
Create a PHP script which outputs your data in JSON format
Use jQuery, specifically the getJSON function to retrieve that script's output
Do what you want to do with that data.
After an earlier question relating to this error.
Error: unable to get value of the property ‘split’: object is null or undefined
An answer was offered to add the following code:
/* Cross-Browser Split 1.0.1
(c) Steven Levithan <stevenlevithan.com>; MIT License
An ECMA-compliant, uniform cross-browser split method */
var cbSplit;
// avoid running twice, which would break `cbSplit._nativeSplit`'s reference to the native `split`
if (!cbSplit) {
cbSplit = function (str, separator, limit) {
// if `separator` is not a regex, use the native `split`
if (Object.prototype.toString.call(separator) !== "[object RegExp]") {
return cbSplit._nativeSplit.call(str, separator, limit);
}
var output = [],
lastLastIndex = 0,
flags = (separator.ignoreCase ? "i" : "") +
(separator.multiline ? "m" : "") +
(separator.sticky ? "y" : ""),
separator = RegExp(separator.source, flags + "g"), // make `global` and avoid `lastIndex` issues by working with a copy
separator2, match, lastIndex, lastLength;
str = str + ""; // type conversion
if (!cbSplit._compliantExecNpcg) {
separator2 = RegExp("^" + separator.source + "$(?!\\s)", flags); // doesn't need /g or /y, but they don't hurt
}
/* behavior for `limit`: if it's...
- `undefined`: no limit.
- `NaN` or zero: return an empty array.
- a positive number: use `Math.floor(limit)`.
- a negative number: no limit.
- other: type-convert, then use the above rules. */
if (limit === undefined || +limit < 0) {
limit = Infinity;
} else {
limit = Math.floor(+limit);
if (!limit) {
return [];
}
}
while (match = separator.exec(str)) {
lastIndex = match.index + match[0].length; // `separator.lastIndex` is not reliable cross-browser
if (lastIndex > lastLastIndex) {
output.push(str.slice(lastLastIndex, match.index));
// fix browsers whose `exec` methods don't consistently return `undefined` for nonparticipating capturing groups
if (!cbSplit._compliantExecNpcg && match.length > 1) {
match[0].replace(separator2, function () {
for (var i = 1; i < arguments.length - 2; i++) {
if (arguments[i] === undefined) {
match[i] = undefined;
}
}
});
}
if (match.length > 1 && match.index < str.length) {
Array.prototype.push.apply(output, match.slice(1));
}
lastLength = match[0].length;
lastLastIndex = lastIndex;
if (output.length >= limit) {
break;
}
}
if (separator.lastIndex === match.index) {
separator.lastIndex++; // avoid an infinite loop
}
}
if (lastLastIndex === str.length) {
if (lastLength || !separator.test("")) {
output.push("");
}
} else {
output.push(str.slice(lastLastIndex));
}
return output.length > limit ? output.slice(0, limit) : output;
};
cbSplit._compliantExecNpcg = /()??/.exec("")[1] === undefined; // NPCG: nonparticipating capturing group
cbSplit._nativeSplit = String.prototype.split;
} // end `if (!cbSplit)`
// for convenience...
String.prototype.split = function (separator, limit) {
return cbSplit(this, separator, limit);
};
After trialling the code above and deleting caches it was found to do nothing...can anyone help at all, kind regards in advance.
Thanks EdoDodo for the above code but can you offer any further help as I am almost tearing my hair out and it did not work in the end, one point to note, the linked in button on the home page (if commented out) makes that site work for the home page and the error goes away but I really want the linked in buttons for each post excerpt on the home page.
site is:
www.mobileinquirer.com
Firefox shows me a script error on line 913 in this part of your script:
<script type="text/javascript">
// <![CDATA[
var disqus_shortname = 'mobileinquirer';
var disqus_domain = 'disqus.com';
(function () {
var nodes = document.getElementsByTagName('span');
for (var i = 0, url; i < nodes.length; i++) {
if (nodes[i].className.indexOf('dsq-postid') != -1) {
nodes[i].parentNode.setAttribute('data-disqus-identifier', nodes[i].getAttribute('rel'));
url = nodes[i].parentNode.href.split('#', 1);
if (url.length == 1) url = url[0];
else url = url[1]
nodes[i].parentNode.href = url + '#disqus_thread';
}
}
var s = document.createElement('script'); s.async = true;
s.type = 'text/javascript';
s.src = 'http://' + disqus_domain + '/forums/' + disqus_shortname + '/count.js';
(document.getElementsByTagName('HEAD')[0] || document.getElementsByTagName('BODY')[0]).appendChild(s);
}());
//]]>
</script>
The specific error is on this line:
url = nodes[i].parentNode.href.split('#', 1);
and it's because parentNode does not have an href. This error has nothing to do with the split function. The code is trying to obtain the value of the href attribute on the parentNode, but there is no href attribute so that resolves to undefined so the call to split fails. It has nothing to do with the split function. The issue is that your markup is apparently wrong and what I think is disqus code is expecting an tag around a tag, but it isn't finding that.
If you look at line 664-665 in the mobilinquirer.com HTML source, you will find this sequence at that line and then several times following:
<p><span
class="dsq-postid">8 Comments</span></p>
This code causes the error. The <span class="dsq-postid"> tag must have an <a href="xxx"> tag as it's parent or you will get this error. I see this same problem several problems in your HTML.
This problem has NOTHING to do with the split function. To make this error go away, you need to fix your HTML so that it is what the disqus code is expecting or remove the offending disqus code (which you don't seem to need) or both.
I need to make a countdown timer that displays a specific number of minutes and seconds counting down - not a countdown to a certain date.
And depending on a variable, change these numbers.
So for $video == 1, I need to display on the page: 8 minutes & 54 seconds (counting down)
And for $video == 2, I need to display on the page: 5 minutes & 01 seconds (counting down)
I also need the countdown display to disappear after the time has elapsed, but maybe I should put that into a different question.
The problem I'm having is the all the countdown scripts I can find deal with counting down to a specific date.
Everything you need, just enter the total time in seconds in the <span> tags. 30 and 120 here for demo. Should work if you copy and paste directly into a webpage. Add and edit code as needed.
<span id="countdown-1">30 seconds</span>
<span id="countdown-2">120 seconds</span>
<script type="text/javascript">
// Initialize clock countdowns by using the total seconds in the elements tag
secs = parseInt(document.getElementById('countdown-1').innerHTML,10);
setTimeout("countdown('countdown-1',"+secs+")", 1000);
secs = parseInt(document.getElementById('countdown-2').innerHTML,10);
setTimeout("countdown('countdown-2',"+secs+")", 1000);
/**
* Countdown function
* Clock count downs to 0:00 then hides the element holding the clock
* #param id Element ID of clock placeholder
* #param timer Total seconds to display clock
*/
function countdown(id, timer){
timer--;
minRemain = Math.floor(timer / 60);
secsRemain = new String(timer - (minRemain * 60));
// Pad the string with leading 0 if less than 2 chars long
if (secsRemain.length < 2) {
secsRemain = '0' + secsRemain;
}
// String format the remaining time
clock = minRemain + ":" + secsRemain;
document.getElementById(id).innerHTML = clock;
if ( timer > 0 ) {
// Time still remains, call this function again in 1 sec
setTimeout("countdown('" + id + "'," + timer + ")", 1000);
} else {
// Time is out! Hide the countdown
document.getElementById(id).style.display = 'none';
}
}
</script>
Try:
var x, secs = 600; //declared globally
x = setInterval(myFunc, 1000);
function myFunc()
{
document.getElementById('timer').innerHTML = secs; //assuming there is a label with id 'timer'
secs --;
if(secs == 0)
{
document.getElementById('timer').style.hidden = true;
clearInterval(x);
}
}
There is a countdown script located at http://javascript.internet.com/time-date/countdown-timer.html that doesn't countdown to a date but rather a specified amount of minutes.
The code may be customized as follows to get the desired effect
<?php
if ($video===1){
$time="8:54";
}
if ($video===2){
$time="5:01";
}
?>
<script type="text/javascript" src="countDown.js"></script>
<form name="cd">
<input id="txt" readonly="true" type="text" value="<?php echo $time; ?>" border="0" name="disp">
</form>
Make sure that the contents of countDown.js looks like this:
/* This script and many more are available free online at
The JavaScript Source :: http://javascript.internet.com
Created by: Neill Broderick :: http://www.bespoke-software-solutions.co.uk/downloads/downjs.php */
var mins
var secs;
function cd() {
mins = 1 * m("10"); // change minutes here
secs = 0 + s(":01"); // change seconds here (always add an additional second to your total)
redo();
}
function m(obj) {
for(var i = 0; i < obj.length; i++) {
if(obj.substring(i, i + 1) == ":")
break;
}
return(obj.substring(0, i));
}
function s(obj) {
for(var i = 0; i < obj.length; i++) {
if(obj.substring(i, i + 1) == ":")
break;
}
return(obj.substring(i + 1, obj.length));
}
function dis(mins,secs) {
var disp;
if(mins <= 9) {
disp = " 0";
} else {
disp = " ";
}
disp += mins + ":";
if(secs <= 9) {
disp += "0" + secs;
} else {
disp += secs;
}
return(disp);
}
function redo() {
secs--;
if(secs == -1) {
secs = 59;
mins--;
}
document.cd.disp.value = dis(mins,secs); // setup additional displays here.
if((mins == 0) && (secs == 0)) {
window.alert("Time is up. Press OK to continue."); // change timeout message as required
// window.location = "yourpage.htm" // redirects to specified page once timer ends and ok button is pressed
} else {
cd = setTimeout("redo()",1000);
}
}
function init() {
cd();
}
window.onload = init;
<?php
$countDownTime = 0;
if ($video == 1) $countDownTime = (8*60 + 54);
else if ($video == 2) $countDownTime = (5*60 + 1);
echo '<script>var countdownTime="' . $countDownTime . '";</script>"';
?>
<script>
<!-- as per the hyper linked reference below -->
$(selector).countdown({until: countdownTime});
</script>
Using the following library, you can implement a JQuery timer using the var countdownTime you specify above...
http://keith-wood.name/countdown.html <-- tutorial on the first page!
Edit Replaced $someTimeInSeconds with $countDownTime
Ok, I'm looking at doing something similar. Currently I have a simple countdown timer that is based off of current time that counts down every 30min. The problem is that I have to use a meta refresh to update it. I'm wondering if a combination of javascript and PHP might be a simpler solution to this answer. Use javascript to call the php code and automatically update it? Maybe set a variable for the time in the php script to be called with javascript? Well, here's the code I have that might help. I'm still learning.
$minutes_left = ($minutes)?((30 - $minutes)-(($seconds)?1:0)):0;
$minutes_left = str_pad ($minutes_left , 2, '0', STR_PAD_LEFT);
$seconds_left = ($seconds)?(60 - $seconds):0;
$seconds_left = str_pad ($seconds_left , 2, '0', STR_PAD_LEFT);
echo '<center><h1 style="font-color:white;">Next station break in: '.$minutes_left.'m '.$seconds_left.'s</h2></center>';
?>
I just have to figure out how to get it to reset itself at the end of every 30min and to update without meta refresh.