External Javascript file fails to receive variables from javascript block in head - php

I've been searching the net for several hours and can't find an answer in the whole "external js file"-jungle. I hope you guys can help!
In short: My external javascript file doesn't seem to get the variables which I defined in the main.php file..
On main.php I define php variables and "transform" them into
javascript variables
<head>...
<script type="text/javascript">
var phpmain_img = <?php echo json_encode($main_img); ?>;
var phpvar1_large = <?php echo json_encode($var1_large); ?>;
var phpvar2_large = <?php echo json_encode($var2_large); ?>;
var phpvar3_large = <?php echo json_encode($var3_large); ?>;
var phpvar4_large = <?php echo json_encode($var4_large); ?>;
</script>
...
<script language="javascript" type="text/javascript" src="/wshop/ext.js"></script>
</head>
In my ext.js file I want to process those variables. In the
ext.js file I defined a the function swapImage() that will be used
back in the main PHP:
var imgArray = new Array(
phpmain_img,
phpvar1_large,
phpvar2_large,
phpvar3_large
);
function swapImage(imgID) {
var theImage = document.getElementById('theImage');
var newImg;
newImg = imgArray[imgID];
theImage.src = newImg;
}
function preloadImages() {
for(var i = 0; i < imgArray.length; i++) {
var tmpImg = new Image;
tmpImg.src = imgArray[i];
}
}
Result: The swapImage() in the main.php... doesnt work
<div id="image">
<img id="theImage" src="<?=$main_img; ?>" alt="" />
</div>
<div id="thumbs">
<?php
echo "<img src=\"<$main_img_small\" alt=\"\" onmouseover=\"swapImage(0);\">";
echo "<img src=\"$var1_small\" alt=\"\" onmouseover=\"swapImage(1);\">";
echo "<img src=\"$var2_small\" alt=\"\" onmouseover=\"swapImage(2);\">";
echo "<img src=\"$var3_small\" alt=\"\" onmouseover=\"swapImage(3);\">";
?>
<br />
</div>
Any help is greatly appreciated!
UPDATE:
I don't get a specific error, the swapImage functions doesn't work at mouseover. However, I tried to output the variables with e.g. document.write(phpimg_main) but nothing appears which makes me believe that there's something wrong with the handing over of the variables...
Here's the source code browser output
<html>
<head>
<link href="../demo.css" rel="stylesheet" type="text/css" />
<style type="text/css">
....
</style>
<script type="text/javascript">
var phpmain_img = {"0":"http:\/\/path\/to\/main\/image.jpg"};
var phpvar1_large = {"0":"http:\/\/path\/to\/image1.jpg"};
var phpvar2_large = {"0":"http:\/\/path\/to\/image2.jpg"};
var phpvar3_large = null;
var phpvar4_large = null;
</script>
<script language="javascript" type="text/javascript" src="/wshop/ext.js"></script>
</head>
<body onload="preloadImages()">
<div id="image">
<img id="theImage" src="http://path-to-main-image.jpg" alt="" />
</div>
<div id="thumbs">
<img src="http://path-to-main-image.jpg" alt="" onmouseover="swapImage(0);"><img src="http://path-to-image1.jpg" alt="" onmouseover="swapImage(1);"><img src="http://path-to-image2.jpg" alt="" onmouseover="swapImage(2);">
<br />
</div>
</body>
`
UPDATE 2:
Thanks for your input and answers! Of course, you're right, I need a string and not an object, so the encoding is a great hint.
However the problem is still not solved with [0]. Even if I hardcode it like below, the second javascript block (which I tried to outsource as an external js-file before) doesn't get the variables defined in the first javascript block.
<script type="text/javascript">
var phpmain_img = "http://www.abc.de/path-img_main.jpg";
var phpvar1_large = "http://www.abc.de/path-img1.jpg";
var phpvar2_large = "http://www.abc.de/path-img2.jpg";
var phpvar3_large = "http://www.abc.de/path-img3.jpg";
var phpvar4_large = "http://www.abc.de/path-img4.jpg";
</script>
<script language="javascript" type="text/javascript">
var imgArray = new Array(
phpmain_img,
phpvar1_large,
phpvar2_large,
phpvar3_large,
phpvar4_large
);
function swapImage(imgID) {
var theImage = document.getElementById('theImage');
var newImg;
newImg = imgArray[imgID];
theImage.src = newImg;
}
function preloadImages() {
for(var i = 0; i < imgArray.length; i++) {
var tmpImg = new Image;
tmpImg.src = imgArray[i];
}
}
</script>
Browser Source View Output:
<script type="text/javascript">
var phpmain_img = "http://www.abc.de/path-img_main.jpg";
var phpvar1_large = "http://www.abc.de/path-img1.jpg";
var phpvar2_large = "http://www.abc.de/path-img2.jpg";
var phpvar3_large = "http://www.abc.de/path-img3.jpg";
var phpvar4_large = "http://www.abc.de/path-img4.jpg";
</script>
<script language="javascript" type="text/javascript"> //this i actually wanted to outsource into an external js-file
var imgArray = new Array(
phpmain_img,
phpvar1_large,
phpvar2_large,
phpvar3_large,
phpvar4_large
);
function swapImage(imgID) {
var theImage = document.getElementById('theImage');
var newImg;
newImg = imgArray[imgID];
theImage.src = newImg;
}
function preloadImages() {
for(var i = 0; i < imgArray.length; i++) {
var tmpImg = new Image;
tmpImg.src = imgArray[i];
}
}
</script>
Sorry, for the long topic here. I hope you can follow! I'm giving my best to learn!

Although I'm not PHP expert, did you possibly mean
var phpmain_img = "<?php echo urlencode($main_img); ?>";
instead of
var phpmain_img = <?php echo json_encode($main_img); ?>;
If you look at rendered markup, it is obvious that image variables don't contain what you expected:
var phpmain_img = {"0":"http:\/\/path\/to\/main\/image.jpg"};
Instead of a string, it is an object.

Related

How can I print result in consecutive textarea?

I am again here for same question again.
Now my old problem is solved. I have two files index.html and code.js
1) index.html
<html>
<head>
<title> perl </title>
<link rel="stylesheet" href="http://code.guru99.com/css/1140.css" type="text/css" media="screen" />
<link rel="stylesheet" href="http://code.guru99.com/css/styles.css" type="text/css" media="screen" />
<script src="http://code.guru99.com/php/lib/codemirror.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">></script>
<link rel="stylesheet" href="http://code.guru99.com/Sanjay/lib/codemirror.css" type="text/css" media="screen" />
<script src="code.js"></script>
<script type="text/javascript" src="http://code.guru99.com/perl/perl.js"></script>
<style>
.CodeMirror {
border: 1px solid #eee;
height: auto;
width : 600px;
}
.CodeMirror-scroll {
height: auto;
overflow-y: hidden;
overflow-x: auto;
}
</style>
</head>
<body>
Integer : whole numbers e.g. -3, 0, 69. The maximum value of an integer is platform-dependent. On a 32 bit machine, its usually around 2 billion. 64 bit machines usually have larger values. The constant PHP_INT_MAX is used to determine the maximum value.
<pre class="codeguru">say 'hi';</pre>
Let us now look at how PHP determines the data type depending on the attributes of the supplied data.
<pre class="codeguru">say 'hello';</pre>
Floating point numbers
<pre class="codeguru">say 'you r amazing';</pre>
Character strings
<pre class="codeguru">say 'i am fine';</pre>
</div>
<form class="hidden code-box" method="GET" name="sample">
<div dir="ltr"><textarea class="php" name="codeguru"></textarea></div>
<input type="button" value="Run" />
</br></br>
Output:</br></br>
<textarea id="print-result" disabled="true" cols="77"></textarea></br>
</form></div>
</body>
</html>
and code.js contain following code
$(document).ready(function()
{
$('pre.codeguru').each(function()
{
var pre = this;
var form = $('form[name=sample]').clone();
$(form).removeAttr('name');
$(form).removeClass('hidden');
$($(form).find('textarea')[0]).val($(pre).text());
var id = $(pre).attr('id');
$(form).find('div textarea[name=code]').first().attr('id', id);
$(pre).replaceWith(form);
});
var n = 0;
$('input[type=button]').each(function () {
$(this).click(function (x) {
return function () {
execute(x);
};
}(n++))
}
);
window.editors = [];
$('textarea[name=codeguru]').each(function()
{
window.editor = CodeMirror.fromTextArea(this,
{
lineNumbers: true,
matchBrackets: true,
mode: "application/x-httpd-perl",
tabMode: "shift"
});
editors.push(editor);
});
});
function execute(idx) {
p5pkg.CORE.print = function(List__) {
var i;
for (i = 0; i < List__.length; i++) {
document.getElementById('print-result').value+=p5str(List__[i])
}
return true;
};
p5pkg["main"]["v_^O"] = "browser";
p5pkg["main"]["Hash_INC"]["Perlito5/strict.pm"] = "Perlito5/strict.pm";
p5pkg["main"]["Hash_INC"]["Perlito5/warnings.pm"] = "Perlito5/warnings.pm";
var source = editors[idx].getValue();
alert(source);
var pos = 0;
var ast;
var match;
document.getElementById('print-result').value = "";
try {
var start = new Date().getTime();
var js_source = p5pkg["Perlito5"].compile_p5_to_js([source]);
var end = new Date().getTime();
var time = end - start;
// run
start = new Date().getTime();
eval(js_source);
end = new Date().getTime();
time = end - start;
}
catch(err) {
//document.getElementById('log-result').value += "Error:\n";
}
}
When I run this code its works fine give me output also. But my problem is that the output prints in one textarea only. I want to print the output in consecutive textarea.
This code in code.js prints the output.
p5pkg.CORE.print = function(List__) {
var i;
for (i = 0; i < List__.length; i++) {
document.getElementById('print-result').value += p5str(List__[i])
}
}
So what I have to do for print my output in consecutive textarea.Please please help me.
using same id for different elements in a page can create problems..
make the text area like this..
<textarea id="print-result" class='print-result' disabled="true" cols="77></textarea>
Modified code in code.js that prints the output is
p5pkg.CORE.print = function(List__) {
var i,concat='';
for (i = 0; i < List__.length; i++) {
concat=$(".print-result").eq(idx).val();
$(".print-result").eq(idx).val(concat+p5str(List__[i]));
}
return true;
}
Add name attribute to your textarea like
<textarea id="print-result" disabled="true" name="code" cols="77"></textarea>
in place of
<textarea id="print-result" disabled="true" cols="77"></textarea>
Updated
In your code I can't see a textarea having name="code", and you are using it.
Is it codeguru?

Javascript not firing another function

I am trying to add new elements (buttons) to html file using javascript. Here is the working script:
<div id="examples">
<?php
while ($row=mysql_fetch_array($result))
{?>
<script type="text/javascript">
var element = document.createElement("input");
element.type = "button";
element.value = "Click me";
element.id = <?=$row['id'];?>;
var foo = document.getElementById("examples");
foo.appendChild(element);
</script>
<?php
}
?>
</div>
The script adding new elements to html file, but I would like to change some of the properties (for example:button size) too.
I have method SetProperties(id, fontSize) and if I am adding it in code when elements should be created it doesn't work, it even do not creates that new elements. Here is the code which makes me a headache:
<div id="examples">
<?php
while ($row=mysql_fetch_array($result))
{?>
<script type="text/javascript">
var element = document.createElement("input");
element.type = "button";
element.value = "Click me";
element.id = <?=$row['id'];?>;
var foo = document.getElementById("examples");
foo.appendChild(element);
*SetProperties(<?=$row['id'];?>, <?=$row['fontSize'];?>);*
</script>
<?php
}
?>
</div>
And here is the function which changes new elements properties:
<script type="text/javascript">
function SetProperties(id, fontSize)
{
var btn = document.getElementById(id);
btn.style.fontSize = fontSize + "px;";
}
</script>
you may try like this
<style>
#examples [type=button]
{
font-size:25px;
}
</style>
<div id="examples">
<?php
while ($row=mysql_fetch_array($result))
{?>
<script type="text/javascript">
var element = document.createElement("input");
element.type = "button";
element.value = "Click me";
element.id = <?=$row['id'];?>;
var foo = document.getElementById("examples");
foo.appendChild(element);
</script>
<?php
}
?>
</div>
About your code, try using just strings for the id:
element.id = "<?=$row['id'];?>";
/* ... */
SetProperties("<?=$row['id'];?>");
Because getElementById expects a string. In some cases JavaScript could cast the number to string, but it depends on how getElementById is implemented in the browser.
Besides that, the code that your are doing can be implemented in a much better way:
Output the HTML directly
Use CSS for changing the styles
If you need to associate some meta-data to your button so you can refer for example to a database id, use data attributes, instead of messing with the ID.
For example:
<div id="examples">
<?php
while ($row=mysql_fetch_array($result)) {?>
<button class="do-something" data-row-id="<?=$row['id'];?>">Click me</button>
<?php
}
?>
</div>
Then in CSS:
.do-something { /* set CSS properties */ }
Also if you need to add a click handler, and you have a lot of buttons, you can assign the handler to the container of buttons (the example uses jQuery):
$('#examples').on('click', '.do-something', function () { /* handler */ });
This is more efficient than assigning the click handler for each button.
<script type="text/javascript">
function SetProperties(id)
{
document.getElementById(id).style.fontSize = 25 + "px";
}
</script>
<div id="examples">
<?php
while ($row=mysql_fetch_array($result))
{?>
<script type="text/javascript">
var element = document.createElement("input");
element.type = "button";
element.value = "Click me";
element.id = <?=$row['id'];?>;
var foo = document.getElementById("examples");
foo.appendChild(element);
SetProperties(<?=$row['id'];?>, <?=$row['fontSize'];?>);
</script>
<?php
}
?>
</div>
I agree with #meagar -- why emit JavaScript when you can do it all on the server?
Here's how you would add the elements directly on the server-side, instead of emitting JavaScript that then adds the elements on the client-side:
<div id="examples">
<?php
while ($row=mysql_fetch_array($result))
{?>
<input type="button" value="Click me" id="<?=$row['id'];?>" />
<?php } ?>
</div>
and to style it, put this in the <head> or in your CSS file:
<style>
#examples input {
font-size: 25px;
}
</style>
You may try like this to avoid creating `buttons` at `client` side
<div id="examples">
<?php
while ($row=mysql_fetch_array($result))
{?>
<input type="button" value="Click me" id="<?=$row['id'];?>" style="font-size: 25px;" />
<?php } ?>
</div>

php echo not working for strtotime function while assigning it to a javascript variable

This works fine
<html>
<head>
<script src="jquery.js"></script>
<script>
$(document).ready(function(){
var timeLeft = <?php echo '1279'; ?>;
$("#time").text(timeLeft);
});
</script>
</head>
<body>
<div id="time"></div>
</body>
</html>
but this doesn't
<script>
$(document).ready(function(){
var timeLeft = <?php echo strtotime("now"); ?>;
$("#time").text(timeLeft);
});
</script>
It gives error Uncaught SyntaxError: Unexpected token < .
It is a php extension file.
Try this:
<script>
$(document).ready(function(){
var timeLeft = '<?php echo strtotime("now"); ?>';
$("#time").text(timeLeft);
});
</script>
Directly using php in javascript is very dangeorous. Because timetostr may output some warnings about timezone etc and your code will be broken without any visual clue.
In my projects, If I have to use any php output in my javascript, I create hidden divs and access the value from javascript:
<div class='hidden' id='values'>
<div class='val-time'><?php echo strtotime("now"); ?></div>
</div>
<script>
$(document).ready(function(){
var timeLeft = $("#values .val-time").html();
$("#time").text(timeLeft);
});
</script>
So whenever you want to debug your code, simply remove "hidden" class from #values and look at which values are ouputted by PHP.

Inserting json data into html page in list

I'm trying to get information from mysql and post the information into an html page. Here's what I've got so far:This is my tenantlistmob.php
<?php
include('connection.php');
$result = mysql_query("SELECT * FROM tenanttemp");
while ($row = mysql_fetch_assoc($result))
{
$array[] = array($row['TenantFirstName']);
}
echo json_encode($array);
?>
When i call tenantlistmob from browser directly it shows [["Humayun"],["Sahjahan"],["Bayezid"],["Bayezid"],["Asaduzzaman"],["Mouri"]] where firstnames are comming. I like to use this name in html page. my html page is
<!DOCTYPE HTML>
<html>
<link rel="stylesheet" href="styles/main.css" />
<script type="text/javascript" src="jquery.js"></script>
<body>
<div id="output">this element will be accessed by jquery and this text replaced</div>
<script id="source" type="text/javascript">
$(function ()
{
$.ajax({
url: 'tenantlistmob.php',
data: "",
dataType: 'json',
success: function(data)
{
var id = data;
//var vname = data[1]; //get name
$.each(id, function (val)
{
$('#output').html(""+id);
});
}
});
});
</script>
<form id="formset">
<fieldset id="fieldset">
<h3 align="center">Tenant List</h3><hr/>
name1<br /><hr/>
name2 <br /><hr/>
</fieldset>
</form>
<a id="box-link1" class="myButtonLink" href="category1.php"></a>
</div>
</body>
</html>
My output(main.css) is like this
#output
{
color:#ffffff;
font-size : 20px;
margin : 0;
letter-spacing:1px;
width:480px;
}
I am getting the first name asHumayun,Sahjahan,Bayezid,Bayezid,Asaduzzaman,Mouri in top-left corner. But i like to get the name as list(name1,name2) with link. when i click on a name(name1,name2) it will show details of the name. How can I do this?
Thank in advance
It looks like your looking to iterate the JSON using JavaScript. Since you're using jQuery, you simply need to "iterate" the JSON result. Technically 0 comes before 1 in JavaScript.
var _result = $data[0];
$.each(_result, function (val)
{
console.log(val);
});
http://api.jquery.com/jQuery.each/
Try this:
<?php
include('connection.php');
$result = mysql_query("SELECT * FROM tenanttemp");
$array = array();
while ($row = mysql_fetch_assoc($result))
{
$array[] = $row['TenantFirstName'];
}
echo json_encode($array);
?>

Gigya User Object is Missing

I've just started using Gigya to allow users to connect to my site. I already have a login system so I just want to connect existing users to the Gigya service.
To do this I have called the "gigya.services.socialize.notifyLogin" function which returns a Gigya User object with the UID provided by my site. [fig 1]
Do I need to do anything with this User object, like add it to a cookie or is it just for reference.
The problem that Im having is on another page, I want to allow users to connect to their social media accounts. I use the "showAddConnectionsUI" function passing my api key, but the returned object does NOT have the User object in, although the documentation says it should. How do I get the users conenctions and the key information from this function. Do I need to send any additional information along with my api key. [fig 2]
I have spent several days reading the wiki, documentation and forum for advice but I am still stuck. Any help would be greatly appreciated. Thanks in advance, Ben
[fig 1]
<script type="text/javascript" src="http://cdn.gigya.com/js/socialize.js?apiKey=<?php echo $key; ?>"></script>
<script type="text/javascript">
var gigyaConf = { APIKey: "<?php echo $key; ?>", signIDs: "true" }
var signature = "<?php echo $signature; ?>";
var siteUID = "<?php echo $userId; ?>";
var timestamp = "<?php echo $timestamp; ?>";
var gigyaParams =
{
siteUID:siteUID,
timestamp:timestamp,
signature:signature,
callback:gigyaNotifyLoginCallback
};
gigya.services.socialize.notifyLogin(gigyaConf, gigyaParams);
function gigyaNotifyLoginCallback(eventObj) {
if ( eventObj.errorCode != 0 ) {
alert('Gigya Error: ' + eventObj.errorMessage);
}
}
</script>
[fig 2]
<script type="text/javascript" lang="javascript" src="http://cdn.gigya.com/JS/socialize.js?apikey=<?php echo $key; ?>"></script>
<script>
var conf = { APIKey: '<?php echo $key; ?>', signIDs: 'true' };
$(document).ready(function(){
gigya.services.socialize.getUserInfo(conf, { callback: renderUI });
gigya.services.socialize.addEventHandlers(conf,
{
onConnectionAdded: renderUI,
onConnectionRemoved: renderUI
});
});
</script>
<script>
function renderUI(res) {
if (res.user != null && res.user.isConnected) {
document.getElementById("name").innerHTML = res.user.nickname;
if (res.user.thumbnailURL.length > 0)
document.getElementById("photo").src = res.user.thumbnailURL;
else
document.getElementById("photo").src = "http://cdn.gigya.com/site/images/bsAPI/Placeholder.gif";
document.getElementById("profile").style.display = "block";
} else {
document.getElementById("profile").style.display = "none";
}
}
</script>
<div id="content">
<h5>Step 1: Connect</h5>
<div id="divConnect"></div>
<script type="text/javascript">
gigya.services.socialize.showAddConnectionsUI(conf, {
height:65,
width:175,
showTermsLink:false,
hideGigyaLink:true,
useHTML:true,
containerID: "divConnect"
});
</script>
<br />
<h5>Step 2: See User Info</h5><br />
<div id=profile style="display:none;">
<img id="photo" src="" width="60" />
<br />
<span id="name" ></span>
</div>
</div>
Any help, advice, code snippits that would help will be greatly appreciated
Re: your first question, not required to do anything special with the Gigya User object. It's for your reference.
Re: your code, I can't tell if you're using JQuery but I was getting an error with your $(document).ready function. I modified your code slightly by adding body onLoad and everything worked. This assumes you have connected with a provider. Here's my code... hope it helps:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" lang="javascript" src="http://cdn.gigya.com/JS/socialize.js?apikey=<?php echo $key; ?>"></script>
<script>
var conf = { APIKey: '<?php echo $key; ?>', signIDs: 'true' };
function onLoad() {
gigya.services.socialize.getUserInfo(conf, { callback: renderUI });
gigya.services.socialize.addEventHandlers(conf,
{
onConnectionAdded: renderUI,
onConnectionRemoved: renderUI
});
}
</script>
<script>
function renderUI(res) {
if (res.user != null && res.user.isConnected) {
document.getElementById("name").innerHTML = res.user.nickname;
if (res.user.thumbnailURL.length > 0)
document.getElementById("photo").src = res.user.thumbnailURL;
else
document.getElementById("photo").src = "http://cdn.gigya.com/site/images/bsAPI/Placeholder.gif";
document.getElementById("profile").style.display = "block";
} else {
document.getElementById("profile").style.display = "none";
}
}
</script>
<body onload="onLoad()">
<div id="content">
<h5>Step 1: Connect</h5>
<div id="divConnect"></div>
<script type="text/javascript">
gigya.services.socialize.showAddConnectionsUI(conf, {
height:65,
width:175,
showTermsLink:false,
hideGigyaLink:true,
useHTML:true,
containerID: "divConnect"
});
</script>
<br />
<h5>Step 2: See User Info</h5><br />
<div id=profile style="display:none;">
<img id="photo" src="" width="60" />
<br />
<span id="name" ></span>
</div>
</div>
</body>
</html>

Categories