PHP echo in Javascript - php

I have this code:
document.getElementById('root').style.left = '<?php echo $page_position[$info["os"]][$info["browser"]][0]; ?>';
document.getElementById('root').style.top = '<?php echo $page_position[$info["os"]][$info["browser"]][1]; ?>';
Why won't this work like this?
Can anybody point me in the right direction?
EDIT:
<?php echo $page_position[$info["os"]][$info["browser"]][1]; ?>
echoed "top:300px;"
Sorry guys, very stupid error of mine :/

If you put it in a .js file, it won't work because it must be in a page that is parsed for PHP (.php).

Things to check:
Check to make sure those variables are available. print_r($info) will help you out.
Make sure that the code is actually being filled with those variables (symptom of #1). View source and check that they are there.
Ensure you don't have any JavaScript errors preceding your code. Open your console (like Firebug) and check to make sure you don't.
Ensure that a root element exists. Again, use your console.
My money goes on #3, you probably have a JavaScript error somewhere that is stopping execution of the script.

Related

Understanding PHP code includes

I am pretty new to PHP. I am going through a website and am trying to find a source of some of the content and have come across what looks like where the source is, but I cannot decipher the code. Can someone help me understand what this means?
<?php
if (is_file($office_file))
include($office_file);
echo do_shortcode(ob_get_clean());
?>
Thanks!
I have copied your code and added comments that (hopefully) explain what is going on.
<?php
if (is_file($office_file)) // check if $office_file is a valid file
include($office_file); // the check passes, so now include the contents of that file inline
echo do_shortcode(ob_get_clean()); // not enough context to know really what this does, but it looks like its printing the result of parsing 'shortcode' from an output buffer
?>

javascript inside php code

i have place javascript inside php code, like this
<?php if(condition) { ?><script>do some scripting here</script><?php } ?>
it works perfect when i run it in local.
but when i upload it to the server it doesnt run..
the javascript doesnt work.
Can anyone please help.
thanks,
Devan
First, I'm pretty sure you have to do either:
<?php if (condition) { ?> ** script stuff ** <?php } ?>
or
<?php if (condition) : ?> ** script stuff ** <?php endif; ?>
(Your script has no scope on the if statement, although that could be a copy/paste error).
Second, it could be your script (perhaps one of the Javascript files such as jQuery isn't on your server).
Your problem is pretty vague...
Here's all the things I would review first :
are you sure php runs on your distant server ?
do you have anything on screen when running your script ?
when you view the source code from the generated page : do you see your javascript code ?
did you check for javascript error messages ?
Another batch of questions after the comments :)
Did you try to change your JS code with a "basic" one, such as "alert('my code works');" ? (in order to see if your javascript code is triggered)
If the basic alert code does not produce a popup, then you should see your browser's setup with javascript. It may not be enabled
if it works (and you don't have any JS error messages) : try to place some more "alert" popups along your own code, in order to find where your code stops to work)
This will not provide you a direct answer to your problem, but will help you to find more details on your problem, and will help us find an answer

Passing data from one php page to another is not working - why?

Frustrated php novice here...
I'm trying to pass a "type" value of either billto or shipto from ab.php to abp.php.
ab.php snippet:
<?php
echo '<a href="' . tep_href_link(FILENAME_ABP, 'edit=' . $bill_address['address_book_id'] . '&type=billto', 'SSL') . '">' .
tep_image_button('small_edit.gif', SMALL_IMAGE_BUTTON_EDIT) .
'</a>';
?>
This does add the &type=billto to the end of the url. It looks like this:
www.mydomain.com/abp.php?edit=408&type=billto&id=4a6524d
abp.php snippet:
if ($HTTP_GET_VARS['type'] == 'billto') {
then it does a db update...
The if returns false though (from what I can tell) because the update is not performed.
I've also tried $_GET instead of $HTTP_GET_VARS.
Because the code in abp.php isn't executed until after the user clicks a button, I can't use echos to check the value, but I can see the type in the url, so I'm not sure why it's not executing.
Could really use some direction... whether it's what I need to change, or even just suggestions on how to troubleshoot it further. I'm in the middle of a huge learning curve right now. Thanks!!!
edit:
Sorry, I just realized I left out that after the db update the user goes back to ab.php. So the whole workflow is this:
User goes to ab.php.
User clicks link to go to abp.php.
User changes data on abp.php.
User clicks button on abp.php.
Update to db is executed and user is sent back to ab.php.
Because the code in abp.php isn't executed until after the user clicks a button, I can't use echos to check the valueWhy not?
echo '<pre>Debug: $_GET=', htmlspecialchars(var_export($_GET, true)), "</pre>\n";
echo '<pre>Debug: billto===$_GET[type] = ', 'billto'===$_GET['type'] ? 'true':'false', "</pre>\n";
if ( 'billto'===$_GET['type'] ) {
...
edit: You might also be interested in netbeans and its php module:
"Debug PHP code using Xdebug: You can inspect local variables, set watches, set breakpoints, and evaluate code live. Navigate to declarations, types and files using Go To shortcuts and hypertext links."
try something like this
if ($_GET['type'] == 'billto') {
die("got to here, type must == billto");
this will prove that your if statement is working or not,
it may be that the update part is not working
Before the if statement - try
var_dump($_GET);
And make sure the 'billto' is contained within the $_GET array. Of course, if you have got the debuger setup, you should be able to watch the value of the $_GET array
or try:
var_dump($_REQUEST);
Check the URL of the second page, is it in the correct form? From the code snippet you post, I don't know if there would be a ? after the question mark. Also try to disable the redirect to see if your code is working as it should.
One other thing is you may want to put the new url in a variable first, then put that into the link HTML. It's less efficient, but makes the code easier to read and debug.
Try turning on error reporting, place this at the start of your php script
error_reporting ( E_ALL | E_STRICT)
PHP is very tolerant of typos and accessing subscripts in an array that does not exist; by enforcing strict and reporting all errors you would be able to catch those cases.
If you can't see the output, try this:
function log_error($no,$msg,$file,$line)
{
$errorMessage = "Error no $no: $msg in $file at line number $line";
file_put_contents("errors_paypal.txt",$errorMessage."\n\n",FILE_APPEND);
}
set_error_handler('log_error');
You may have to set some file permissions for the log file to be written to.
Of course, you can get Netbeans and its debugging module too.

javascript-php var post get

That code work:
startSlideshow(<?php echo json_encode(glob("photos-animaux/*.jpg"))?>);
that code dont :
$.post("",{'folder':'animaux'});
startSlideshow(<?php echo json_encode(glob("photos-".$_GET["folder"]."/*.jpg"))?>);
WHY ?, what i am doing wrong ?, help !
why the stupid php fonction just dont make the string right !! ahhhh!
---new infos----
that line work :
startSlideshow(<?php echo json_encode(glob("photos-".$_GET["folder"]."/*.jpg")) ?>);
because if i MANUALLY enter in the address bar ?folder=animaux...bam! work
so the problem shoul be there : $.get("photo-portfolio.php",{folder:"animaux"});
still dont know where !
If you're using $.post() from JQuery, you should use $_POST['folder'] to access your variable. If you use $.get(), then you use $_GET['folder'] in PHP. Try changing that $_GET to $_POST.
Change $_GET["folder"] to $_POST["folder"] ?
You can dump the $_POST to be sure you're getting the right info..
echo '<pre>', print_r( $_POST, 1), '</pre>';
I hope you're not literally writing these two lines together and hope they are interacting, are you?
$.post("",{'folder':'animaux'});
startSlideshow(<?php echo json_encode(glob("photos-".$_GET["folder"]."/*.jpg"))?>);
PHP runs on the server, Javascript in the browser. In the above two lines, if written like this, the PHP is already long done by the time $.post() is called.
PHP processes the code on the server and sends this to the browser:
$.post("",{'folder':'animaux'});
startSlideshow(['something.jpg', 'something2.jpg']);
The browser executes this code:
Post {'folder':animaux'} to "" (no effect whatsoever).
Start a slideshow with ['something.jpg', 'something2.jpg'] (which was already decided by the time the page loaded).
I hope you're aware of this two stage process.

javascript function not behaving correctly

I have this little function
function makewindows(){
child1 = window.open ("about:blank");
child1.document.write("<?php echo htmlspecialchars(json_encode($row2['ARTICLE_DESC']), ENT_QUOTES); ?>");
child1.document.close();
}
Which whatever I try, simply outputs the php code as the html source, and not the result of the php code. This was previously working fine, and I am not sure what I have changed to result in this behavior.
I have pasted all the code now. An error is generated by a link that calls updateByQuery, preventing makewindows from being parsed correctly..I think. I am not sure what is wrong with updateByQuery however:
function updateByQuery(layer, query) {
url = "get_records.php?cmd=GetRecordSet&query="+query+"&sid="+Math.random();
update(layer, url);
}
Have you recently moved this file out of a PHP parsed file (i.e. .phtml/.php) and into a .js file? Note that any PHP you expect to be executed must be parsed by the PHP parser before delivery to the client. If it was originally in a .php file, then it would have been parsed/ executed, and worked fine.
However, .js files are not, by default, parsed by PHP. Perhaps they were, at one point, but your server administrator has recently upgraded something, and lost this behaviour? You may be able to use a local configuration file (in Apache, .htaccess) to re-enable it.
This code must be in a file that is parsed by PHP before being sent to the browser. Make sure it has a ".php" extension (or that Apache/(or other) is configured to put whatever extension it is using through PHP). Also, make sure PHP is installed correctly and working.
I assume you still have it in a file that is parsed by PHP, like the others already have said. Then it is probably something above this code snippet that confuses the php-parser so it don't recognize the php-tag.
To test that, try to output something else before this function, maybe just a comment or something.
Also, use "var" before client1, or else client1 will be in the global scope.
update 1
Since you tried to insert a piece of php-code and it broke, then the problem is that the server don't parse the file as it should.
To test if the server really parses your .js files (its not the default setting I believe), create a new file: test.js
<?php echo "This is a test"; ?>
Open the test.js file in your browser and look at the page source. If it has the php tags your server don't parse .js files.
update 2
If the php works in .js files, try to rewrite the function like this (sorry I have not tested it because I don't have access to a php-server right now)
<?php
echo "function makewindows(){var child1 = window.open (\"about:blank\"); " .
"child1.document.write(\"" . htmlspecialchars(json_encode($row2['ARTICLE_DESC']), ENT_QUOTES) . "\");" . "child1.document.close(); }";
?>
Make sure you are running the page from the webserver like such: http://localhost/yourpage.php and not directly from the file itself like such: file://yourpage.php
I'm not sure if this will help, but best practices dictate that whenever you write to a new window using JavaScript, you should open and close the document. Can you try this?
function makewindows(){
var child1 = window.open ("about:blank");
child1.document.open();
child1.document.write("<?php echo htmlspecialchars(json_encode($row2['ARTICLE_DESC']), ENT_QUOTES); ?>");
child1.document.close();
}

Categories