...

View Full Version : Problem parsing php in JavaScript



tlsterling
08-07-2006, 03:08 AM
Hi there,

I'm trying to institute remote scripting using an iframe and everything seems to be working great with the exception of JavaScript on the server side recognizing/parsing the embedded php within it. I'm really stumped on this error. This is my client.html file:

----------------------------------------------------------------------------------------------------
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd">
<html><head><title>Remote Scripting with an IFrame - complexer client page</title>
<meta http-equiv="pragma" content="no-cache">

<script type="text/javascript">

function buildQueryString(theFormName) {
theForm = document.forms[theFormName];
var qs = ''
for (e=0;e<theForm.elements.length;e++) {
if (theForm.elements[e].name!='') {
qs+=(qs=='')?'?':'&'
qs+=theForm.elements[e].name+'='+escape(theForm.elements[e].value)
}
}
return qs
}

function messageReciept(name, msg) {
var theFormDiv = document.getElementById('theFormDiv');
theFormDiv.style.display = 'none';
var responseMessage = document.getElementById('responseMessage');
var message = '<p>Your message has been sent! Thank you.<\/p>'
message += ('<p>Your Name: <\/p>' + name)
message += ('<p>Your Message: <\/p>' + msg)
message += '<p><a href="#" onclick="showForm(); return false;">Send another message<\/a><\/p>'
responseMessage.innerHTML = message;
responseMessage.style.display = 'block';
}

var IFrameObj; // our IFrame object
function callToServer(theFormName) {
if (!document.createElement) {return true};
var IFrameDoc;
var URL = 'server.php' + buildQueryString(theFormName);
if (!IFrameObj && document.createElement) {
// create the IFrame and assign a reference to the
// object to our global variable IFrameObj.
// this will only happen the first time
// callToServer() is called
var tempIFrame=document.createElement('iframe');
tempIFrame.setAttribute('id','RSIFrame');
tempIFrame.style.border='0px';
tempIFrame.style.width='0px';
tempIFrame.style.height='0px';
IFrameObj = document.body.appendChild(tempIFrame);

if (document.frames) {
// this is for IE5 Mac, because it will only
// allow access to the document object
// of the IFrame if we access it through
// the document.frames array
IFrameObj = document.frames['RSIFrame'];
}
}

if (navigator.userAgent.indexOf('Gecko') !=-1 && !IFrameObj.contentDocument) {
// we have to give NS6 a fraction of a second
// to recognize the new IFrame
setTimeout('callToServer("'+theFormName+'")',10);
return false;
}

if (IFrameObj.contentDocument) {
// For NS6
IFrameDoc = IFrameObj.contentDocument;
} else if (IFrameObj.contentWindow) {
// For IE5.5 and IE6
IFrameDoc = IFrameObj.contentWindow.document;
} else if (IFrameObj.document) {
// For IE5
IFrameDoc = IFrameObj.document;
} else {
return true;
}

IFrameDoc.location.replace(URL);
return false;
}



function showForm() {
var theFormDiv = document.getElementById('theFormDiv');
theFormDiv.style.display = 'block';
document.forms['emailForm'].reset();
var responseMessage = document.getElementById('responseMessage');
responseMessage.style.display = 'none';
}

function processState(st) {
alert(st)
}
</script>

</head>
<body>

<div id="responseMessage" style="display:none"></div>

<div id="theFormDiv">
<form name="emailForm" id="emailForm"
action="server.php"
onsubmit="return callToServer(this.name)">
Your name:

<input type="text" name="realname">


Your message:

<textarea name="message" cols="50" rows="10"></textarea>


<input type="submit" value="submit">
</form>
</div>

</body>
</html>
----------------------------------------------------------------------------------------

And this is what I've got for server.php:

---------------------------------------------------------------------------------------

<?php

$username = "testName";
?>
<script language="javascript" type="text/javascript">
parent.window.messageReciept('<?php =$username;?>' + 'ggg', '<?php echo "hhh";?>')
</script>

------------------------------------------------------------------------------

After entering some arbitrary values into the 'Your name' and 'Your message' box and submitting, this is the output I get:

-------------------------------------------------------------------------------

Your message has been sent! Thank you.

Your Name:
ggg

Your Message:

Send another message

-----------------------------------------------------------------------

I currently have the xampp (LAMP) installation set up on my machine and it seems to parse php files/commands with no trouble. Any idea why I cannot get JavaScript to recognize/parse any php??

I'm really stumped, any help you can offer would be greatly appreciated, or even let me know if you're unable to reproduce the error on your machine, thanks!!!

Pyth007
08-07-2006, 04:13 PM
Firstly, javascript doesn't parse php nor the other way 'round. PHP can have html and js in it as it passes the parsed PHP code to the browser where the html and js get parsed. Thus the problem is either with your PHP or with your js, but not in ow one parses the other. Since you are getting part of the response message, we know that the call-back function (messageReciept) is getting called correctly. Also the hardcoded "ggg" is being passed but not the php, so the error looks like it's in your php. (Also, when I ran this, looking at FF's javascript console didn't reveal any js errors).

The first time I tried a similar piece of code, I got it to work:


<?
$name="Test Name";
$msg=$_GET['msg'];
?>
<script type='text/javascript'>
parent.window.messageReciept('<?= $name; ?>', '<? echo $msg; ?>');
</script>

//And as you can probably tell, I sent "test.php?msg=Message here" as my URL for the hidden iframe.

Comparing the code I wrote to what you had, I noticed that I was using the shorthand "<?" instead of "<?php" to open my PHP code (I've gotten into the habit of always using that, so I didn't realize this difference until after I started comparing code). When I tried using the longer version, however, it would not work (sort of). Actually, it was OK if I used <?php at the very top of the document or when I used it around the extended echo statement (ie "<?php echo $msg; ?>"). However, I trouble with the shortened echo (ie "<?php= $name?>", and variations thereof with / without a space between the opening tag and the =, as well as variations in caps of <?PHP). Each time I tried using the longhand <?php tag nothing would appear on the screen (as though the callback function was not getting called).

Thus it seemed like there's some problem with the longhand version... I checked out php.net and sure enough:


echo() also has a shortcut syntax, where you can immediately follow the opening tag with an equals sign. This short syntax only works with the short_open_tag configuration setting enabled.


I have <?=$foo?> foo.


(Scroll up a little from here (http://us3.php.net/manual/en/function.echo.php#AEN192026)to see the link)

For future reference, one trick I've done to try nailing down server-side problems is to make the iframe not hidden. In your callToServer function, just change the height and width to an actual value (I've actually created two js files, one for using hidden IFrames and the other using 100px by 100px IFrames. It's small so doesn't reck the design that much, yet it still provides a large enough box to scroll thru to see what the problem might be).

tlsterling
08-07-2006, 07:27 PM
Thanks for the great advice!! So at this point I copied your syntax exactly and I consulted the php.net website, but unfortunately nothing I seem to do makes it parse the PHP. This is what I have for server.php now:



<?
$name="Test Name";
?>
<script type="text/javascript">
parent.window.messageReciept('<?=$name?>', 'hhh')
</script>


And this is what I'm getting out:

Your message has been sent! Thank you.

Your Name:

Your Message:

hhh

Send another message

Could there be some obscure configuration differences between us?? What's even stranger is that I got this exactly method to work with this same set-up a couple of days ago and now it suddenly won't.

I also tried adding some dimensions to my hidden iframe for debugging purposes (100px by 100px), but I'm not seeing it appear upon form submittal from Client.html. Maybe I'm misunderstanding, is that when I should be able to see it??

Pyth007
08-07-2006, 09:41 PM
Are you sure you have set the short_open_tag directive in the php.ini file? This would need to be set to true in order to enable its usage in php files. Otherwise try using the longer "<?php echo $myVar ?>" form.

As for the 100x100 iframe, after your form gets submited, an iframe should be generated. Perhaps add a border to help you locate it. If you still are not seeing this iframe, it may be that the callToServer function is not working correctly. When the function fails during its tests, it returns true (perhaps make an alert for debugging). This in turn returns "true" to the onsubmit which will cause the form to run server.php by itself. This might be causing your problems, but because you are generating the php variables "manually" instead of repeating what the server received in its $_GET[] array, it doesn't seem likely.

tlsterling
08-08-2006, 04:54 AM
I took a look at my php.ini file and I've got this line:

short_open_tag = On

I went ahead and tried everything in the long form just for good measure with the same results:


<?php
$name="Test Name";
echo 'hi there!!!';
?>
<script type="text/javascript">
document.write('hi there!!!');
parent.window.messageReciept('<?php echo $name ?>', 'hhh')
</script>

I finally got to see my iframe when I set the background to red and inserted a JavaScript document.write() and those are showing up correctly. Can you think of any reason why it's continuously ignoring my PHP, I can't find anything wrong with my syntax.
Thanks!!

_Aerospace_Eng_
08-08-2006, 05:07 AM
What you have above should work fine. Check out this example (http://pr2006.t35.com/test.php). This is inside of test.php

<?php $name = "hello"; ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
alert('<?php echo $name; ?>');
</script>
</head>

<body>
</body>
</html>

Pyth007
08-08-2006, 03:38 PM
You said that you were able to run other PHP without problems... Is the current file within the Window path for the php parser to recognize the script? (I'm assuming it is, otherwise it again would seem like it would not be running the js at the end of the script, but it still might be something to check)

Also, try putting a <a>-link to the php script from the client.html. This should also run the php script, but will open it in a new page (set target="_blank" to make sure) so that you can see what's going on. Once the php script is straightened out, then you can go back to working with it thru the iframe. It would also show you any html errors (eg File not found, Unauthorized, etc.) that may be getting masked by normal form submition.

One last idea... In your callToServer, have it run a different file (comment out the line where you tack on the GET params at the end of the url and assign the url to be "junk.html" which has a simple alert.) This will let you know if callToServer is failing (and hense submitting the form normally) or is running correctly.

_Aerospace_Eng_
08-08-2006, 05:34 PM
I've just noticed something. You said your file name was client.html. Unless you have your server setup to parse .html files as php its not going to run the php. You would need to change the file extension of you client.html file to .php and then the php should work.

tlsterling
08-08-2006, 08:27 PM
Okay, so here's an interesting twist. The test.php file works fine for me when I put it in the same directory as my Client.html and server.php files; it parses the PHP variable with no problem.

I made these modifications to my server.php file:



<?php $name = "hello"; ?>
<script type="text/javascript" language="javascript">
document.write('<?php echo $name; ?>');
document.write('stuff here');
parent.window.messageReciept('hhh', '<?php echo $name; ?>')
</script>


Strangely enough, when I open this server.php page alone in my browser window (rather than via the hidden iframe constructed in Client.html), it shows 'hello' first and then 'stuff here'. But when I submit my form in Client.html (which then calls server.php from the hidden iframe), it only shows the 'stuff here' (and of course the 'hhh'), but the parameters that are the php $name variable are empty. Why would the iframe 'host' be blocking the php parsing ability?? Thanks!!

Pyth007
08-08-2006, 09:01 PM
When you say you open your test server.php page alone in the borwser, are you actually opening the page thru your web-server (eg "http://myWebRoot.com/server.php") or by the file-path (eg "file://c:/wwwroot/scripts/server.php")?

Also, did you say you had a test.php file that worked, but server.php does not? That would indeed be strange, unless the filename was reserved for something else (though I've neve heard of that...)

tlsterling
08-08-2006, 09:38 PM
When you say you open your test server.php page alone in the borwser, are you actually opening the page thru your web-server (eg "http://myWebRoot.com/server.php") or by the file-path (eg "file://c:/wwwroot/scripts/server.php")?

I'm opening both test.php and server.php thru my web-server: "http://localhost/server.php".


Also, did you say you had a test.php file that worked, but server.php does not? That would indeed be strange, unless the filename was reserved for something else (though I've neve heard of that...)

Both the test.php and server.php files, when opened alone in the web server (i.e. not thru the Client.html iframe) will produce JavaScript output correctly, with any PHP variable parameters correctly parsed.

This is the output I get when opening server.php alone in the web server:



hellostuff here


This is the output I get after form submittal from Client.html (notice the 'hello' is missing both as JavaScript output and as the 'msg' parameter):



Your message has been sent! Thank you.

Your Name:
hhh

Your Message:

Send another message
Your name:

Your message:



So, in essence, it's as though the PHP is recognized outside of the hidden iframe, but not within it. Does that make sense??

tlsterling
08-08-2006, 11:54 PM
Step 1. Locate brick wall
Step 2. Place hands, palms down, approximately 6 inches apart on wall
Step 3. Bang head repeatedly

I figured out my problem...I assumed that opening files directly from the directory indicated as my DocumentRoot within my httpd.conf Apache document was the same as opening my page thru the web-server.

Famous last words..."I was wrong".

It has now become clear that DocumentRoot is nothing more than a directory to instruct the server of where to look for documents.
I apologize for dragging you all along on this learning experience of mine and appreciate all of your assistance!!

Pyth007
08-09-2006, 02:34 PM
It's like the infamous missing semi-colon... It's always those small things we overlook that bite us! Glad you got it working!

Plus it wasn't all for loss; you gained new insights into using remote scripting, and if nothing else, hopefully it'll save others from a similar headache.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum