How do I run multiple javascripts in one page? [closed] - javascript

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I'm having this problem with my site. I'm trying to get 2 scripts to run on the same page but one will not work unless I delete either:
<script src="js/jquery.op.loc.min.js"></script>
or
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
Here is the javascript code I have inserted into the section of my page:
<script src="js/jquery.op.loc.min.js"></script>
<link type="text/css" rel="stylesheet" href="css/jquery.op.loc.min.css" />
<script>
jQuery(document).ready(function ($) {
$("#default-usage .to-lock").loc({
text: {
header: "How are you today?",
message: "Hello!"
},
theme: "secrets",
buttons: {
order: ["twitter-tweet", "facebook-like", "google-plus"]
},
twitter: {
tweet: {
url: "http://twitter.com",
text: "tweet!"
}
},
facebook: {
like: {
url: "http://facebook.com"
},
appId: "427542137301809"
},
google: {
plus: {
url: "http://google.com"
}
}
});
});
</script>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="<?php if($network == "") {echo '';} elseif($network == "") {echo '';} echo $account_id; ?>"></script>
<script type="text/javascript">
$(document).ready(function(){
$("div.process").fadeOut(0);
$("input.button").click(function() {
$('div.process div.bar').css("width", "0%");
$("div.process").fadeOut(0);
$("span.status span").empty();
$("span.status span").append("On hold");
$("span.status").css("color", "#FF0000");
var urlform = $("input.profile").val();
$.post("<?php echo $filename; ?>?post=1", {url:urlform}, function(data) {
var exploded = data.split('||');
var profileimage = exploded[0];
var profilename = exploded[1];
if(profilename !== "") {
$("img.profileimg").attr("src", profileimage);
$("span.profilename span").empty();
$("span.profilename span").append(profilename);
$("span.status span").empty();
$("span.status span").append("Searching for account");
$("span.status").css("color", "#FFFF00");
$("div.process").fadeIn("2000");
$('div.process div.bar').animate({
width: "200px"
}, 14000, function() {
$("span.status span").empty();
$("span.status span").append("Account found");
$("span.status").css("color", "#33FF00");
setTimeout(function() {startGateway('<?php echo $widget_id; ?>');}, 500);
});
} else {
$("span.status span").empty();
$("span.status span").append("Account not found!");
$("span.status").css("color", "#FF0000");
$("img.profileimg").attr("src", "img/blank.jpg");
}
});
});
});
</script>
I am a complete newbie when it comes to javascript so any help will be much appreciated!

There are a few things you can try to get this working.
Be sure your script is being pulled into the page, one way to check is by using the 'sources' tab in the Chrome Debugger and searching for the file else in the html head section
Be sure that you've included the other scripts after you've included jQuery, as it is most certainly dependant upon that.
Check whether jQuery is included properly and once only.
Watch out for jQuery conflicts. There is some other library which is overridding $, so your code is not working because $ is not an alias for jQuery anymore. You can use jQuery.noConflict() to avoid conflicts with other libraries on the page which use the same variable $.

Related

Problem to Load PHP File In different Divs After Page Load and refresh them Using JQuery

I am having a problem to show different types of graphs in different divs using Javascript and JQuery in a HTML file.
I am using a single PHP file that generates those graphs according to the parameters I pass it through the URL (GET Method). The PHP files imports the data from a PostgreSQL database and creates the graphs using FLOT Library.
After loading the page I want to show the graphs, and after 1 minute, I want to refresh each graph, I am using JQuery to achieve this.
If I use only one div showing only one graph it works just fine, it show the graph and refreshes it.
The problem is when I try to load different graphs in different divs because it only shows the initial graph in the first div only, and then it goes refreshing and showing the other graphs but in the same div # 1.
Can someone give an idea how to solve it? or tell me what is wrong in the code?
This is the code I'm using:
<html>
<head>
<script type="text/javascript" src="js/jquery-3.4.1.js"></script>
<script type="text/javascript">
function update()
{
$('#flot1').load('basic.php?p=1&c1=00b8d8&c2=eff9fb');
$('#flot2').load('basic.php?p=2&c1=8be3b8&c2=f1fbf6');
}
setInterval( "update()", 60000 );
</script>
</head>
<body>
<div id = "flot1"></div>
<div id = "flot2"></div>
<script type="text/javascript">
$(document).ready(function(){
$("#flot1").load('basic.php?p=1&c1=00b8d8&c2=eff9fb');
$("#flot2").load('basic.php?p=2&c1=8be3b8&c2=f1fbf6');
});
</script>
</body>
</html>
This is the code of the PHP file that creates the graphs:
<html>
<head>
<script language="javascript" type="text/javascript" src="flot/jquery.js"></script>
<script language="javascript" type="text/javascript" src="flot/jquery.flot.js"></script>
</head>
<body>
<div id="placeholder" style="width:202px;height:140px;"></div>
<?php
include "opendb.php";
if(!isset($tag)){ $tag=$_GET['p']; }
if(!isset($c1)) { $c1="#".$_GET['c1']; }
if(!isset($c2)) { $c2="#".$_GET['c2']; }
$dataset1 = array();
$query1="SELECT nu_valor, nu_fecha_hora_timestamp FROM x001t_historico_tag WHERE co_tag = '$tag' ORDER BY nu_fecha_hora_timestamp DESC LIMIT 6";
$result1 = pg_query($query1);
while ($row = pg_fetch_array($result1))
{
$unix = $row['nu_fecha_hora_timestamp'];
$nu_valor = $row['nu_valor'];
$dataset1[] = array( $unix, $nu_valor );
}
?>
<script type="text/javascript">
var dataset1 = <?php echo json_encode($dataset1); ?>;
$(function () {
var options = { xaxis: { ticks: [] }, yaxis: { ticks: [], autoscaleMargin: 0.5 }, grid: { backgroundColor: '#fff', color: "#fff" },
};
//plotting
$.plot($("#placeholder"),[
{
color: '<?php echo $c1; ?>', data: dataset1 ,
lines: { show: true, fill: true, fillColor: "<?php echo $c2; ?>", lineWidth: 2},
} ], options);
});
</script>
</body>
</html>
If I run the graph from the browser passing it the parameters through the URL it also works fine and creates the graph.

How to add ajax execution time in boomrang page load time?

I am using boomerang plugin to check web performance.
Following the code that used to get page load time.
<script type="text/javascript" src="http://yui.yahooapis.com/combo?3.1.1/build/yui/yui-base-min.js&3.1.1/build/oop/oop-min.js&3.1.1/build/yui/yui-later-min.js&3.1.1/build/event-custom/event-custom-base-min.js&3.1.1/build/querystring/querystring-stringify-simple-min.js&3.1.1/build/io/io-base-min.js"></script>
<script src="/js/boomerang.js" type="text/javascript"></script>
<script src="/js/plugins/rt.js" type="text/javascript"></script>
<script src="/js/plugins/bw.js" type="text/javascript"></script>
<script src="/js/plugins/navtiming.js" type="text/javascript"></script>
<script type="text/javascript">
BOOMR.init({
BW: {
enabled: false,
cookie: 'HOWTO-BA'
},
RT: {
cookie: 'HOWTO-RT'
}
});
YUI().use("io-base", function(Y) {
var uri = "dynamic-content.txt?" + new Date().getTime();
var timer;
function complete(id, o) {
var html = "<p>\n" + o.responseText.replace(/^$/mg, '</p>\n<p>') + "\n</p>";
document.getElementById("dynamic-content").innerHTML = html;
if(timer) timer.loaded();
};
Y.on('io:complete', complete);
timer = BOOMR.requestStart("my-timer");
var request = Y.io(uri);
});
BOOMR.plugins.RT.setTimer("t_js", new Date().getTime() - t_pagestart).
startTimer("t_head");
</script>
script src="/pgr/js/howtos.js" type="text/javascript"></script>
<script type="text/javascript">
BOOMR.plugins.RT.endTimer("t_howtojs").endTimer("t_body");
</script>
Here YUI that make separate ajax call and adds execrutiont ime in page load time. In my website there are many ajax calls on page load, those execution time I want to add in page load time.
But stuck how to use YIU with existing code.
My ajax call
jQuery(document).ready(function($) {
$.ajax({
type : 'POST',
url : '/getdata/',
data : { sid:retSid},
dataType: 'JSON',
beforeSend: function(){
$('.blocker').show();
},
success : function(result) {
if(result.data)
{
....
}
});
});
You should use one of the SPA plugins to measure single page apps / AJAX apps. It would be better to ask your question on the boomerang support forum. We prefer keeping all discussion and issues in one place so that if a code change is required, we can reference the discussion via a git reference.
You can ask the question here: https://github.com/soasta/boomerang/issues

Javascript function plays correctly old site but not new

I recently moved my companies website to one of our unused web servers in order to update the Joomla backend from 1.5.26 to the latest Joomla 2.5. We couldn't go to 3.x because of modules.I used SP Upgrade, and everything migrated brilliantly once I had my new theme and current modules installed.
We have a customized default theme and an assigned theme to the home page. Within the assigned theme (assigned to the home menu) directory, index.php has a script above the header. I will post this code below.
The old site can be found at the following link and when you first go to the site, you will see the video play.
cpmchurchministries.com/old
The new site can be found at the following link and when you first go to the site, you will see only an image.
cpmchurchministries.com/new
The code is the same for both sites, index.php:
<head>
<jdoc:include type="head" />
<link rel="stylesheet" href="<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/css/template.css" type="text/css"/>
<script type="text/javascript" src="<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/swf/swfobject.js"></script>
<script type="text/javascript">
swfobject.embedSWF("<?php echo $this->baseurl ?>/templates/chosenpeople/swf/cpm_logo.swf", "flash_logo", "245", "162", "7");
window.addEvent('domready', function() {
if($('default_header')) {
if(Cookie.get("cpm_movie") != "full") {
full_movie();
} else {
small_movie();
}
}
});
function small_movie() {
$('default_header').removeClass('full_movie');
$('default_header').addClass('small_movie');
swfobject.embedSWF("<?php echo $this->baseurl ?>/templates/cphome/swf/header_home.swf", "flash_header", "696", "157", "7");
}
function full_movie() {
$('default_header').removeClass('small_movie');
$('default_header').addClass('full_movie');
Cookie.set("cpm_movie", "full", {duration: 365});
swfobject.embedSWF("<?php echo $this->baseurl ?>/templates/cphome/swf/video_header.swf", "flash_header", "696", "400", "7");
}
</script>
<?php if ($editmode) echo '<link rel="stylesheet" href="'.$this->baseurl.'/templates/system/css/general.css" type="text/css" />'."\n"; ?>
Has anyone run into a similar issue? Is it possible to get any help?
Thank you. . .
The newer version of Joomla that you are using uses a newer version of the MooTools library so you need to make the following two function changes to the code:
OLD
window.addEvent('domready', function() {
if($('default_header')) {
if(Cookie.get("cpm_movie") != "full") {
full_movie();
} else {
small_movie();
}
}
});
function small_movie() {
$('default_header').removeClass('full_movie');
$('default_header').addClass('small_movie');
swfobject.embedSWF("/new/templates/cphome/swf/header_home.swf", "flash_header", "696", "157", "7");
}
function full_movie() {
$('default_header').removeClass('small_movie');
$('default_header').addClass('full_movie');
Cookie.set("cpm_movie", "full", {duration: 365});
swfobject.embedSWF("/new/templates/cphome/swf/video_header.swf", "flash_header", "696", "400", "7");
}
NEW
window.addEvent('domready', function() {
if($('default_header')) {
if(Cookie.read("cpm_movie") != "full") {
full_movie();
} else {
small_movie();
}
}
});
function small_movie() {
$('default_header').removeClass('full_movie');
$('default_header').addClass('small_movie');
swfobject.embedSWF("/new/templates/cphome/swf/header_home.swf", "flash_header", "696", "157", "7");
}
function full_movie() {
$('default_header').removeClass('small_movie');
$('default_header').addClass('full_movie');
Cookie.write("cpm_movie", "full", {duration: 365});
swfobject.embedSWF("/new/templates/cphome/swf/video_header.swf", "flash_header", "696", "400", "7");
}
EDIT for easy copy paste
I have this error on your "new site" :
GET http://cdn.wibiya.com/Toolbars/dir_0775/Toolbar_775982/Loader_775982.js 403 (Forbidden)
I can't access the "old site", there is a Joomla login page. It would be easier if we could access it to compare both sites.
As Pointy said, you are getting some errors in the Javascript console:
Uncaught TypeError: Object function
(){e(this);if(g.$prototyping){return this;}this.$caller=null;var
i=(this.initialize)?this.initialize.apply(this,arguments):this;this.$caller=this.caller=null;
return i;} has no method 'get' (index):27
GET
http://cdn.wibiya.com/Toolbars/dir_0775/Toolbar_775982/Loader_775982.js
403 (Forbidden) (index):249
Uncaught ReferenceError: JCaption is not defined (index):17
GET http://cpmchurchministries.com/main/flash/menorah_shine.swf 404
(Not Found)
When there are errors with Javascript, the flow is stopped, so your image on the header is not replaced by the video (is not a "video", it's a flash swf movie).
One of the offending codes are:
<script type="text/javascript">
window.addEvent('load', function() {
new JCaption('img.caption');
});
</script>
If you cannot remove this code, Try this link to get rid of the JCaption problem and try again your site.
By the way, to see the errors on the console, try using a Chrome Browser, Tools, Javascript console (a must for every webdev!)

Javascript not working without an internet connection in IE9

I have published a website on a laptop with IIS 7.5 running IE9. When I have the internet plugged in the website works fine. The weird thing is that it will work fine in firefox weither the machine has internet or not.
Some other information that may be helpful.
Running Windows 7 64Bit. Latest version of firefox. IE9.
Not sure what else you may need. I have tried checking IE permissions but there may be something I have missed so any help will be appreciated.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>#ViewBag.Title</title>
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<meta name="viewport" content="width=device-width" />
#*----------------- JQUERY UI for Accordion Starts here-------------------- *#
<link href="../../Content/themes/Blue/jquery-ui-1.9.1.custom.min.css" rel="stylesheet"
type="text/css" />
<script src="../../Scripts/jquery-1.8.2.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-ui-1.9.1.custom.js" type="text/javascript"></script>
#* -----------JQUERY UI for Accordion Ends here--------------------- *# #*----------------- JQUERY UI for Delete Dialog Starts here-------------------- *#
<script src="../../Scripts/external/jquery.bgiframe-2.1.2.js" type="text/javascript"></script>
#* <script src="http://code.jquery.com/ui/1.9.1/jquery-ui.js"></script>*#
<script src="../../Scripts/external/jquery-ui.js">></script>
#*----------------- JQUERY UI for Delete Dialog Ends here-------------------- *#
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
#*
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
*# #* ----------- Scripts added for Devexpress but commented because JQUERY UI not working --------------------- *#
#*
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery-1.4.4.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")"></script>
*# #* ----------- Scripts added for Devexpress ends here--------------------- *#
#Html.DevExpress().GetScripts(
new Script { ExtensionSuite = ExtensionSuite.GridView },
new Script { ExtensionSuite = ExtensionSuite.PivotGrid },
new Script { ExtensionSuite = ExtensionSuite.HtmlEditor },
new Script { ExtensionSuite = ExtensionSuite.Editors },
new Script { ExtensionSuite = ExtensionSuite.NavigationAndLayout },
new Script { ExtensionSuite = ExtensionSuite.Chart },
new Script { ExtensionSuite = ExtensionSuite.Report }
//new Script { ExtensionSuite = ExtensionSuite.Scheduler }
)
#Html.DevExpress().GetStyleSheets(
new StyleSheet { ExtensionSuite = ExtensionSuite.GridView },
new StyleSheet { ExtensionSuite = ExtensionSuite.PivotGrid },
new StyleSheet { ExtensionSuite = ExtensionSuite.HtmlEditor },
new StyleSheet { ExtensionSuite = ExtensionSuite.Editors },
new StyleSheet { ExtensionSuite = ExtensionSuite.NavigationAndLayout },
new StyleSheet { ExtensionSuite = ExtensionSuite.Chart },
new StyleSheet { ExtensionSuite = ExtensionSuite.Report }
//new StyleSheet { ExtensionSuite = ExtensionSuite.Scheduler }
)
#* ---------------------------------JQUERY Scripts for Delete confirmation Starts here --------------------------------*#
<script type="text/javascript">
// increase the default animation speed to exaggerate the effect
$.fx.speeds._default = 500;
$(function () {
$("#dialog").dialog({
autoOpen: false,
show: "blind",
hide: "explode",
width: 250,
resizable: false,
modal: true,
buttons:
{
"Delete": function () {
$.post(deleteLinkObj[0].href, function (data) { //Post to action
//Check data the return from the middle layer, if it is just true, deletion is successful
if (data == '#Boolean.TrueString') {
deleteLinkObj.closest("tr").hide('fast'); //Hide Row
$("#dialog").dialog("close"); //See it used #dialog instead of (this) because the scope (context) has changed in the "Delete" callback
$(this).empty();
$("#StatusMsg").html("Deleted");
location.reload(); //refreshes the page
}
else {
//Show the errror on the dialog content. Data is used to show the error
//expecting the Error handlers in middle layer will return the meaning ful error message
$("#dialog").html(data);
//Hide confirmation button inorder to show the user to only the content of error in the same
//dialog box and allow to cancel this dialog
$(":button:contains('Delete')").css("display", "none");
$("#StatusMsg").html("Not Deleted");
}
//location.reload();
});
},
"Cancel": function () {
//This reset of the Delete button is need since if it wsas invoked and jumped into show error routine,
// then that routine would have removed the Delete button.
$(":button:contains('Delete')").css("display", "inline");
$(this).dialog("close");
$("#StatusMsg").html("");
}
}
});
var deleteLinkObj;
var deletMsg;
$('a.inputFakeDelete').click(function () {
//Here the message is built using the delete button properties id and name.
//So every page calling this jquery need to have the link button embedded with these properties
//eg: id = Grade, name = the name of the grade from the model
deletMsg = "Are you sure you want to delete this " + this.id;
if (this.name == "") {
}
else {
deletMsg = deletMsg + " '" + this.name + "'" //"Are you sure you want to delete the " + (this).id + " '" + (this).name + "'?";
}
deletMsg = deletMsg + "?"
$("#dialog").html(deletMsg)
deleteLinkObj = $(this); //to use in the dialog javascript
$("#dialog").dialog("open");
return false;
});
});
</script>
#*----------------------------------JQUERY Scripts delete confirmation Ends here --------------------------------*#
#*----------------------------------JQUERY Scripts for record cuirrent filer --------------------------------*#
<script type="text/javascript">
var currentValue = 0;
function handleClick(currentfilter) {
//alert('Old value: ' + currentValue);
//alert('New value: ' + currentfilter.value);
currentValue = currentfilter.value;
//Redirect the page so that will reload with new parameters
window.location = 'http://' + window.location.host + currentValue; //Add 'http://' since host will not include this
}
</script>
#*----------------------------------JQUERY Scripts for record cuirrent filer ends here --------------------------------*#
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
The error page just says that it cannot find a specific webpage. Customer/Delete
I am not sure if this is was the fix for my problem (and it is a little hard to test as the machine is not my own) but later on we reconfigured .net by using aspnet_regiis.exe and the problem looks like it has disapeared.

Page loading slowly in IE

I am using the colorbox on my site due to this the page is loading very slowly in IE as comparison to other browsers. When I remove the colorbox jQuery file the pages are loading fine. How can I resolve this? I am using the following scripts on my site:
<script src="js/script.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"> </script>
<script type="text/javascript" src="js/jquery.colorbox-min.js"></script>
<?php if($_GET['s']=="invoices") {?>
<script src="js/thickbox1.js" type="text/javascript"></script>
<?php } else {?>
<script src="js/thickbox.js" type="text/javascript"></script>
<?php }?>
<script src="js/jquery.treeview.min.js" type="text/javascript"></script>
<script src="js/jquery.tipTip.minified.js" type="text/javascript"></script>
You could try defering script execution. This way it would be executed later, when the page is already loaded. Also, you can put it in the end of your HTML document, right before the closing </body> tag. The browser could then render most of the UI and only then load "colorbox".
Here's an option: Load your scripts via JavaScript on DOM ready.
Consider the following:
if (window.addEventListener) { // for non-crappy browsers
window.addEventListener('load', loadHandler, false);
} else if (window.attachEvent) { // for IE
window.attachEvent('onload', loadHandler);
}
function loadHandler() {
var scripts = {
'scripts': {
'src': 'js/scripts.js',
'type': 'text/javascript'
},
'jquery': {
'src': 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js',
'type': ''
},
'colorbox': {
'src': 'js/jquery.colorbox-min.js',
'type': 'text/javascript'
},
'thickbox1': {
'src': 'js/thickbox1.js',
'type': 'text/javascript'
},
'thickbox': {
'src': 'js/thickbox.js',
'type': 'text/javascript'
},
'treeview': {
'src': 'js/jquery.treeview.min.js',
'type': 'text/javascript'
},
'tipTip': {
'src': 'js/jquery.tipTip.minified.js',
'type': 'text/javascript'
}
};
for (var key in scripts) {
script = document.createElement('script');
script.src = scripts[key]['src'];
script.type = scripts[key]['type'];
document.body.appendChild(script);
}
}
This way, your scripts will only load when the page is ready.

Categories

Resources