Insert a PHP variable in Js ( JQuery) - javascript

I wanna start by saying that I have absolutely NO knowledge in JS ( which I think I'm gonna learn because I'm over-heating like never before ).
I'm making a website for a friend , and I wanted to add a little more stylish that just plain CSS3 & HTML, So I went on Google and did a little research and I downloaded a free usable jQuery plugin called "Simple Modal".
I want to display a PHP variables inside that Modal.
Here's a screenshot of it:
And here is the minimum required to make the plugin work properly on any page:
> <link rel="stylesheet" href="simplemodal.css" type="text/css"
> media="screen" title="no title" charset="utf-8">
> <script src="assets/javascript/mootools-more-1.3.1.1.js" type="text/javascript charset="utf-8"></script>
> <script src="/js/simple-modal.js" type="text/javascript" charset="utf-8"></script>
> <script src="assets/javascript/demo.js" type="text/javascript" charset="utf-8"> </script>
Now here comes the problem. The content of the Modal is in -> simple-modal.js in the following form:
$("modal").addEvent("click", function(e){
e.stop();
var SM = new SimpleModal({"btn_ok":"Confirm button"});
// Confirm Button
SM.addButton("Confirm", "btn primary", function(){
alert("Action confirm modal");
this.hide();
});
// Cancel button
SM.addButton("Cancel", "btn");
SM.show({
"model":"modal",
"title":"Modal Window Title",
"contents":"<p >Hey , how you doing? Nice weather today!</p>"
});
})
In order to edit the content that is displayed , i need to edit the "contents".
I tried to put my PHP variable in it .. It didn't worked .. Googled it... And I found a solution. Which is putting a JS variable and then, PHP one on the main page.
<?php $content = $user['username']; ?>
<script type="text/javascript"> var name = "<?= $content ?>"; </script>
So after my new found , I tried to do this:
"contents":"<p>Hey" + name + ", how you doing? Nice weather today!</p>"
Didn't work. I then, tried (To see , maybe the variable was the problem ):
"contents": name
And this time it worked. It seems , for an unknown reason to me, that I can't 'combine' 2 things(? if that's a proper way to name them all).
I even tried things such as "Good" + "Morning" but I got the same result.
I'm very confused on why is that.
So, if anybody could be of any help by explaining me why this is happening, how to fix it or at least give a precise path for researches, I would be very graceful.
Thank you.

<?php $content = $user['username']; ?>
<script type="text/javascript">
var name = "<?= $content ?>";
var fullcontent = "<p>Hey" + name + ", how you doing? Nice weather today!</p>";
</script>
and here it will be
"contents":fullcontent
Where as for the modal you can try EXTJS its quite efficient and easy to use.

Related

Adding placeholder text to Wordpress wp-login.php page

So I want to add placeholder text to the Username and Password fields on the standard wp-login.php page - I don't want to edit the actual wp-login.php page because every time WordPress is updated my amends will just be wiped.
So! In functions.php I've added a simple function to add a .js file (and some css files but I don't think that's important for this) to the wp-login.php page where I have this code - here is my function in functions.php
function my_custom_login() {
echo '<link rel="stylesheet" type="text/css" href="/shared-assets/css/main-screen-styles.css" />';
echo '<link rel="stylesheet" type="text/css" href="' . get_bloginfo('stylesheet_directory') . '/css/campsite-finder-screen-styles.css" />';
echo '<script type="text/javascript" href="/shared-assets/js/test.js">
</script>';
}
add_action('login_head', 'my_custom_login');
And here is my js file
jQuery(document).ready(function(){
jQuery('#user_login').attr('placeholder', 'Name');
jQuery('#user_email').attr('placeholder', 'Email');
jQuery('#user_pass').attr('placeholder', 'Password');
});
And this is where I get stuck .. in my mind that should work, I've checked the IDs and they all seem to line up but I'm clearly doing something wrong, you can see the page here http://www.camp-site-finder.com/wp-login.php
If you view the source you can see the link to my .js file and I'm referencing jQuery so errmm, have I done something stupid along the way or is there a better way of doing this?
If anyone can point me in the right direction on this one I'd be very grateful
N
you didn't include .JS file in <script src="something.js"> . you have included it in <link rel=stylesheet > tag that's the problem i have found in your page

intro js is not worked when checking Cookies

i want to create INTRO js to my website, when user first time visit my website.
I use cookies with PHP. but its not worked.
This is my code
if(isset($_COOKIE["userip"]))
{
echo " $_COOKIE[userip]";
}
else
{
?>
<script>
//I THINK THE PROBLEM IS AT THIS JS LINE
// introJs();
//javascript:introJs.start();
introJs().setOption('showProgress', true).start();
</script>
<?php
setcookie("userip", "mycookiename", time()+3600);
}
<script type="text/javascript" src="intro.js"></script>
but if i put:
introJs().setOption('showProgress', true).start();
in body onload it is work.
but what i need is checking cookies first.
pls help me
thank you
my problem is now fixed,
i change javascript code like be like this:
<script>
$(document).ready(function(){
javascript:introJs().setOption('showProgress', true).start();
});
</script>
I think your issue is resolved by changing the order of scripts (or maybe adding a close tag to your first):
<!-- load intro.js FIRST -->
<script type="text/javascript" src="intro.js"></script>
<!-- use intro.js -->
<script>
// include any options you want
introJs().start();
// set cookies if you want
// ...
</script>

Passing a PHP variable into Javascript returns NULL

I know there are a lot of questions covering something similar, but I've tried the answers without any luck.
Snippet of PHP:
$usernum_query = "SELECT numPersonID FROM tbllogins WHERE txtUserName='$currentuser'";
if(!$usernumber = $db1->query($usernum_query)){
die('There was an error running the usernumber query [' . $db1->error . ']');
}
while($row = $usernumber -> fetch_assoc()) {
$userIDnum = $row['numPersonID'];
$userIDnum = utf8_encode($userIDnum);
}
Snippet of Javascript:
$(function(){
$("#0").click(function(){
var userIDnum = <?php echo json_encode($userIDnum); ?>;
alert(userIDnum);
The most common answer I've come across says to UTF_encode my variable, which I think I've done correctly. I've also tried:
var userIDnum = <?php echo $userIDnum; ?>;
Which doesn't work.
In my HTML outside of the script,
<?php echo json_encode($userIDnum); ?>
return "90" (with the quotes)
<?php echo $userIDnum; ?>
returns 90 (without the quotes).
Within the script, I get null and no alert box, respectively.
Any ideas as to why the variable isn't passed into the script? Thanks!
edit: tried with quotes and got the same result
[Taken from comments as requested]
If I can make a recommendation, put your value in a data-attribute in the HTML (e.g. <body data-user-id="<?php echo $userId ?>">. This keeps you from mixing code languages together which is hard to read, and would allow your external script to run correctly without making it a PHP page.
As far as IE9, I'll take a quick look. You might want to see how jQuery manages the data attributes. You should, at the least, have access to
domObject.getAttribute('data-user-id').
Yep, just did a quick lookup, and even IE10 doesn't support the dataset feature. So, you'll need to use getAttribute for IE <= 10.
A solution based on a suggestion by calamari:
In the HTML:
<!DOCTYPE html>
<!--[if lt IE 11 ]> <html class="ie10orless"> <![endif]-->
<head>
... more code here ...
And in the script:
var oldIE;
if ($('html').is('.ie10orless')) {
oldIE = true;
}
if (oldIE) {
var x = document.getElementsByTagName("div")[0].getAttribute("data-number");
alert("in IE");
alert(x);
} else {
var userinfo = document.querySelector('#user');
alert("NOT in IE");
alert(userinfo.dataset.number);
}
Hope this helps someone else. Thanks everyone for the other suggestions as well.
There are couple of things to check. Lets say this is your script:
<?php $htmlString= 'testing'; //Lets say this is a snippet of your php
?>
<html>
<body>
<script type="text/javascript"><!-- And this is the snippet of your JS -->
// notice the quotes around the ?php tag
var htmlString="<?php echo $htmlString; ?>"; //Make sure there's double
//quotes around your php
alert(htmlString);
</script>
</body>
</html>
Make sure you have PHP and JS in a file called .php. If its an external .js file, php inside it will not work (you can rename the JS file to a .php extension if you have it set up that way)
Also make sure you have the html, php and js setup the way above. There has to be double quotes around php, for example:
var userIDnum = <?php echo json_encode($userIDnum); ?>;
change this to below:
var userIDnum = "<?php echo json_encode($userIDnum); ?>";

Update a div with jQuery [duplicate]

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

XML in HTML with FadeIn-Effects

I am currently working on a banner with different texts in different languages. The banner has to be HTML (+CSS) and JS/jQuery. I though about going with an XML for the multilingual part.
Here's my html (part of it):
<script type="text/javascript" language='javascript' src='./js/jquery-2.1.0.js'></script>
<script type="text/javascript" language="javascript" src='./js/xmltranslation.js'></script>
<script type="text/javascript" language='javascript' src='./js/jquery.lettering.js'></script>
<script type="text/javascript" language='javascript' src='./js/jquery.textillate.js'></script>
.
.
.
<h1 id="title" class="tlt" data-in-effect="fadeInLeft"></h1>
My solution with the XML file is done per jQuery:
$(function() {
var filename = location.pathname.substring(location.pathname.lastIndexOf("/") + 1);
filename = filename.split(".")[0];
var language = 'de';
$.ajax({
url: 'content.xml',
success: function(xml) {
$(xml).find(filename).each(function(){
var id = $(this).attr('id');
var text = $(this).find(language).text();
$("#" + id).html(text);
});
}
});
});
That works great so far. It displays the right phrases at the right container.
But I want to use the "fadeInUp" etc. effects, found in the jquery.textillate.js library (https://github.com/jschr/textillate).
They work great, if I have a text in the tag:
<h1 id="title" class="tlt" data-in-effect="fadeInLeft">Test</h1>
The test is fading in smoothly. But it isn't working because of the XML parsing. I think, the XML parsing is done after the page is loaded, while the Fade in effect takes place, when the page is rendered.
Has anybody a better solution? I already thought about parsing the XML with jQuery or JS and put the whole page between a -Tag and output the html parts with
document.write
but since other people in my company who only have basic html skills should work with the files aswell, I would prefer another solution.
Or does anybody know another fade in-Effect library?
Edit:
My solution (adding in the JQuery XML parsing):
$("#" + id).html(text).hide().fadeIn(1000)
You could try using this library. It's worked for me when dynamically populating pages before. you just need to make the element hidden until page load. So an easy way might be to set the elements opacity to 0 then use the setTimeout function then add the class you want to the element. an example:
setTimeout(function(){
$('foo').addClass(animate fadeIn);
},100);

Categories