PDA

View Full Version : PHP Not Working When Inside a Javascript <script> Tag



Robert_B
04-25-2016, 09:39 PM
Hi. I'm brand new to PHP and am trying to see what it can do. I put a small page together that sort of looks like this:


<?php
echo '
-- some javascript code --
</script>
<script>
';
$file = fopen("Awards.csv","r");
$x = fgetcsv($file);
print_r ($x);
echo '
</script>
-- some more javascript code

-- some html code --
';
?>


Here's the thing. The PHP code only seems to work if I put it outside of the <script></script> tags. It's probably something I'm doing wrong, but all the reading I've done on PHP says it should work.

What I'm really trying to do is to get the contents of the file into a javascript array. That's probably something for a different thread.

If someone could tell me what I'm doing wrong and why the PHP code won't work, I'd appreciate it.

Thanks.

jscheuer1
04-25-2016, 10:35 PM
Works here. If I run it on a csv file then use the browser's "view source", this is what I see:


-- some javascript code --
</script>
<script>
Array
(
[0] => Date
[1] => Time
[2] => Time Zone
[3] => Name
[4] => Type
[5] => Status
[6] => Gross
[7] => Fee
[8] => Net
[9] => Note
[10] => From Email Address
[11] => To Email Address
[12] => Transaction ID
[13] => Item Title
[14] => Item ID
[15] => Reference Txn ID
[16] => Receipt ID
[17] => Balance
[18] =>
)

</script>
-- some more javascript code

-- some html code --


What were you expecting? Keep in mind that (just like with a regular HTML page) both the opening and closing tags and anything between the javascript <script></script> tags will not be seen unless one uses "view source". Also, your second -- some more javascript code is itself outside those tags, so couldn't really be script code. The 'code' at the top could be, but has no opening <script> tag we can see, so it might not really be javascript either, and without one, is not.

Robert_B
04-26-2016, 07:10 PM
I'm going to try this again.

Hi John.

That's exactly what I expect.

Sorry about the script tags, they really are there in my file. Didn't mean to confuse the issue.

I assume the "view source" is a PHP function, but the only thing I could find was "show_source". I tried it, but it still didn't display. I though, maybe, it was because I has so much other code between the php tags, so I just put them around the php code. It now looks like this:



<script>
function myFunc( )
{
var xx = new Array()
xx[0,0] = "this is a test"

<?php
$file = fopen("Awards.csv","r");
$x = fgetcsv($file);
show_source ($x);
?>
xx = <?PHP show_source(fgetcsv($file)); ?>;
alert (xx);
}
</script>


Neither the show_source or alert displays the file.
The function is called using an onblur event. Don't know if that makes a difference, but I thought I'd mention it.

jscheuer1
04-26-2016, 07:47 PM
OK, about your posts not showing up, I know - it's frustrating. They got automatically moderated. They're still there, you just cant see them unless I or another mod or the admin approves them. In the future just be patient or perhaps post one short response like the ones you did mentioning that the post didn't show up. I'm only going to approve one now though, and maybe get rid of the "complaints", justified as they are, because they don't add to the thread.

On to the real stuff. No, view source is available in all modern browsers. They make it increasingly hard to find though. Which browsers are you using? ctrl-u often will let you see the served source code.

And, since I'm having to explain that, I'm assuming you don't get that, even if your PHP code 'works', in so far as appearing inside <script></script> tags, you will never see it on the page if it's viewed in the normal manner in a browser because it's javascript code - javascript code is never seen in the normal view of a page.

And that's why you really are going to have to get this idea of "view source", as it's the best way to see javascript code in the browser - regardless of whether or not it was produced by PHP or just hard coded. You can also use a browser's developers' console (if available) to view it, but that's not always the best way.

So anyways if you are using latest Firefox, Opera, Chrome, IE11, probably others, and you are viewing your page, hold down the CTRL key and hit the U key, then release both. You should then see the raw code the browser received from the server when it requested the page. That should clear up a lot.

Robert_B
04-26-2016, 09:20 PM
Hi John.

First, let me apologize for my impatience, and thank you for removing the complaints my multiple replies created.

Now, as you said, On to the real stuff. I'm using either Firefox ver. 45 or IE 11. Situation is the same in both. When I pull up the page (on the server), and hit ctrl-U, the display doesn't show the php code at all and doesn't show the output of the file. I tested it both before and after invoking the script function.

BTW, thanks for clearing up the view source thing. Sometimes I can be a bit dense.

Maybe we should go right to my ultimate goal of getting the file output into an array that JavaScript CAN operate on.

Never thought this would be this difficult.

p.s. I'm going to wait on this reply until it shows up. :p

jscheuer1
04-27-2016, 07:03 AM
Maybe we should go right to my ultimate goal of getting the file output into an array that JavaScript CAN operate on.

I was thinking of mentioning that. However, and we can try/do that, in the long run you will be better off seeing how this stuff evolves yourself, so you can trouble shoot it if and when the need arises, or at least get a fuller sense of it. We can accomplish both things. To that end, first let's make doubly sure you get the CTRL-U idea. Here's my current test page's raw code (php_help.php):


<?php
echo '
-- some javascript code --
</script>
<script>
';
$file = fopen("Awards.csv","r");
$x = fgetcsv($file, 1000, ',');
print_r ($x);
fclose($file);
echo '
</script>
-- some more javascript code

-- some html code --
';
?>

There's no way you can ever see that unless you invent it (which you mostly or entirely did in this case), or someone else shows you what their server side code is/gives you access to their server so you can download/view the raw file. This is what it looks like if I navigate to it:


-- some javascript code -- -- some more javascript code -- some html code --

Now I will show you what it looks like (here) in view source (ctrl-u) mode:




-- some javascript code --
</script>
<script>
Array
(
[0] => Date
[1] => Time
[2] => Time Zone
[3] => Name
[4] => Type
[5] => Status
[6] => Gross
[7] => Fee
[8] => Net
[9] => Note
[10] => From Email Address
[11] => To Email Address
[12] => Transaction ID
[13] => Item Title
[14] => Item ID
[15] => Option 1 Name
[16] => Option 1 Value
[17] => Option 2 Name
[18] => Option 2 Value
[19] => Reference Txn ID
[20] => Custom Number
[21] => Receipt ID
[22] => Balance
[23] =>
)

</script>
-- some more javascript code

-- some html code --


Now I'm going to put it somewhere you can look at it:

http://john.dynamicdrive.com/demos/tidbits/vshelp/php_help.php

This, by the way is the Awards.csv file I'm using (just one line - doesn't have to be, but for demo purposes is sufficient, that said, it does nothing more than give us something to grab for this exercise. A fuller file would present more possibilities):


Date, Time, Time Zone, Name, Type, Status, Gross, Fee, Net, Note, From Email Address, To Email Address, Transaction ID, Item Title, Item ID, Option 1 Name, Option 1 Value, Option 2 Name, Option 2 Value, Reference Txn ID, Custom Number, Receipt ID, Balance,


Anyways, navigate to that link and view my php_help.php file both normally in the browser, and using the browser's "view source" via CTRL-U, and confirm that both views are as I have quoted above. If not, report what you do see. I'm fairly confident though that you will see what I've presented in my quotes for each view - but again, if not - stop and tell me as best you can what the problem is.

OK, now assuming that all is working and you can also do something like that on your own on your server, or in your sandbox environment (like WAMP or XAMP), consider this PHP file:


<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css">
table, td {border: 1px solid gray;}
.td2, .td9, .td11, .td12, .td18, .td15, .td16 {display: none;}
</style>
</head>
<body>
<table>
<tbody>
<?php
if (($handle = fopen("Awards.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<tr>";
for ($c=0; $c < $num; $c++) {
echo "<td class='td$c'>$data[$c]</td>";
}
echo "</tr>\n";
}
fclose($handle);
}
?>
</tbody>
</table>

</body>
</html>

As you probably know or could discover, this will create a table out of the data in the csv file with the first row being the headings and each subsequent row (if any) showing an entry with all available data (as exists) for each column in the headings. It also gives each td a class (.td# or .td##, etc.) that can potentially be used to style the columns or to hide them (display none). Here's that file:

http://john.dynamicdrive.com/demos/tidbits/vshelp/php_test_2help.php

It would have a lot more info if the csv file had more than one line. Yet, even with just the one line, we see how we can control, through a combination of PHP and css which columns are seen. That might be enough or primarily enough for your purposes, you can always act upon the resulting table with javascript in order to refine it further.

Now if still required, we get to the slightly trickier part of how to get the info into a javascript variable. I cannot guarantee this will work in all cases, but it's viable and can be trouble shot if need be. One way to produce a javascript variable (a multidimensional array) from a csv file:


<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<script>
var myAwards = [];
<?php
$row = 0;
if (($handle = fopen("Awards.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "myAwards[$row] = [];";
for ($c=0; $c < $num; $c++) {
echo "myAwards[$row][$c] = '$data[$c]';\n";
}
$row++;
}
fclose($handle);
}
?>
alert(myAwards);
</script>

</body>
</html>

The alert (near the end) is just a primitive way of demonstrating that the array has been constructed and need not be used in the finished code:

http://john.dynamicdrive.com/demos/tidbits/vshelp/php_test_3help.php

Also, after dismissing the alert, use CTRL-U to view the javascript code that was produced by this page.

And, as noted before, this is just a one line csv file. With more lines, a more complex array will be created. I'm sure there are other ways. This was the easiest that presented itself to me at this point.

Just to underscore the use of of CTRL-U, I had to resort both to it and the browsers's error console in order to get the code correct for just this simple demo. So obviously, these are talents that will likely come in handy for fine tuning whatever you have specifically in mind.

I know this is a lot to take in. Feel free to ask questions. Just do me the favor of starting from the earliest point where I lost you and leaving anything that comes after that for later.

Robert_B
04-27-2016, 11:46 AM
Hi John.

First, I want to thank you for taking so much time to lay out the 3 steps. I think I'm beginning to get a handle on PHP (I know I have a handle on "view source - cntr-u) :)

I went through each step, read the explanation and looked at the code. I executed your code through the link and then copied the code and put it up on my server (just to make sure the environment was the same).

Each step looked exactly the same, both through my browser and with view source, through your link and on my server. Until step 3. When I ran the code through your link, it looked exactly as you said. But when I copied the code to my server, the view source looked good, but the alert didn't execute (browser displayed blank page). I tried it in both Firefox and IE.

Is part of my problem getting things to work due to my server's configuration?

Again, thank you for your time and patience.

jscheuer1
04-27-2016, 02:58 PM
Maybe (but if everything else worked as expected, that's doubtful. Or it could be a peculiarity of the browsers you used (also doubtful), or of the Awards.csv file you have (I'm thinking this is most likely). Like if it includes apostrophes or single quotes in it, that would break the javascript array that this code attempts to write out. Let me see if there's another way to get the information from the PHP array to the javascript array. I know there is, it might not be any better at avoiding this issue, though we can always use a PHP function to escape or to change single quotes/apostrophes to entities.

For me to really tell though, I would need to see your link. Can you post it here?

Or try this version:


<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<script>
var myAwards = [];
<?php
$row = 0;
if (($handle = fopen("Awards.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "\tmyAwards[$row] = [];\n";
for ($c=0; $c < $num; $c++) {
echo "\t\tmyAwards[$row][$c] = '" . addslashes($data[$c]) . "';\n";
}
$row++;
}
fclose($handle);
}
?>
alert(myAwards);
</script>

</body>
</html>

If it is what I think it is, that will fix it. If uploading over an existing file, be sure to refresh the page and/or clear the browser cache, otherwise the old non-working code may still be used.

Oh, and there actually is at least one better way of dealing with this I just discovered, but it makes the view source view a lot messier looking. Let's get this resolved, and then I can explain this other method.

Jim Weinberg
04-28-2016, 08:41 PM
Hi John.

Just a quick note so you don't think I've bailed on you. I can put up the file, but it's going to have to wait. I just received word that a dear friend has passed away unexpectedly, and I have to go up to help his widow sort things out. I'll probably be gone for a week. I'll get back to you when I return. Again, thanks for all your help.

jscheuer1
04-29-2016, 07:17 AM
Hi John.

Just a quick note so you don't think I've bailed on you. I can put up the file, but it's going to have to wait. I just received word that a dear friend has passed away unexpectedly, and I have to go up to help his widow sort things out. I'll probably be gone for a week. I'll get back to you when I return. Again, thanks for all your help.

Sorry to hear that. I sincerely hope things go well there. I know this isn't the best time to ask you this, and certainly can wait till you get back, but are you also the OP of this thread? Are you also Robert_B? I wouldn't have thought to check, but this post I'm responding to made me wonder. And l discovered you both have the same IP address. Why is that? It's not really a big deal, but unless there's a good reason for having two accounts, you should maybe pick one.