This question already has answers here:
Wordpress how to use jquery and $ sign
(17 answers)
Why is my javascript file not found by wordpress? and why doesn't my javascript file refresh?
(6 answers)
Closed 5 years ago.
I have a page template which is applied to a specific page on my wordpress page. Usually for all of my other scripts i put them in my footer.php and they load from there beautifully. On this specific page though I want to load a script that only should be running on this page. So in my template i include it like this:
<?php
/**
* Template Name: Template
*/
?>
<?php get_header(); ?>
<script src="<?php echo get_template_directory_uri(); ?>/js/teacher-signup.js"></script>
<?php get_footer( ); ?>
Unfortunately when doing that I only get errors like:
Uncaught TypeError: $(...).whatever is not a function
Is there some way in Wordpress to include a couple of scripts on a specific template only? Or am I missing something?
Thanks in advance
register the script like wp recommends:
wp_register_script('your_file_name', get_template_directory_uri() . '/assets/js/some_file.js', false, null, true);
than enqueue the registered script for that specific page/template
if (is_page('page_name') ) {
wp_enqueue_script('your_file_name');
}
you can also add a conditional for the page template name if you want:
if (is_page_template("template_name.php')
You can make if conditional is_page() in certain page id / page slug for example
<?php if (is_page( 1 )) : ?>
<script src="<?php echo get_template_directory_uri(); ?>/js/teacher-signup.js"></script>
<?php endif; ?>
You can put it on your footer.php theme
This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 6 years ago.
I have three files a .php, a .html and a .js. How can I combine all three of them so that I can use the value of a variable set in php in JavaScript?
I will have to save this file by .php extenstion
<html>
<head> </head>
<body>
<?php
// here I can write my php code ?> // I can end it any time to include some JS code here
<script> Some js code</script>
<?php // and start again to write some more php code
?>
</body>
</html>
I have been searching stack overflow and other sites on this one for a few days and can't find enough information to solve my exact problem.
I have also referred to 'create web charts with JqPlot' by Fabio Nelli, while a great book it does not address my circumstances.
I do not have a great grasp of java script which may be some of my problem.
I am trying to get some data charted into a bar graph and think that the data is not getting encoded to JSON in the required format leading to the failure.
I may also not have my JavaScript component of my php document structured correctly.
(My source MySQL data is being handled by PhP and builds the required table - my theory behind this is to pull a table up and use to compare with a JqPlot Chart).
My bits of relevant code
Head:
<script type='text/javascript'> chart_data = ".json_encode($data_array).";</script>
Body (after fetching php variables as array through a html form filtering the data)
// creates array for json_encode
$data_array [] = array($inj_data2['count'], $damage_data2['count']);
Section that outputs the chart canvas and hopefully colorful data (using Bootstrap)
print ("<div class='panel-group'>
<div class='panel panel-default'>
<div class='col-sm-6 col-md-6 col-lg-6'><div class='row'><div id='chartdiv'></div>");
And for page loading speed the Jq Plot is at the foot of the script:
?>
</body> <!-- side bar chart source info http://www.jqplot.com/examples/barTest.php# !-->
<script type="text/javascript" src="jquerychart/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="jquerychart/jquery.jqplot.js"></script>
<script type="text/javascript" src="jquerychart/jqplot.barRenderer.js"></script>
<script type="text/javascript" src="jquerychart/jqplot.pieRenderer.js"></script>
<script type="text/javascript" src="jquerychart/jqplot.categoryAxisRenderer.js"></script>
<script type="text/javascript" src="jquerychart/jqplot.pointLabels.js"></script>
<link rel="stylesheet" type="text/css" href="jquerychart/jquery.jqplot.css" />
<script>
$(document).ready(function(){
var plot4 = $.jqplot('chartdiv', [chart_data],
{
stackSeries: true,
captureRightClick: true,
seriesDefaults:{
renderer:$.jqplot.BarRenderer,
shadowAngle: 135,
rendererOptions: {
barDirection: 'horizontal',
highlightMouseDown: true
},
pointLabels: {show: true, formatString: '%'}
},
legend: {
show: true,
location: 'e',
placement: 'within'
},
title:"Incidents by Department",
axes: {
yaxis: {
renderer: $.jqplot.CategoryAxisRenderer
}
}
});
});
</script>
</html>
I have checked the json_encode array with
print json_encode($data_array);
And this is output to the browser
[["5","1"],["1","1"],["1","0"]]
These data sets are what I am after, however I believe the " " symbols are what is causing the issue?
I also wish to be able to create labels based on variables (expecting this will require JSON also) and would appreciate pointers on this.
My constraints are that I do not want any AJAX calls and wish to be able to pass all the data within the php script this is written in.
The current code returns a blank canvas below the table, and Firebug console returns:
Error: No data specified
All feedback will be greatly appreciated, please remember JavaScript is not a strong point for me.
The chart also works if data is manually input to the code (ruling out any basic issues around resources).
Cheers Jase
I have solved the problem (99%) I had - it may not be pretty or technically correct ..... if it can be improved upon please let me know......
Converting the variables to an array and removing the double quotes - I needed to declare each variable as the variable type within the array.
Within the php body
$data_array [] = array((int)$inj_data2['count'],(int)$damage_data2['count']);
This was the bit that stumped me for days...
Convert the php array into a JSON object using json_encode.
I knew I had to create a javascript object but a little stuck.
I was mistakenly missing out the php tags in the javascript
My fix was to place this code in the foot (after the body close tag) of he document like this:
<script type='text/javascript'> var chart_data = <?php echo json_encode($data_array);?></script>
Then declare this javascript variable within the JqPlot code like this:
var plot4 = $.jqplot('chartdiv', chart_data,
{
Hopefully this can assist someone in the future I still need to work out how to add the required text labels from variables.
Cheers Jase
I have a site that creates a profile page on the fly. I want to add a skype button to the page for each of the profiles - each profile having a different ID.
I have found this code:
<script type="text/javascript" src="http://www.skypeassets.com/i/scom/js/skype-uri.js"></script>
<div id="SkypeButton_Call_skypeid_1">
<script type="text/javascript">
Skype.ui({
"name": "call",
"element": "SkypeButton_Call_skypeid_1",
"participants": ["skypeid"],
"imageSize": 32
});
</script>
This is just pasted into a php file at the moment.
I need to change the skypeid on the fly - I can do it for the html bits easy enough since I have a php variable for skypeid.
How do I pass this variable into the javascript?
<script type="text/javascript" src="http://www.skypeassets.com/i/scom/js/skype-uri.js"></script>
<div id="SkypeButton_Call_skypeid_1">
<script type="text/javascript">
Skype.ui({
"name": "call",
"element": "SkypeButton_Call_skypeid_1",
"participants": ["<?php echo $skypeid ?>"],
"imageSize": 32
});
</script>
should be what you need. If you cant access that script directly define a global javascript variable and pass that to the script
This question already has answers here:
jQuery AJAX cross domain
(15 answers)
Closed 8 years ago.
I have a jQuery script for refresh the content of a div. The content is get from an external page like mypage.php. The code is this:
page.html:
<html>
<head>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
//var first_load =
function firstLoad()
{
$('#load_tweets').load('mypage.php');//.fadeIn("slow");
}
var auto_refresh = setInterval(
function ()
{
$('#load_tweets').load('mypage.php').fadeIn("slow");
}, 10000); // refresh every 10000 milliseconds
</script>
</head>
<body onLoad="firstLoad()";>
<div id="load_tweets"> </div>
</body>
</html>
If i get the content from mypage.php, that is a php script with an echo command at the end, all work fine. But now i need to get the content of div from here:
http://37.187.90.121:3874/currentsong?sid=1&c=
The output of this source is like this:
Inna - Un Momento
If i replace "myage.php" with "37.187.90.121:3874/currentsong?sid=1&c=" the jquery script in page.htm don't work and return a blank output. What is the problem?
EDIT1:
ok is a policy problem, how i can resolve it?
EDIT2:+
The proxy php page solution don't work.
I have make this php page:
<?php
echo file_get_contents("http://37.187.90.121:3874/currentsong");
?>
But i have this error message:
Warning: file_get_contents() [function.file-get-contents]: http:// wrapper is disabled in the server configuration by allow_url_fopen=0 in /home/mhd-01/www.radiowhitecrash.com/htdocs/Player/GTitle/current_g2.php on line 2
Warning: file_get_contents(http://37.187.90.121:3874/currentsong) [function.file-get-contents]: failed to open stream: no suitable wrapper could be found in /home/mhd-01/www.radiowhitecrash.com/htdocs/Player/GTitle/current_g2.php on line 2
Edit3:
The external service give me a javascript to get the information:
window.centovacast===undefined&&(window.centovacast={}),window.centovacast.options===undefined&&(window.centovacast.options={}),window.centovacast.loader===undefined&&(window.centovacast.loader={attempts:0,external_jquery:!1,loaded:!1,ready:!1,widget_definitions:{},url:"",load_script:function(e){var t=document.createElement("script");t!==undefined&&(t.setAttribute("type","text/javascript"),t.setAttribute("src",e),t!==undefined&&document.getElementsByTagName("head")[0].appendChild(t))},load_widget:function(e){var t=this.widget_definitions[e];t.ref===null&&(t.ref=t.define(jQuery))},jq_get_jsonp:function(e,t,n){return jQuery.ajax({type:"GET",url:e,data:t,success:n,dataType:"jsonp"})},jq_ready:function(){this.ready=!0;for(var e in this.widget_definitions)typeof this.widget_definitions[e].init=="function"&&this.widget_definitions[e].init(jQuery)},jq_loaded:function(){this.external_jquery||jQuery.noConflict(),jQuery.getJSONP=this.jq_get_jsonp;for(var e in this.widget_definitions)this.load_widget(e);this.loaded=!0;var t=this;jQuery(document).ready(function(){t.jq_ready()})},wait:function(){setTimeout(function(){window.centovacast.loader.check()},100)},check:function(){typeof jQuery=="undefined"?(this.wait(),this.attempts++):this.jq_loaded()},init:function(){var e=document.getElementsByTagName("script"),t=e[e.length-1],n;n=t.getAttribute.length!==undefined?t.getAttribute("src"):t.getAttribute("src",2),n.match(/^https?:\/\//i)||(n=window.location.href),this.url=n.replace(/(\.(?:[a-z]{2,}|[0-9]+)(:[0-9]+)?\/).*$/i,"$1"),this.external_jquery=typeof jQuery!="undefined",this.external_jquery||this.load_script(this.url+"system/jquery.min.js"),this.check()},add:function(e,t,n){this.widget_definitions[e]||(this.widget_definitions[e]={define:n,init:t,ref:null}),this.loaded&&this.load_widget(e),this.ready&&t(jQuery)}},window.centovacast.loader.init()),window.centovacast.loader.add("streaminfo",function(e){e.extend(window.centovacast.streaminfo.settings,window.centovacast.options.streaminfo),window.centovacast.streaminfo.settings.manual||window.centovacast.streaminfo.run()},function(e){return window.centovacast.options.streaminfo=e.extend({},window.centovacast.options.streaminfo,window.centovacast.streaminfo?window.centovacast.streaminfo.config:null),window.centovacast.streaminfo={pollcount:0,settings:{poll_limit:60,poll_frequency:6e4},state:{},registry:{},check_username:function(e){e+="";if(!this.registry[e]){if(this.registry.length==1){for(var t in this.registry)e=t;return e}return""}return e},get_streaminfo_element:function(t,n){return e("#"+this.registry[t].id[n])},_handle_json:function(t){if(!t)return;var n=this.check_username(t.rid);!n.length&&t.requestdata&&(n=this.check_username(t.requestdata.rid));if(!n.length)return;if(t.type=="error"){var r=t?t.error:"No JSON object";this.get_streaminfo_element(n,"song").html('<span title="'+r+'">Unavailable</span>'),typeof this.settings.on_error_callback=="function"&&this.settings.on_error_callback(r)}else{var i,s=t.data[0];this.state=s,t.data[0].songchanged=s.song!=this.settings.lastsong,typeof this.settings.before_change_callback=="function"&&this.settings.before_change_callback(t);for(i in s)i!="song"&&(typeof s[i]=="string"||typeof s[i]=="number")&&this.get_streaminfo_element(n,i).html(s[i]);if(typeof s.track=="object"){for(i in s.track)i!="buyurl"&&i!="imageurl"&&i!="playlist"&&(typeof s.track[i]=="string"||typeof s.track[i]=="number")&&this.get_streaminfo_element(n,"track"+i).html(s.track[i]);this.get_streaminfo_element(n,"playlist").html(typeof s.track.playlist=="object"?s.track.playlist.title:"");var o=s.track.buyurl?s.track.buyurl:"javascript:void(0)";e("img#"+this.registry[n].id.trackimageurl).attr("src",s.track.imageurl),e("a#"+this.registry[n].id.trackbuyurl).attr("href",o)}typeof this.settings.after_change_callback=="function"&&this.settings.after_change_callback(t);var u=s.song;u&&u!=this.registry[n].current_song&&(this.get_streaminfo_element(n,"song").fadeOut("fast",function(){e(this).html(u),e(this).fadeIn("fast")}),this.registry[n].current_song=u)}},handle_json:function(e,t,n){e&&window.centovacast.streaminfo._handle_json(e)},poll:function(t){var n=(this.settings.local?"/":window.centovacast.loader.url)+"external/rpc.php",r={m:"streaminfo.get",username:t,charset:this.registry[t].charset,mountpoint:this.registry[t].mountpoint,rid:t};e.getJSONP(n,r,this.handle_json)},_poll_all:function(){for(var e in this.registry)typeof e=="string"&&this.poll(e);(this.settings.poll_limit===0||this.pollcount++<this.settings.poll_limit)&&setTimeout(this.poll_all,this.settings.poll_frequency)},poll_all:function(){window.centovacast.streaminfo._poll_all()},register:function(e,t,n,r){this.registry[t]||(this.registry[t]={charset:n,mountpoint:r,current_song:"",id:{}});var i=e.match(/^cc_strinfo_([a-z]+)_/);i&&(this.registry[t].id[i[1]]=e)},load:function(){var t=e(this).attr("id");if(typeof t!="string")return;var n=t.replace(/^cc_strinfo_[a-z]+_/,""),r="",i="",s=/_cs-([A-Za-z0-9\-]+)$/,o=s.exec(n);o&&(r=o[1],n=n.replace(s,"")),s=/_mp-([A-Za-z0-9\-]+)$/,o=s.exec(n),o&&(i=o[1],n=n.replace(s,"")),window.centovacast.streaminfo.register(t,n,r,i)},run:function(){e(".cc_streaminfo").each(window.centovacast.streaminfo.load),window.centovacast.streaminfo.poll_all()}}});
You can check it at this link:
http://cp.eu2.fastcast4u.com:2199/system/streaminfo.js
Unfortunaly with no identation and in add i have few experiences with javascript i cant' edit the output of this script.
This script give me an output like:
"Radio Name - Author - Title of song"
and this is a link (if you click on it open another page).
I need to get only "Author - Title of song" with no link. Any idea?
Edit4:
I have make another test, i have call the streaminfo.js in a span and i prove to use the document.getX of javascript to get the content of the span in various ways, but i get "undefined" output:
<html>
<head>
<script language="javascript" type="text/javascript" src="http://cp.eu2.fastcast4u.com:2199/system/streaminfo.js"></script>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
var div = document.getElementsByClassName('cc_streaminfo')[0];
document.write("w1" + document.getElementsByClassName('cc_streaminfo')[0]);
document.write("w2" + document.getElementsByClassName('cc_streaminfo')[1]);
document.write("w3" + document.getElementsByClassName('cc_streaminfo')[2]);
var container = document.getElementById ("cc_strinfo_summary_radiowhite");
var spans = div.getElementsByTagName("span");
document.write("il mio script: " + spans[0] + "!");
document.write("il mio script: " + container + "!");
//var first_load =
function firstLoad()
{
$('#load_tweets').load('current_g.php?song=ciao');//.fadeIn("slow");
}
var auto_refresh = setInterval(
function ()
{
$('#load_tweets').load('current_g.php?song=' + cc_streaminfo).fadeIn("slow");
}, 10000); // refresh every 10000 milliseconds
</script>
</head>
<body onLoad="firstLoad()";>
<br>
<span id="cc_strinfo_summary_radiowhite" class="cc_streaminfo">sss</span>
<div id="load_tweets"> </div>
</body>
</html>
I think this has something to do with CORS. Basically, unless the webpage at 37.187.90.121 explicitly states that it trusts the sources of the domain under which your website is running, your browser will not make the request.
If you are the owner of 37.187.90.121, you can add custom headers to allow inclusion of your response in other webpages.
Check your javascript console of your browser to get more details.
Using jQuery to get (.load()) the contents from a div on another page ( same domain ) to add to a div on the current page is like :
$("#dividoncurrentpage").load("/otherpage.php #dividonotherpage");
Is this what you need ?
It's because:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
mstaessen has explained on the post above.
The alternative solution is: You can create a file called, for example song.php and add the following code.
<?php
echo file_get_contents("http://37.187.90.121:3874/currentsong?sid=1&c=");
?>
And update the script to
<script type="text/javascript">
//var first_load =
function firstLoad()
{
$('#load_tweets').load('song.php');//.fadeIn("slow");
}
var auto_refresh = setInterval(
function ()
{
$('#load_tweets').load('song.php').fadeIn("slow");
}, 10000); // refresh every 10000 milliseconds
</script>
Its better to use jQuery $.ajax to get the content. Link
By using $.ajax you have many ways to work around this issue like crossDomain or get the result in Json format by setting the dataType that you will receive from the server to JSON or JSONP