Javascript Slideshow with script.aculo.us - php

I am making a slideshow on my mvc php site using script.aculo.us to animate it. The model looks up the images from the database, fills it into the view and then the javascript uses script.aculo.us to animate it. However, when it gets to the second slide, it stops working and I can find this error message in Chrome's console:
Uncaught TypeError: Cannot call method 'getStyle' of undefined
I cannot work out why it isn't working. Here is the code. Any ideas?
PHP:
<div id="main">
<div id="mainContainer">
<div id="showcaseContent">
<?php $i = 0; foreach($showcase as $ShowcaseItems): ?>
<div id="showcaseSlide<?php echo $i; ?>" <?php if($i != 0){ echo 'style="display: none;"'; }else{ echo 'style="display: block;"'; } ?> >
<img src="<?php echo $ShowcaseItems['showcase_image']; ?>" width="720px" height="275px" />
</div>
<?php ++$i; endforeach ?>
</div>
</div>
Javascript
(I have to use the top 4 loop because the client can put from 2-10 images onto the showcase slideshow):
var slides = new Array();
for(i=0; i<=10; i++){
slides[i] = "showcaseSlide"+i;
if(document.getElementById(slides[i]) == null) break;
};
var wait = 5000;
function startShowcase(){
setInterval(showcase(), wait);
};
function showcase(){
var i = 0;
Effect.Fade(slides[i], {duration: 1.0, from: 1.0, to: 0.0});
i++
if(i == slides.count - 1) {i=0};
Effect.Appear(slides[i], {duration: 1.0, from: 0.0, to: 1.0});
};
Edit:
The error appears on line 544 of the effects.js script that comes with script.aculo.us, which (as far as I can work out) is the line which starts 'from:' in the following code:
Effect.Appear = function(element) {
element = $(element);
var options = Object.extend({
from: (element.getStyle('display') == 'none' ? 0.0 : element.getOpacity() || 0.0),
Uncaught TypeError: Cannot call method 'getStyle' of undefined
to: 1.0,
// force Safari to render floated elements properly
afterFinishInternal: function(effect) {
effect.element.forceRerendering();
},
beforeSetup: function(effect) {
effect.element.setOpacity(effect.options.from).show();
}}, arguments[1] || { });
return new Effect.Opacity(element,options);
};
And here are the relevant sections of the rendered page:
<!DOCTYPE html>
<head>
<!--Title-->
<title>Urban Feather | Home</title>
<!--CSS Styles-->
<link rel="stylesheet" href='http://www.example.com/2012/styles/layout.css' type="text/css" media="screen, projection" />
<link rel="stylesheet" href='http://www.example.com/2012/styles/forms.css' type="text/css" media="screen, projection" />
<link rel="stylesheet" href='http://www.example.com/2012/styles/fonts.css' type="text/css" media="screen, projection" />
<!--Javascript Scripts-->
<script src="http://www.example.com/2012/scripts/sonOfSuckerfish.js" type="text/javascript"></script>
<script src="http://www.example.com/2012/scripts/script.aculo.us/prototype.js" type="text/javascript"></script>
<script src="http://www.example.com/2012/scripts/script.aculo.us/scriptaculous.js?load=effects" type="text/javascript"></script>
<script src="http://www.example.com/2012/scripts/selectreplace.js" type="text/javascript"></script>
<script src="http://www.example.com/2012/scripts/showcase.js" type="text/javascript"></script>
<script src="http://twitter.com/javascripts/blogger.js" type="text/javascript"></script>
</head>
<div id="main">
<div id="mainContainer">
<div id="showcaseContent">
<div id="showcaseSlide0" style="display: block;" >
<img src="http://www.example.com/2012/images/showcase/client3.jpg" width="720px" height="275px" />
</div>
<div id="showcaseSlide1" style="display: block;" >
<img src="http://www.example.com/2012/images/showcase/client3.jpg" width="720px" height="275px" />
</div>
<div id="showcaseSlide2" style="display: block;" >
<img src="http://www.example.com/2012/images/client3.jpg" width="720px" height="275px" />
</div>
</div>

Thanks to stormdrain and my other post (break loop based on an element not existing), I have resolved the problem. The loop was not working as it was called before the divs were rendered and the code needed a little restructuring. Here is my working code:
var count = 0; //A loop for the counter
var wait = 4000; //The amount of time (ms) inbetween transitions
var slides = []; //The empty array of slide ids
function startShowcase(){
for(var i=0; i<10; i++){
slides[i] = "showcaseSlide"+i;;
if(!document.getElementById(slides[i])) break;
};
setInterval(showcase, wait);
};
function showcase(){
if(count==slides.length-2){
count=0;
}
if(document.getElementById(slides[count]).style.display==='none'){
Effect.Appear(slides[count], {duration: 1.0, from: 0.0, to: 1.0});
}else{
Effect.Fade(slides[count], {duration: 1.0, from: 1.0, to: 0.0});
}
count++;
};

http://prototypejs.org/api/element/getStyle
Safari returns null for any non-inline property if the element is
hidden (has display set to 'none').
<?php if($i != 0){ echo 'style="display: none;"'; }else...
function showcase(){
var i = 0;
Effect.Fade(slides[i], {duration: 1.0, from: 1.0, to: 0.0});
//slide[0] is the only slide without display:none,
//so the first slide (slide[0]) works (Fades)!
//Once var i increments, everything is display:none and the
//getStyle used in prototypes Effect.Appear method doesn't work
i++
if(i == slides.count - 1) {i=0};
Effect.Appear(slides[i], {duration: 1.0, from: 0.0, to: 1.0});
//slides[1] has display:none so getStyle in Appear breaks
};
that's my guess anyway...
Update:
Think it's an issue with the counter:
var i = 0;
Effect.Fade(slides[i], {duration: 1.0, from: 1.0, to: 0.0});
i++
if(i == slides.count - 1) {i=0};
Effect.Appear(slides[i], {duration: 1.0, from: 0.0, to: 1.0});
i will always be 0 when showcase() is called by the interval, so on the second interval, it is trying to make slides[0] Effect.Fade which was already faded on the first.
This works:
var slides = new Array();
var count = 0;
for(i=0; i<=10; i++){
slides[i] = "showcaseSlide"+i;
if(document.getElementById(slides[i]) == null) break;
};
var wait = 1000;//shortened because I'm impatient
function startShowcase(){
setInterval(showcase, wait);
};
function showcase(){
if(count==slides.length-1){
count=0;
}
if($(slides[count]).style.display==='none'){
Effect.Appear(slides[count], {duration: 1.0, from: 0.0, to: 1.0});
}else{
Effect.Fade(slides[count], {duration: 1.0, from: 1.0, to: 0.0});
}
count++;
};
Technically, this is more technical; also proper:
var slides = [], count = 0, wait = 4000;
for(var i in $('showcaseContent').select('div')){slides[i] = "showcaseSlide"+i;};
function startShowcase(){setInterval(showcase, wait);};
function showcase(){
(count==slides.length)?count=0:count=count;
($(slides[count]).style.display==='none')?
Effect.Appear(slides[count], {duration: 1.0, from: 0.0, to: 1.0}):
Effect.Fade(slides[count], {duration: 1.0, from: 1.0, to: 0.0});
count++;
};
startShowcase();
YEAH

Related

Can not deserialize instance of String out of START_OBJECT token

I've gone through the other answers to this question, but no one seems to be able to apply it universally. Other questions just go unanswered.
Obviously, I'm getting "Can not deserialize instance of String out of START_OBJECT token." in my console. I believe it happens when I attempt to stringify(response) from my websocketdata.
Here is the code.
<?php /**
* The Header for our theme.
*
* Displays all of the <head> section and everything up till <div id="main">
*
*/ ?>
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<!--<![endif]-->
<head>
<meta http-equiv="Content-Type" content="<?php bloginfo('html_type'); ?>; charset=<?php bloginfo('charset'); ?>" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
<script type="text/javascript"
src='http://martialparks.com/wp-content/themes/js/gamesparks-rt.js'></script>
<script type='text/javascript' src='http://martialparks.com/wp-content/themes/js/gamesparks.js'></script>
<script type='text/javascript'
src='http://martialparks.com/wp-content/themes/js/gamesparks-functions.js'></script>
<script type='text/javascript' src='http://martialparks.com/wp-content/themes/js/hmac-sha256.js'></script>
<link rel="profile" href="http://gmpg.org/xfn/11" />
<link rel="pingback" href="<?php bloginfo('pingback_url'); ?>" />
<?php
wp_head();
?>
</head>
<body <?php body_class() ?>>
<body onload="init()">
<!--Start Header Wrapper-->
<div class="header_wrapper">
<div class="header">
<!--Start Container-->
<div class="container_24">
<div class="grid_24">
<div class="logo"> <a href="<?php echo esc_url(home_url()); ?>"><img src="<?php if (business_directory_get_option('business_directory_logo') != '') { ?><?php echo esc_url(business_directory_get_option('business_directory_logo')); ?><?php
} else {
echo esc_url(get_template_directory_uri() . '/images/logo.png');
}
?>" alt="<?php bloginfo('name'); ?>" /></a></div>
</div>
<div class="clear"></div>
</div>
<!--End Container-->
<div class="clear"></div>
</div>
<div class="clear"></div>
<!--Start Menu Wrapper-->
<div class="menu_wrapper">
<div class="top_arc"></div>
<div class="menu-container">
<div class="container_24">
<div class="grid_24">
<?php business_directory_nav(); ?>
</div>
</div>
<div class="clear"></div>
</div>
<div class="clear"></div>
<div class="bottom_arc"></div>
</div>
<!--End Container-->
<div class="clear"></div>
</div>
<!--End Header Wrapper-->
<div class="clear"></div>
<div class="wrapper">
<!--Start Container-->
<div class="container_24">
<div class="grid_24">
<br/>
<br/>
<br/>
<input id="apiKey" type="hidden" value="A319082inSk2"/>
<input id="apiSecret" type="hidden" value="BNuYLYZAoDZDZyh1F7tbR8BMTiqeJbWt"/>
<label for="apiCredential">Api Credential</label><input id="apiCredential"/>
<label for="username">User Name</label><input id="username"/>
<label for="password">Password</label><input id="password"/>
<button onClick='gamesparks.registrationRequest("testuser", "testuser", "testuser", registerResponse)'>Register</button>
<button onClick='gamesparks.authenticationRequest(username, password, loginResponse)'>Login</button>
<button onClick='gamesparks.accountDetailsRequest(accountDetailsResponse)'>Account Details</button>
<button onClick='customEvent()'>Custom Event</button>
<button onClick='testRT()'>Test RT</button>
<i>Special thanks to the awesome team at GameSparks!</i>
<div id="messages"></div>
<br/>
<br/>
User Name
<div id="displayName" style="color: blue;"></div>
Coins
<div id="Coins" style="color: red;"></div>
Exp
<div id="Exp" style="color: green;"></div>
Leader Points
<div id="LeadP" style="color: darkgreen;"></div>
Hero Points
<div id="HeroP" style="color: purple;"></div>
<style>
#map {
height: 400px;
width: 100%;
}
</style>
<h3>Find a Park</h3>
<div id="map"></div>
<script>
function initMap() {
var Velocity = {lat: 38.308101, lng: -85.815464};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: Velocity
});
var marker = new google.maps.Marker({
position: Velocity,
map: map
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDSHCinT3IVWFCLUudbsMZV6644GNrGiwc&callback=initMap">
</script>
<script type="text/javascript">
//Create a gamesparks object to be used
var gamesparks = new GameSparks();
//Initialse the SDK
function init() {
gamesparks.initPreview({
key: document.getElementById('apiKey').value,
secret: document.getElementById('apiSecret').value,
credential: document.getElementById('apiCredential').value,
onNonce: onNonce,
onInit: onInit,
onMessage: onMessage,
logger: console.log,
});
}
function accountDetailsResponseCreator() {
var response = {
displayName: 'A User',
currencies: {Coins: 'A coin', Exp: 'A exp', LeadP: 'A lead p', HeroP: 'A hero p'}
}
accountDetailsResponse(response)
}
//Callback function to hmac sha256 a nonce with the secret. It's assumed you will have your own method of securing the secret;
function onNonce(nonce) {
return CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA256(nonce, document.getElementById('apiSecret').value));
}
//Callback to handle when the SDK is initialised and ready to go
function onInit() {
console.log("Initialised");
}
//Callback to handle async messages from the gamesparks platform
function onMessage(message) {
console.log("onMessage");
}
//Response handler examples
function registerResponse(response) {
console.log(JSON.stringify(response));
}
function loginResponse(response) {
console.log(JSON.stringify(response));
}
function accountDetailsResponse(response) {
console.log (JSON.stringify(response));//logs the string to console
document.getElementById("displayName").innerHTML = (response.displayName);
document.getElementById("Coins").innerHTML = (response.currencies.Coins);
document.getElementById("Exp").innerHTML = (response.currencies.Exp);
document.getElementById("LeadP").innerHTML = (response.currencies.LeadP);
document.getElementById("HeroP").innerHTML = (response.currencies.HeroP); //returns value of name from string. I've tried doing each line with semicolons at the end, and all in a group with commas separating them. Both just give me the first variable and delete the rest.
}
function customEvent() {
gamesparks.sendWithData(
"LogEventRequest",
{
eventKey: "FIRST_EVENT",
NUMBER_ATTR: 123,
STRING_ATTR: "this is a string",
JSON_ATTR: {key1: 12, key2: "abc"}
},
function (response) {
console.log(JSON.stringify(response));
}
);
}
var apiKey = "2974660weiMa";
var apiSecret = "p5pFVnohi5eWPYETb4aPgeMLtd95bjfJ";
var myTimer = null;
var myRTSession = function () {
};
var numCycles = 0;
myRTSession.started = false;
myRTSession.onPlayerConnectCB = null;
myRTSession.onPlayerDisconnectCB = null;
myRTSession.onReadyCB = null;
myRTSession.onPacketCB = null;
myRTSession.session = null;
myRTSession.start = function (connectToken, host, port) {
var index = host.indexOf(":");
var theHost;
if (index > 0) {
theHost = host.slice(0, index);
} else {
theHost = host;
}
console.log(theHost + " : " + port);
myRTSession.session = GameSparksRT.getSession(connectToken, theHost, port, myRTSession);
if (myRTSession.session != null) {
myRTSession.started = true;
myRTSession.session.start();
} else {
myRTSession.started = false;
}
};
myRTSession.stop = function () {
myRTSession.started = false;
if (myRTSession.session != null) {
myRTSession.session.stop();
}
};
myRTSession.log = function (message) {
var peers = "|";
for (var k in myRTSession.session.activePeers) {
peers = peers + myRTSession.session.activePeers[k] + "|";
}
console.log(myRTSession.session.peerId + ": " + message + " peers:" + peers);
};
myRTSession.onPlayerConnect = function (peerId) {
myRTSession.log(" OnPlayerConnect:" + peerId);
if (myRTSession.onPlayerConnectCB != null) {
myRTSession.onPlayerConnectCB(peerId);
}
};
myRTSession.onPlayerDisconnect = function (peerId) {
myRTSession.log(" OnPlayerDisconnect:" + peerId);
if (myRTSession.onPlayerDisconnectCB != null) {
myRTSession.onPlayerDisconnectCB(peerId);
}
};
myRTSession.onReady = function (ready) {
myRTSession.log(" OnReady:" + ready.toString());
if (myRTSession.onReadyCB != null) {
myRTSession.onReadyCB(ready);
}
};
myRTSession.onPacket = function (packet) {
myRTSession.log(" OnPacket:" + packet.toString());
if (myRTSession.onPacketCB != null) {
myRTSession.onPacketCB(packet);
}
};
function testRT() {
myRTSession.stop();
gamesparks.initPreview({
key: apiKey,
secret: apiSecret,
credential: "",
onNonce: onNonceRT,
onInit: onInitRT,
onMessage: onMessageRT,
logger: console.log,
});
}
function onNonceRT(nonce) {
return CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA256(nonce, apiSecret));
}
function onInitRT() {
console.log("Initialised");
gamesparks.deviceAuthenticationRequest((Math.floor(Math.random() * (999 - 1)) + 1).toString(), null, null, "js", null, null, function (response) {
if (response.error) {
console.error(JSON.stringify(response.error));
} else {
sendMatchmakingRequest();
}
});
}
//Callback to handle async messages from the gamesparks platform
function onMessageRT(message) {
//console.log("message " + JSON.stringify(message));
if (message["#class"] === ".MatchFoundMessage") {
var accessToken = message["accessToken"];
var host = message["host"];
var port = message["port"];
myRTSession.stop();
if (myTimer) {
clearTimeout(myTimer);
}
myTimer = setInterval(mainRTLoop, 10);
myRTSession.start(accessToken, host, port);
} else if (message["#class"] === ".MatchNotFoundMessage") {
console.log("MATCH NOT FOUND");
sendMatchmakingRequest();
}
}
function sendMatchmakingRequest() {
gamesparks.sendWithData("MatchmakingRequest",
{
skill: 1,
matchShortCode: "Match_STD"
},
function (response) {
if (response.error) {
console.error(JSON.stringify(response.error));
} else {
console.log("Match OK...");
}
}
);
}
function mainRTLoop() {
if (myRTSession.started) {
myRTSession.session.update();
var data = RTData.get();
data.setLong(1, numCycles);
myRTSession.session.sendRTData(1, GameSparksRT.deliveryIntent.RELIABLE, data, []);
numCycles++;
}
}
</script>
</body>
</html>
For the life of me, I have no idea what is happening or how to fix it. The problem pops up when I activate a button that references line 173
function loginResponse(response) {
console.log(JSON.stringify(response));
}
But don't let that affect your impartiality. I compared this code to earlier versions of the code I have and could not identify a change in any of my functions.
Well, bottom line is this: When you are an idiot, don't post questions to stackoverflow. No one will respond. Not because they are mean, but because learning the basics is important.
So the problem originated for me in the top of my code with this:
<button onClick='gamesparks.authenticationRequest(username, password, loginResponse)'>Login</button>
Weird, right? Not really. What had done was try to alter the input for the authentication request to match my html element inputs (see where my elements are labeled as username and password?) It didn't work, and I obviously just shelved that and moved on...and forgot. What I did was change "username" to "testuser". This matched the value I was trying to authenticate. Now, my baby is returning values on my testuser, and running like a dream.
Thanks for the tough love, stackoverflow.

How to use FLOT chart examples on web server?

I'm having a problem with my web server on raspberry pi. I have these two files( among others) : view_action.php and graph.html.
One of the function of the firs file is to to redirect the user to the file graph.html.
The graph.html is a copy of the realtime example of Flot chart. The files that i have to include on the code: jquery.js, jquery.flot.js and excanvas.min.js are on the same folder as the files above. So, the only thing changed on the graph.html is the path to these 3 files.
Here the graph.html:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Flot Examples: Real-time updates</title>
<link href="../examples.css" rel="stylesheet" type="text/css">
<!--[if lte IE 8]><script language="javascript" type="text/javascript" src="excanvas.min.js"></script><![endif]-->
<script language="javascript" type="text/javascript" src="jquery.js"></script>
<script language="javascript" type="text/javascript" src="jquery.flot.js"></script>
<script type="text/javascript">
$(function() {
// We use an inline data source in the example, usually data would
// be fetched from a server
var data = [],
totalPoints = 300;
function getRandomData() {
if (data.length > 0)
data = data.slice(1);
// Do a random walk
while (data.length < totalPoints) {
var prev = data.length > 0 ? data[data.length - 1] : 50,
y = prev + Math.random() * 10 - 5;
if (y < 0) {
y = 0;
} else if (y > 100) {
y = 100;
}
data.push(y);
}
// Zip the generated y values with the x values
var res = [];
for (var i = 0; i < data.length; ++i) {
res.push([i, data[i]])
}
return res;
}
// Set up the control widget
var updateInterval = 30;
$("#updateInterval").val(updateInterval).change(function () {
var v = $(this).val();
if (v && !isNaN(+v)) {
updateInterval = +v;
if (updateInterval < 1) {
updateInterval = 1;
} else if (updateInterval > 2000) {
updateInterval = 2000;
}
$(this).val("" + updateInterval);
}
});
var plot = $.plot("#placeholder", [ getRandomData() ], {
series: {
shadowSize: 0 // Drawing is faster without shadows
},
yaxis: {
min: 0,
max: 100
},
xaxis: {
show: false
}
});
function update() {
plot.setData([getRandomData()]);
// Since the axes don't change, we don't need to call plot.setupGrid()
plot.draw();
setTimeout(update, updateInterval);
}
update();
// Add the Flot version string to the footer
$("#footer").prepend("Flot " + $.plot.version + " – ");
});
</script>
</head>
<body>
<div id="header">
<h2>Real-time updates</h2>
</div>
<div id="content">
<div class="demo-container">
<div id="placeholder" class="demo-placeholder"></div>
</div>
<p>You can update a chart periodically to get a real-time effect by using a timer to insert the new data in the plot and redraw it.</p>
<p>Time between updates: <input id="updateInterval" type="text" value="" style="text-align: right; width:5em"> milliseconds</p>
</div>
<div id="footer">
Copyright © 2007 - 2014 IOLA and Ole Laursen
</div>
When the view_action.php redirect to graph.html it only appear the title and the info of the body. No graph. I think my webserver it isnt running javascript codes. What is the problem?
Thanks,
Ricardo
You need to specify a width and height for the placeholder div element (see the readme). In the original example this is done in the example.css. Check if the path to the CSS file is correct in your code (you have href="../examples.css").
Changing
<div id="placeholder" class="demo-placeholder"></div>
to
<div id="placeholder" class="demo-placeholder" style="width: 800px; height: 450px;"></div>
or similar should fix that issue if you don't want to use the CSS file.

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?

PHP Within Google Maps API V3

I'm having a puzzling little problem with the Google Maps API which has had me tearing my hair out. The following code
<?php
$anim='images/animation.gif';
session_start();
if ($_SESSION['anim']==1) {
$anim='images/transparent.png';
}
//Select database
require_once('../Connections/MySQL_extranet.php');
mysql_select_db($database_MySQL_extranet, $MySQL_extranet);
// Get the hid which is passed from previous page
if (isset($_REQUEST['hid'])) {
$hid=$_REQUEST['hid'];
}
//MySQL query to select location details
$query_location = "SELECT hotel, lat, lng, zoomair, sp_lat, sp_lng FROM ex_hotel WHERE hid = '$hid'";
$location = mysql_query($query_location, $MySQL_extranet) or die(mysql_error());
$row_location = mysql_fetch_assoc($location);
//Set the session variable to pass the hotel name
$_SESSION['hotel'] = $row_location['hotel'];
?>
<!DOCTYPE html>
<!--[if IE 7 ]> <html class="ie7"> <![endif]-->
<!--[if (gt IE 7)|!(IE)]><!--> <html> <!--<![endif]-->
<!--Dump the above when IE7 users go below 2% -->
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Little Hotels - Directions to <?php echo $row_location['hotel'];?></title>
<meta name="description" content="Little Hotels provides accurate directions to hotels from any starting point you choose.">
<meta name="keywords" content="hotel directions, google maps, Little Hotels, driving directions, directions to <?php echo $row_location['hotel'];?>">
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon" >
<?php
$full_url = (!empty($_SERVER['HTTPS'])) ? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] : "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
$canonical_url = strtok($full_url,'?');
echo '<link rel="canonical" href="' . $canonical_url . '" >';
?>
<link rel="stylesheet" href="css/littlehotels.css" type="text/css">
<style type="text/css">
#content{padding: 70px 5px 0; width: 100%;}
#mapcontainer{float:left; display:block;}
#mapCanvas {width: 600px; height: 400px;}
#markerStatus {height: 0px;}
#info {height: 0px;}
#infoPanel {margin-left: 620px; margin-right:10px; display:block;}
#infoPanel div {margin-bottom: 5px;}
</style>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder = new google.maps.Geocoder();
var lat = <?php echo $row_location['lat'];?>;
var lng = <?php echo $row_location['lng'];?>;
var latlng = new google.maps.LatLng(lat, lng);
function geocodePosition(pos) {
geocoder.geocode({
latLng: pos
}, function(responses) {
if (responses && responses.length > 0) {
updateMarkerAddress(responses[0].formatted_address);
} else {
updateMarkerAddress('Cannot determine address at this location.');
}
});
}
function updateMarkerStatus(str) {
document.getElementById('markerStatus').innerHTML = str;
}
function updateMarkerPosition(startpoint) {
document.getElementById('info').innerHTML = [
startpoint.lat(),
startpoint.lng()
].join(', ');
}
function nextPage() {
saddress = document.getElementById('info').innerHTML;
location='directions_detail.php?saddr='+saddress+'&daddr='+latlng;
}
function updateMarkerAddress(str) {
document.getElementById('address').innerHTML = str;
}
function initialize() {
var zoom = <?php echo $row_location['zoomair'];?>;
var sp_lat = <?php echo $row_location['sp_lat'];?>;
var sp_lng = <?php echo $row_location['sp_lng'];?>;
var startpoint = new google.maps.LatLng(sp_lat, sp_lng);
var map = new google.maps.Map(document.getElementById('mapCanvas'), {
zoom: zoom,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
streetViewControl: false,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL
}
});
var destimage = new google.maps.MarkerImage('/images/hotel_icon.gif',
new google.maps.Size(32, 37),
new google.maps.Point(0,0),
new google.maps.Point(16, 35));
var destshadow = new google.maps.MarkerImage('/images/hotelshadow.png',
new google.maps.Size(51, 37),
new google.maps.Point(0,0),
new google.maps.Point(16, 35));
var marker = new google.maps.Marker({
icon: destimage,
shadow: destshadow,
map: map,
position: latlng
});
var startimage = new google.maps.MarkerImage(
'/images/start_icon.png',
new google.maps.Size(59, 37),
new google.maps.Point(0,0),
new google.maps.Point(29, 35));
var marker = new google.maps.Marker({
position: startpoint,
title: 'If necessary, drag this to a different start point',
map: map,
draggable: true,
icon: startimage
});
// Update current position info.
updateMarkerPosition(startpoint);
geocodePosition(startpoint);
// Add dragging event listeners.
google.maps.event.addListener(marker, 'dragstart', function() {
updateMarkerAddress('Dragging...');
});
google.maps.event.addListener(marker, 'drag', function() {
updateMarkerStatus('Dragging...');
updateMarkerPosition(marker.getPosition());
});
google.maps.event.addListener(marker, 'dragend', function() {
updateMarkerStatus('Drag ended');
geocodePosition(marker.getPosition());
});
}
// Onload handler to fire off the app.
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body onload="initialize()">
<div id="wrapper">
<img src="images/transparent.png" width="266" height="122" border="0" alt="Little Hotels">
<img src="<?php echo $anim ?>" alt="Little Hotels logo" width="93" height="117" align="top">
<img src="images/header/directions.png" alt="Little Hotels" width="364" height="88">
<div id="container">
<?php include("includes/topnavbar.html"); ?>
<div id="breadcrumb">
<div class="bc-link" style="width:200px">Car Hire at competitive rates</div>
<div class="bc-link">Flights</div>
<div class="bc-link">Ferries</div>
<div class="bc-link">Airport Parking</div>
<div class="bc-link">Airport Hotels</div>
<div class="bc-link" style="width:200px">Travel Insurance</div>
<div class="bc-link" style="width:200px" align="right">News and Special Offers</div>
</div>
<div id="content">
<div id="mapcontainer">
<table border=1 bordercolor="#666666">
<tr>
<td>
<div id="mapCanvas"></div>
</td>
</tr>
</table>
</div>
<div id="infoPanel">
<h2>Driving Directions to <?php echo $row_location['hotel'];?> </h2>
<!-- Following two lines must be kept in, even though not visible. Also corresponding lines in Style -->
<div id="markerStatus" style="visibility:hidden;"><i>Click and drag the marker.</i></div>
<div id="info" style="visibility:hidden;"></div>
<b>Start Point:</b>
<div id="address"></div>
<br><b>Destination:</b><br>
<div><?php echo $row_location['hotel'];?></div>
<br>
To select a different starting point, just drag the start icon to the required location (zoom in if necessary for better precision).<br>
<br>
<button onclick="nextPage()">Get Directions</button>
<br>
<span class="verdana"><br>
</span>
</div>
</div>
</div>
</div>
</body>
</html>
<?php
$_SESSION['anim']=1;
?>
creates a satisfactory page (http://new.littlehotels.co.uk/directions_hotel.php?hid=colorado) but I want to add a couple of refinements. These changes need me to create a javascript variable from a piece of MySQL data.
Therefore I want to create a line something like this:
var hotelname = <?php echo $row_location['hotel'];?>;
That shouldn't be too hard as I already have several similar lines in the working code. However, this new line breaks the page every time, no matter what variations I try. When I add that line in, the page displays but without the map and without the name of the Start Point on the righthand side.
Is it me?????????????
I am guessing you are outputting a string from $row_location['hotel'] in that case you need to wrap in quotes to tell javascript its not a variable but a string value.
thus:
var hotelname = "<?php echo $row_location['hotel'];?>";
To check if the above hypothesis is true check your console and you will see the following error:
ReferenceError: <value returned by $raw_location['hotel']> is not defined
Like this one can pass variables to JS and it prevents the PHP interpreter from complaining about any missing indexes, just in case (it depends how error reporting is set in php.ini), for example:
var hotelname = "<?php echo(isset($row_location['hotel']) ? $row_location['hotel'] :''); ?>";
console.info(hotelname);
The surrounding quotes are the difference, like this $row_location['hotel'] gets casted to string in JavaScript.
... what does this code return, you even get any result?
while ($row_location = mysql_fetch_assoc($location)) {
echo '<pre>'.print_r($row_location,true).'</pre>';
}

Ajax Value Not Transmitting To PHP

I have this Star Rating system right. When you click on a star it should pass a value into the function. Then using AJAX it posts it to an external PHP file. The only problem is that when it gets to the PHP file it comes as null or no value.
I will try to echo the $_POST['vote'] variable in an alert box using AJAX and it is blank so it doesn't come back as "NULL" or "0" it's just nothing. I'm not sure where I'm losing the value because I can track it all the way to the send() function. Anyone see a problem?
HTML:
<style type="text/css">
#container{margin: 10px auto;width: 500px;height: 300px;background-color: gray;}
#starContainer{padding-top:20px;margin:0 auto;width:150px;}
.box{height:28px;width:30px;float:left;position:relative;z-index:5;cursor:pointer;}
.star{background-image:url('emptyStar.png');background-repeat:no-repeat;}
.starHover{background-image:url('goldStar.png');background-repeat:no-repeat;}
#voteBar{float:left;height:28px;background-color:#dbd923;position:relative;top:-28px;z-index:1;}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.box').hover(
// Handles the mouseover
function() {
$(this).prevAll().andSelf().addClass('starHover');
},
// Handles the mouseout
function() {
$(this).prevAll().andSelf().removeClass('starHover');
}
);
});
function Cast(vote)
{
if(window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
alert(xmlhttp.responseText);
var json = JSON.parse(xmlhttp.responseText);
}
}
xmlhttp.open("POST", "process.php", true);
xmlhttp.send('vote=' + vote);
}
</script>
</head>
<body>
<div id="container">
<center>
<div id="starContainer">
<div class="box star" onclick="Cast(1)"></div>
<div class="box star" onclick="Cast(2)"></div>
<div class="box star" onclick="Cast(3)"></div>
<div class="box star" onclick="Cast(4)"></div>
<div class="box star" onclick="Cast(5)"></div>
<div id="voteBar"></div>
</div>
</center>
</div>
</body>
</html>
PHP:
<?php
$vote = $_POST['vote'];
$totalVoteValue = 0;
$amtVotes = 1;
$width = (($totalVoteValue + (($vote - $totalVoteValue) / $amtVotes)) / 5) * 150;
echo $width;
?>
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
adding this may help (before send after open)
You are already using jquery (a very very very old version if i may say..), why not use it's built in ajax handler?
http://api.jquery.com/jQuery.post/
$.post('process.php', {vote: vote}, function(data) {
$('.result').html(data);
});

Categories