Problems using a variable as array key in html5 script - php

I'm currently trying to start using php for some procedural generations and wanted to display my functions with a bar chart:
<?php
$seed = 58521672597513854781922;
global $randomArray;
for ($i=-1000; $i<1001; $i++) {
$temp = $seed/($i+0.1)^0.5;
$tempRes = $temp.'';
$randomArray[$i] = $tempRes[5];
}
?>
<div>
<canvas id="c3" width="600" height = "200" style="border:solid 1px #000000;"></canvas>
<div>
<button onclick="Vertical_line();return true;">draw array</button>
</div>
</div>
<script>
var c3 = document.getElementById("c3");
var c3_context = c3.getContext("2d");
function Vertical_line() {
<?php
for($j=0;$j<sizeof($randomArray);$j++){
$height = 100 - 10*$randomArray[$j];
?>
c3_context.moveTo(<?php echo 300+$j;?>, 200);
c3_context.lineTo(<?php echo 300+$j;?>, <?php echo $height;?>);
c3_context.strokeStyle = "red";
c3_context.stroke();
<?php }?>
}
</script>
i don't understand why the variable $j as key reference in my array doesnt work. If i replace it by numbers manually to draw a single entry of my array it works without problems, if i set a variable as absolute number and use it as key it works too, just when i use a variable that changes its value it wont display anything.
Help is appreciated :)

Ok, thanks for helping out, found the error, was a problem with the negative key for my array, simple oversight :), thanks # u_mulder for reminding me to look at the source code, i had to scroll quite a while to see the error ^^

You cannot run Php inside ofJavascript, Php always runs as soon as the page loads, you want to create a JS function to do the job u wish

Related

Jquery if else colour shuffle (passing a variable)

This is regarding this question i asked on this link:PHP CSS Colour Shuffle array?
I have changed and added more code and have a different question hence why i've opened a new thread.
I am using php and jQuery to shuffle colours every time the page is refreshed. At the moment this works fine. But i have a jQuery function where i grab some elements and on a hoverstate show the shuffle colour. Now this does work but it's showing css standard default red,blue,green ect and not even displaying colours for the orange. I have been advised to create a variable and then create an if function and pass the variable through the hover function. Below is what i have so far, im a novice user at jQuery so i am unsure of where i am going wrong or where to go next, can someone guide me to why this is broken? My firebug shows no errors and i think im nearly there! Thanks.
PHP Shuffle colours:
<?php
$colours = array('red', 'green', 'blue', 'black');
$blog = $colours[array_rand($colours, 1)];
?>
<body id="<?php echo $blog; ?>">
In my css wherever i wanted to show the shuffle colour #green, #red is before the actuallid,class or element and it works! Just the hover states now where i have this jQuery..
// colour rollover navigation
var colours = "<?php echo $colours; ?>";
if(colours == "red"){
colours = "#600";
}
else if(colours == "green"){
colours = "#363";
}
else if(colours == "blue"){
colours = "#369";
}
else if(colours == "black"){
colours = "#000";
}
//example of some elements that would use the hover effect
$("#footer .address #breadcrumbs a").hover(function() {
$(this).stop().animate({ 'color': colours }, 300);
},function() {
$(this).stop().animate({ 'color': "#fff" }, 300);
});
Am i missing some lines in the if else or passing the variable through wrong? Thanks!
I presume the JS is in script tags on the page.
You can't just echo out an array. I'm guessing you meant to echo $blog. That should pass a single color as string data to be picked up by your if () {} else {} statements (should be switch () { case } really).
Ok i have it working.
I did some things so not sure exactly what totally fixed it:
-Clear Cache (Google Chrome is a pain for this)
-Changed the variable from Colours to color (both in php and JS)
-When defining the variable in JS i echoed $blog instead of $colour.
I get no errors when this works as well.
Thanks!

How can I display a random image from a php array using jQuery?

I have been trying to create a random picture display animation, in the style of a slot machine wheel. The user clicks 'spin' and a gif image appears, giving the effect of a slot wheel spinning. When the wheel stops, the spinning effect gif image is replaced by a random member's picture. However, the random member's picture is not appearing. In firebug, I can see that the array is being populated correctly, and the member pictures (with correct url) are all present.
The issue seems to be that the jQuery script is not prepending the tag to the in which the image is to appear, and I cannot work out why.
The PHP to gather the information for the array is here:
$q = "SELECT id, username FROM members WHERE my_sex =:req_sex";
$stmt = $dbo->prepare($q);
$stmt->execute(array(":req_sex" => $req_sex));
while($r = $stmt->fetch()) {
$m_id = $r['id'];
$m_name = $r['username'];
$m_pic .= '"members/'.$m_id.'/minis/resized_image_'.$m_id.'_0.jpg", ';
}
$m_pic = rtrim($m_pic, ', ');
and the jQuery which I am sure is incorrect somewhere is here:
$(document).ready(function(){
images = new Array(<?php echo $m_pic; ?>);
var length = images.length;
var which = Math.round(Math.random()*(length-1));
$('<img src="'+images[which]+'" alt="" class="randomMember"/>').prependTo('div#wheel');
};
I have been playing around with this and tried various methods, and using firebug to investigate, the best I have managed to achieve is to get the following line showing in the html.
<img class="randomMember" alt="" src="" />
I cannot remember how I did this, but I think it was using document.write and not wrapping it in a function. I have only been using javascript and jQuery for a week or so, and despite a whole lot of Googling and reading up, I cannot see why this isn't working out. Thanks in advance!
EDIT: the html is as follows:
<div class="hidden_sidebox">
<div id="chat_view">
<div id="wheel">
<img src="members/0/default_pic.jpg" alt="" class="preSpin" />
<img src="images/randomChatWheel.gif" alt="" class="spinAnimation" style="top: -220px;" />
</div>
//here is where the problem jQuery script is...I think this is the correct place for it, as it will prependTo the previous div element (which I have explicitly specified anyway, just in case)
<div id="btnPanel">
<div id="chatButton">CHAT</div>
<div id="spinButton">SPIN</div>
</div>
<div id="chatSplash"></div>
</div>
</div>
and the function for the wheel spin (which works perfectly apart from the final image failing to display) is here:
$(document).ready(function() {
$("div#chatSplash").click(function () {
$("div#chatSplash").slideUp("fast");
$('img.randomMember').hide();
$('img.spinAnimation').hide();
$('div#spinButton').removeClass('ButtonDisabled');
$('div#chatButton').removeClass('ButtonDisabled');
});
$("div#spinButton").click(function () {
$("img.preSpin").hide();
$("img.spinAnimation").show();
$('div#spinButton').addClass('ButtonDisabled');
$('div#chatButton').addClass('ButtonDisabled');
setTimeout(function(){$("img.spinAnimation").hide();
$('img.randomMember').show();
$('div#spinButton').removeClass('ButtonDisabled');
$('div#chatButton').removeClass('ButtonDisabled');
}, 2500);
});
});
There is a simple error here, you're not closing parentheses. You have:
$(document).ready(function(){ . . .};
Which should be
$(document).ready(function(){ . . .});
Try this in PHP:
$pictures = array();
while($r = $stmt->fetch()) {
$pictures[] = sprintf('members/%d/minis/resized_image_%d_0.jpg', $r['id'], $r['id']);
}
and then in JS:
images = <?php json_encode($pictures); ?>;

Concatenation of PHP echo with div tag containing php

I am using Javascript to hide / show a blog-post stored in a mysql table. The script for doing this is:
<script type="text/javascript">
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className = (item.className == 'hidden') ? 'unhidden' : 'hidden';
}
}
</script>
This links to some css styling:
.hidden {
display: none;}
.unhidden {
display: inline;}
I am calling the script via a href styles as a button:
<a class=button href="javascript:unhide('first_post');">More</a>
As for the content I originally tried the following to initially show a small section of text, then the rest after the link is clicked:
<?php $var = mysql_result($result,0,"post_text"); ?>
<?php echo substr($var, 0, 400); ?>
<div id="first_post" class = "hidden">
<?php echo substr($var, 400, 5000)?>
</div>
However where the two sets of sub-strings join there is a space. For example if the first sub-string ends in "the tree's hav" and the second sub-string starts "e eyes you know" the concatenation results in "the trees hav e eyes you know"
Can anyone help me with this problem?
Remove newlines between <?php ?> and <div> tags - this should help you get rid of spaces.
<?php echo substr($var, 0, 400); ?><div id="first_post" class = "hidden"><?php echo substr($var, 400, 5000)?></div>
I think what you're looking for is you want to truncate string from the end of the word rather than giving link somewhere in between. That's what I see as permanent solution...
When I googled up expecting that PHP would have something available out of the box found following 2 article which might help you.
http://css-tricks.com/snippets/php/truncate-string-by-words/
How to Truncate a string in PHP to the word closest to a certain number of characters?
They are not exactly what you're looking for but they can be of great help if you take inspiration from the concepts.

AJAX is changing the content of file_get_contents

I am using AJAX to load content into a placeholder, the PHP code uses file_get_contents to get the page I want, then gives it back to the AJAX response which puts it into my placeholder. The problem I am having is that the content that is being grabbed is actually being altered, like html tags are being put where they didn't exist.. Here is the code:
function getPreview() {
var indexe = ajax.length;
ajax[indexe] = new sack();
var form = document.getElementById('form');
ajax[indexe].setVar("prevsub", form.ebay_preview_submit.value);
ajax[indexe].method = 'POST';
ajax[indexe].requestFile = "../admin/model/catalog/getEbay.php";
ajax[indexe].onCompletion = function(){ createPreview(indexe) };
ajax[indexe].runAJAX();
}
function createPreview(indexe) {
var obj = document.getElementById('preview_ph');
obj.innerHTML = ajax[indexe].response;
}
so everything gets put inside of this placeholder:
<div id="preview_ph" ></div>
Here is the PHP that does the grabbing:
if(isset($_POST['prevsub'])){
$template_viewer = http://localhost:8888/admin/view/template/ebay/template_viewer.php';
$file_got = file_get_contents($template_viewer);
echo $file_got;
}
And here is a snippet of what It is supposed to be vs what it is adding in there...
Supposed to be:
Sign up for Newsletter</a> </div></td>
But instead it is altered:
Sign up for Newsletter</a></td></tr>
Another, supposed to be:
bidding! </span>
</div>
</td></tr>
But gets altered to:
bidding! </span>
</div>
</td></tbody>
It alters the content 7 total times from the page its grabbing... Any explanation for this?
The page, opens up in a browser perfectly, it is seriously getting altered by AJAX or file_get_contents in some way, and I am completely baffled...
Thanks for your help!
To me, this looks like the browser is sanitizing the HTML at the time of the .innerHTML operation. That is an act of self-defense, because the HTML you output is clearly not valid, is it?
The end result would look like
<div id="preview_ph" >
Sign up for Newsletter
</a> <--- broken
</div> <--- broken
</td> <--- broken
</div>
that code would break the DOM, so the browser has to try and fix it as best as it can.
Why are you outputting those closing tags through AJAX?

PHP: Read a variable at top present at bottom

Is there a way to read a variable at top which is defined some where at the bottom.
Here is an example of such situation:
<!--this image is somewhere on top of the page-->
<img src="/<?php print logoPath(); ?>" border="0" />
// this code is somewhere on bottom of the page
$logo_query = "select logo_path from table where id = $row->user_id";
$res_logo = mysql_query($logo_query) or die(mysql_error());
$row_logo = mysql_fetch_object($res_logo);
$logo_path = $row_logo->logo_path;
function logoPath()
{
global $logo_path;
return $logo_path;
}
I tried to use that function to return value but even that doesn't seem to work.
Any solution?
Thanks
No, in PHP all instructions are executed sequentially so you cannot read a variable that hasn't yet been defined. You must move the code that sets the value of $logo_path above the place where you call the logoPath() function.
Alternatively you could put the sql code in the logoPath() function, which would allow you to have the function that returns the logo path below the place where you call the function.
No, but there is a way to do it with jquery:
<img id="image" src="" border="0" />
// this code is somewhere on bottom of the page
$logo_query = "select logo_path from table where id = $row->user_id";
$res_logo = mysql_query($logo_query) or die(mysql_error());
$row_logo = mysql_fetch_object($res_logo);
$logo_path = $row_logo->logo_path;
function logoPath()
{
global $logo_path;
echo "<script type='text/javascript'> $('#image').src('".$logo_path."');</script>";
}
It's kinda stupid, but it should work.
What you can do is use a Div tag and make the position on top of the page. This way the code can be executed at the button but the results will show on top.

Categories