I've got the following code, and the stuff before the javascript echos and the stuff after the javascript includes, but the javascript won't echo :/
$currentPage = $_POST["current_page"];
$nextPage = 1 + $currentPage;
$count = $_POST["cum_count"];
$total = $_POST["cum_total"];
$progress = $_POST["cum_progress"];
echo $currentPage . $nextPage;
# number of questions less 1
$numQs[2]=6;
$numQs[3]=3;
$numQs[4]=5;
$numQs[5]=34;
$numQs[6]=17;
$numQs[7]=43;
$falses = array('false');
for ($i=0; $i < $numQs[$nextPage]; $i++) {
array_push($falses,', false');
}
# the js is how the survey keeps track of where it is
echo "<script type='text/javascript'>\n
var c_name = 'whbssurvey';\n
var c_value = '$nextPage';\n
document.cookie=c_name + '=' + c_value;\n
// set survey info\n
var count = $count;\n
var total = $total;\n
var progress = $progress;\n
var qArray = [$falses];\n
</script>";
include("$nextPage.php");
P.S. In case anyone is thinking cum_count is something dirty, it's short for cumulative.
Are you sure it's not echoing? It's being done BEFORE you do your include. If that include is a complete html page, the JS would be echoed BEFORE the opening <html> tag (which makes for an invalid page).
As well, for dumping out multiline text like that, you should either drop out of PHP mode so it's just plaintext that'll get echoed out automatically, or use a HEREDOC. Since you're inserting a couple PHP vars into that output, the HEREDOC would probably be preferable.
Try echoing without the <script> and </script> tags. It's possible that it is being printed but your browser isn't rendering it for some reason. If you get all the code spewed on the page, it worked.
try:
echo "<script type='text/javascript'>\n" .
"var c_name = 'whbssurvey';\n" .
"var c_value = '$nextPage';\n" .
"document.cookie=c_name + '=' + c_value;\n" .
"// set survey info\n" .
"var count = $count;\n" .
"var total = $total;\n" .
"var progress = $progress;\n" .
"var qArray = [$falses];\n" .
"</script>";
Related
ok so I have this in my HTML code:
<script type="text/javascript" src="load2.php"> </script>
I saw somewhere you could call a php file like that and the javascript contained in it will be rendered on the page once echoed.
So in my PHP file i have this:
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$storeArray[] = $row['DayNum']; }
$length = count($storeArray);
I connected to my database and stuff and pulled those records and stored them in an array. Now my problem is alerting them using js. This is what I have:
echo " function test() {
for(var i = 0; i<$length; i++){
alert($storeArray[i]);
}
}
";
The test() function is being onloaded in my HTML page, but for nothing the values in the array won't alert. Any help please?
echo " function test() {
for(var i = 0; i<$length; i++){
alert($storeArray[i]);
}
}
";
This code is literally writing what you have written above. It's not completely clear, but I believe your intent is to loop over the contents of your database data, and alert that to the browser with alert() function.
You can achieve this in a couple of ways.
Write multiple alert statements
echo "function test() {"; //Outputting Javascript code.
for($i = 0; $i<$length; $i++){ //Back in PHP mode - notice how we aren't inside of a string.
$value = $storeArray[$i];
echo "alert($value)"; //Outputting Javascript code again.
}
echo "}"; //Outputting Javascript code to close your javascript "test()" function.
Write a Javascript array, then loop over it in Javascript
echo "function test() {";
echo " var storeArray = ['" . implode("','", $storeArray) . "'];";
echo " for (var i = 0; i < storeArray.length; i++) {";
echo " alert(storeArray[i]);";
echo " };";
echo "}";
Finally, you could use AJAX and JSON to load the data, rather than outputting a JS file from PHP. That is an entirely different topic, though, and you should search StackOverflow for more examples as there are numerous questions and answers involving it.
Unless your array contains only number, you probably have JS error. You should put your $storeArray[i] in quotes in the alert function so it considered as a string in js.
alert('$storeArray[i]');
Once printed out, the JS will look something like this
alert('foo');
alert('bar');
Whereas with your code, it would've printed it like this
alert(foo);
alert(bar);
in your php file include load2.php
header("Content-Type: text/javascript");
in the in the top. so your browser get what it wants.
$i=0;
$storeArray = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$storeArray[$i] = $row['DayNum'];
$i++;
}
echo "var arr = Array();";
echo "function test() {";
foreach ($storeArray as $key=>$item) {
echo "arr[".$key."] = ".$item.";";
}
echo "}";
echo "alert(arr);";
actually you can comment out the two echos containing the <script></script> part when including the file as <script src="load2.php" type="text/javascript" ...
I must be tired or something because i am unable to get this line of code to work:
var all = color.val('all');
$('#cssColor" + <?php echo $page ?> + "', parent.document).attr("background-color", all.hex);
I even have a textbox with the page value as well and i try:
var all = color.val('all');
$('#cssColor" + $('#txtPageValue').val() + "', parent.document).attr("background-color", all.hex);
I can not seem to send the page value!
Try to change this one:
$('#cssColor" + <?php echo $page ?> + "',
to:
$('#cssColor<?php echo $page ?>',
And also, for the second one:
$('#cssColor" + $('#txtPageValue').val() + "',
to:
$('#cssColor' + $('#txtPageValue').val(),
I am not sure how you are assigning the all variable, but assuming it is getting assigned correctly, you could rewrite your code something like this to get the value to appear in the right place in your javascript:
<?php echo "<script type='text/javascript'>
//code somewhere in here should define the color object
var all = color.val('all')
$('#cssColor" . $page . "', parent.document).attr('background-color', all.hex);
</script>"; ?>
This writes the javascript to the document, without breaking the echo function in the middle.
Or, you could do this:
var all = color.val('all');
$('#cssColor'+<?php echo $page; ?>, parent.document).attr('background-color', all.hex);
I was cleaning up my code so that it was more uniform. I placed a couple of javascript functions in the echo command. I was surprised to find that after I had done that, the functions no longer worked. There were no errors that I received, it was only when I went through the page that I noticed that my functions were no longer working. I'm still in my javascript infancy, so I'm not sure if this is a common error or not, but I couldn't find anything related to it.
I troubleshot it down to the third line by taking away all echoes and slowly adding in more until the problem resurfaced. So, I'm not sure what I'm doing wrong.
The purpose of the functions is to make a grey overlay over everything, then a small confirmation box pops-up asking if you want to proceed with the task.
echo '<script type="text/javascript">';
echo 'function showPopUp(el) {';
echo 'var cvr = document.getElementById("cover")';
echo 'var dlg = document.getElementById(el)';
echo 'cvr.style.display = "block"';
echo 'dlg.style.display = "block"';
echo 'if (document.body.style.overflow = "hidden") {';
echo 'cvr.style.width = "100%"';
echo 'cvr.style.height = "100%"';
echo '}';
echo '}';
echo 'function closePopUp(el) {';
echo 'var cvr = document.getElementById("cover")';
echo 'var dlg = document.getElementById(el)';
echo 'cvr.style.display = "none"';
echo 'dlg.style.display = "none"';
echo 'document.body.style.overflowY = ""';
echo '}';
echo '</script>';
Extra information: The entire page is within the php tags, I found another unrelated function that is behaving the same way. The only way that the two are similar is that they both use the var command and they are all functions. Could this be the source?
OH. MY. GOD.
Is the following "allowed" by your company's standards?
echo <<<HTML
<script type="text/javascript">
function showPopUp(el) {
var cvr = document.getElementById("cover")
var dlg = document.getElementById(el)
cvr.style.display = "block"
dlg.style.display = "block"
if (document.body.style.overflow = "hidden") {
cvr.style.width = "100%"
cvr.style.height = "100%"
}
}
function closePopUp(el) {
var cvr = document.getElementById("cover")
var dlg = document.getElementById(el)
cvr.style.display = "none"
dlg.style.display = "none"
document.body.style.overflowY = ""
}
</script>
HTML;
Or just:
<?php
// some PHP code
?>
<script type="text/javascript">
function showPopUp(el) {
var cvr = document.getElementById("cover")
var dlg = document.getElementById(el)
cvr.style.display = "block"
dlg.style.display = "block"
if (document.body.style.overflow = "hidden") {
cvr.style.width = "100%"
cvr.style.height = "100%"
}
}
function closePopUp(el) {
var cvr = document.getElementById("cover")
var dlg = document.getElementById(el)
cvr.style.display = "none"
dlg.style.display = "none"
document.body.style.overflowY = ""
}
</script>
<?php
//some MORE PHP code...
Because if it is, you would have noticed you're using an assignment in an if statement:
if (document.body.style.overflow = "hidden")
should be
if (document.body.style.overflow == "hidden")
Note: The way you're doing it prints the entire javascript block on a single line. If you must print it out this way, you have to either add semicolons or newline characters to each string you print, where necessary.
The generated JavaScript is syntactically incorrect - the lines are not terminated neither with semicolons, nor newlines. Replace with
echo 'var cvr = document.getElementById("cover");';
and so forth.
Also, I vaguely recall that there needs to be a newline after the end of the <script> element. In PHP, echo does not produce a newline at the end, and strings in single quotes don't allow for escape sequences like \n. So you need to do:
echo '<script type="text/javascript">'."\n";
The problem with your echo statements, is missing spaces / semicolons:
echo 'var cvr = document.getElementById("cover")';
echo 'var dlg = document.getElementById(el)';
echo 'cvr.style.display = "block"';
shows up in html as:
var cvr = document.getElementById("cover")var dlg = document.getElementById(el)cvr.style.display = "block"
etc.
and that doesn't make sense in javascript.
I am trying to get some information from our database and then use it in javascript/JQuery and I think I might be doing something wrong with the scope of the coding.
Here is the current segment of code on my phtml page (magento)
<script type="text/javascript">
<?php
echo 'var $image-paths = new Array();';
for ($i = 0; $i < count ($_child_products); $i++)
{
echo '$image-paths[';
echo $i;
echo '] = ';
echo $this->helper('catalog/image')->init($_child_products[$i], 'image');
echo ';';
}
?>
document.getElementById('main-image').href = $image-paths[1];
</script>
The bottom getElementById is just for testing to see if it really grabbed that image path. So far the php stuff is working and echo'ing the correct links. However, is simply echo'ing them not enough; does it actually register it into the javascript code?
Here is what my source code looks like on my server:
<script type="text/javascript">
var $image-paths = new Array();
$image-paths[0] = http://staging.greencupboards.com/media/catalog/product/cache/1/image/9df78eab33525d08d6e5f b8d27136e95/feeds/MrsMeyers/MRM-64565-a.jpg;
$image-paths[1] = http://staging.greencupboards.com/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/feeds/MrsMeyers/MRM-64566-a.jpg;
$image-paths[2] = http://staging.greencupboards.com/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/feeds/MrsMeyers/MRM-64568-a.jpg;
$image-paths[3] = http://staging.greencupboards.com/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/feeds/MrsMeyers/MRM-D43114-a.jpg;
document.getElementById('main-image').href = $image-paths[1];
</script>
But the image link does not change to image-path[1]. Any ideas?
Thanks in advance!
$image-paths[0] = http://staging.greencupboards.com/media/catalog/product/cache/1/image/9df78eab33525d08d6e5f b8d27136e95/feeds/MrsMeyers/MRM-64565-a.jpg;
^-- no quote here, or at the end of the string
You're producing invalid javascript. Pop up your javascript console (shift-ctrl-J in chrome/firefox) and you'll see the error.
Producing javascript dynamically is problematic. Anytime you insert something from a PHP variable/function, you should run that through json_encode(), which guarantees you get valid javascript:
echo json_encode($this->helper('catalog/image')->init($_child_products[$i], 'image'));
Or better yet, change the code to:
$links = array();
for ($i = 0; $i < count ($_child_products); $i++)
$links[] = $this->helper('catalog/image')->init($_child_products[$i], 'image');
}
echo '$image-paths = ', json_encode($links);
<script type="text/javascript">
<?php
echo 'var $image_paths = new Array();';
for ($i = 0; $i < count ($_child_products); $i++)
{
echo '$image_paths[';
echo $i;
echo '] = "'; // Here the starting of quotes.
echo $this->helper('catalog/image')->init($_child_products[$i], 'image');
echo '";'; // Here the ending of quotes.
}
?>
document.getElementById('main-image').href = $image_paths[1];
</script>
This should work now. Hope it helps.
I have a php loop that is echoing out geolocation values. How can I get it to write those values to a javascript array, so I can then use them to plot points on an HTML5 canvas?
The php loop is as follows
<ul id = "geo-list">
<?php foreach($data as $phrase) { ?>
<li><?php
if ($phrase->geo != false) {
echo " | From (";
echo $phrase->geo->coordinates[0];
echo ",";
echo $phrase->geo->coordinates[1];
echo ")";
} else {
echo " | No Location Data";
}
?>
</li>
<?php } ?>
</ul>
Did you try
var myJavascriptData = <?= json_encode($php_data) ?>;
You might want to take advantage of the JSON library for PHP.
The cleanest way to pass data to a browser's javascript program is to put it into a "hidden" html table.
The html should look something like
echo "\n<TABLE style='display: none;' id='DATTAB' >" ;
get_rows();
while ($cf = next_row()) {
echo "\n <TR>";
echo "\n<TD>" . $cf['KEY'] . "</TD>";
echo "\n<TD>" . $cf['COL1'] . "</TD>";
echo "\n<TD>" . $cf['COL2'] . "</TD>";
echo " </TR>";
}
echo "\n</TABLE>";
This table is then easily accessable from your javascript:-
var dtab = document.getElementById("DATATAB");
var rows = dtab.getElementsByTagName("tr");
for (var r = 0; r < rows.length ; r++) {
row = rows[r];
item_key = row.cells[0].innerHTML;
item_col1 = row.cells[1].innerHTML;
item_col2 = row.cells[2].innerHTML;
// do your thing here ......
}
Alternatively you could look at using the AJAX libraries like prototype or dojo
which have the all javascript components for accessing data from a "REST" type service.
You then need to write a separate service which gets the XML or JSON required for your page.
My suggestion is to dump a script block to the output and set them in a variable there.
The array definition will have to actually be in the javascript code that gets output to the page.
e.g., you'll need an output of something like:
<script type="text/javascript">
var coords = new Array(2);
coords[0] = new Array(2);
coords[0][0] = 123.45;
coords[0][1] = 987.65;
coords[1] = new Array(2);
coords[1][0] = 234.56;
coords[1][1] = 876.54;
</script>
There are more efficient ways to create this array statically, but this is just an example.
A more efficient way (in terms of code) would be to build up a string that defined the literal array, then dump out a javascript definition. The output would be something like:
<script type="text/javascript">
var coords = [[123.45,987.65],[234.56,876.54]];
</script>
so in your loop within php, you'd build up a string which would ultimately contain var coords = [[123.45,987.65],[234.56,876.54]]. Outside your loop, you wrap it in the script blocks and output it to the page.