Conceptually, this seems like it should be pretty simple, but I keep finding myself in a catch-22 whenever I try to implement it. (Also, for a variety of reasons, I'd really like to handle this without jQuery or AJAX, if possible.)
On the client side, onload triggers a video to play and a picture to appear. Then, each time the user presses the space bar, a different video plays, until a certain point at which the spacebar triggers the next page to load.
On the server side, PHP arrays control which videos and pictures will be displayed (both the order within a page, as well as which set of videos, out of a total of 70 sets).
Currently, all the client-side action is controlled by a set of JS functions that are included in my html header. All the PHP functions are listed toward the bottom of my main page script. The kicker, though, is that the JS functions necessarily contain some PHP references. For example:
document.getElementById("ImagePort").innerHTML="<img src=Pictures/<? echo $_SESSION['TrialArray'][4] . ">"; ?>";
The issue here isn't the syntax; it's the information flow sequence. The problem is that when these PHP calls are in the header, they appear before the browser makes it to the part where I call the PHP function that assigns values to them. PHP then throws error messages that muck up the JS parsing.
So then the intuitive solution is to either move these JS functions lower down (to a footer, perhaps) or else call the PHP functions before the header loads. However, moving them to the footer didn't solve the problem for me. I sortof thought it would... am I mistaken in that expectation, or have I perhaps made a simple mistake somewhere?
Moving the calls such that they precede the JS function definitions is equally problematic, since then the script doesn't know what the JS functions are called, either by PHP or in HTML.
PHP example: playVid(source) is a JS function, $Instructions is a PHP variable.
if ($_SESSION['Page'] == 0) {
echo "<script>playVid(" . "'" . $Instructions . "'" . ");</script>";
}
HTML example: both setFocus() and ShowFirstStimulus() are JS functions.
<body onload="setFocus(); ShowFirstStimulus()">
Both of these throw an "Uncaught Reference Error: [function] not defined. Again, I'm trying to figure out whether that's because I simply can't do it this way, or if I've just made a mistake in how I've set it up.
Assuming that there really is no way out of this Catch-22 (where PHP functions can't be called before JS functions, and JS functions can't be called before PHP functions), it seems that one remaining option is to simply write some dummy code in which I initialize some PHP variables to some value that's bogus but parse-able. This seems like terrible coding hygiene, but at this point I'm not seeing many other options. Any suggestions?
Please also let me know if I need to clarify anything. Thanks!
Related
This is my first question on this site, so I'm going to try to be as specific as i can... By the way, excuse me for my perfect knowledge of English... which isn't perfect at all..
So what I was wondering is: do php variables persist if you change your page's content, using AJAX methods?
Let me explain: I want to code a web app which has to contain a main layer, containing a few tabs. The user has to be able to write stuff into text areas in one tab, switch the tab, and if he wants so, come back to the first tab to complete what he wrote before (also the app has to keep the php variables that it created previously right?). The app also has to put all the data, entered in all the different tabs, in one or many databases, when a summit button is clicked; so it has to access all the variables created before.
I just don't have any code at this moment, but I want to do a specification file before starting to code, because what I am about to do is kinda massive app, so i hope you will be able to explain me this point.
I still thank you for your help.
You would be best to consider the PHP script as a one-off thing. It does what it is asked to, then terminates. Nothing is preserved.
However, if you NEED to preserve something to pass back with an AJAX call, you can do it by including:
<INPUT type='hidden' id='my_variable' value='my_value'>
This can be referenced by the javascript that calls your AJAX PHP page and thus be passed back.
For what you require, as #AlexP said, you can simply change the visibility of each tab content area with:
<SPAN onclick='toggle(this.id)' id='tab_1'>Tab Name</SPAN>
or similar. Your JS function might include something like:
for(n=1;n<=numberOfTabs;n++)
{
document.getElementById("div_"+n).style.display="none";
}
document.getElementById("div_"+passedid).style.display="block";
though there are other ways of doing it.
Perhaps what you REALLY want to do is save the entered data into a database field frequently (or even continuously).
I have searched and found another with quite close question but the result was YUI Compressor and I didn't find that useful.
I use php to obfuscate my JavaScript code but it is not enough. I need a php script that I can run and then rename all functions and variables to random names (only letters) and ofcause before I obfuscate.
I have seen a few but they are either standalone programs like Java or something you need to pay for, and I can't use that.
Does anyone know a class or code snippet that might be able to do that?
And if the YUI Compressor actually can do that, can anyone point out some help to how I implement it into php?
After writing this long-winded response I began to wonder why you need to obfuscate javascript code in the first place? Javascript code is by nature public and anyone looking at your page can see the result. If you have secret/proprietary things you need to do, look into something like AJAX or otherwise making a callback to your server to do the processing and have it spit out the results for javascript. Any processing you do in javascript will be visible by anyone. Obfuscating just makes debugging harder, and isn't guaranteed to keep someone from cracking the code.
In general use javascript to control presentation, parse results from a server call into the document, and validate user input. Anything secret you want done, do on the server side where they can't see the exact code that is going on.
And with that off my chest here is my response if you still want to go the renaming route:
I haven't taken the time to Google what a YUI compressor is yet, but what you're describing sounds like you would need to parse any javascript and from there go about renaming functions and variables. I see a few issues
If/when your javascript uses built-in variable names like document or window and like-wise built-in functions like .getElementById(). Those you can't touch or the script can't do what it was meant to do.
Javascripts are executed in the context of the browser and might use functions/variables from other javascript files ex an HTML like
<script type="text/javascript" src="a.js"></script>
<script type="text/javascript" src="b.js"></script>
Since b.js was included after a.js, b.js can refer to and use any functions or variables in a.js thus if you scramble the names you will have to make sure any references made in b.js are updated to your new names appropriately.
Depending on how often you are wanting to do this renaming you have a trade off of having the code being cracked easier vs completely trashing the browser cache
Modify the names just once and keep the results - then browsers will cache the responses correctly and your site should work pretty well, however since the names are consistant between calls it will be easier for someone to crack the renaming. Though for this solution you don't necessarily need PHP, just any language or script and run it once
Modify the names per session - probably the best solution and middle of the road though it would require you to keep extra memory associated with each session as to the name changes so any requests for new java script files from the same session get renamed as they should (most modern browsers and server settings will allow for caching of the same named javascript file so as described in point 2 if any functions/variables in a.js are used by another javascript file they will have to be updated accordingly
Modify javascript files per request - this may require you to disable caching of your javascript files as every request for a page will require downloading a new javascript file(s) even if the user reloads the same page. This will lower page loading performance considerably (you have to rename all the functions again and generate a new javascript file, that is then downloaded by the browser and parsed by it) and also increase bandwidth consumption, however no two scripts for a page will be alike.
Overall this doesn't seem like a 1 man (or even 2 or 3 man) project that you want to undertake (unless you have a lot of time on your hands, but then things will have changed), there could be something like this out there already or something close which you could fork off of and modify to your needs. Essentially I think what you are wanting to do would be more work than its worth.
I'm not sure why you want to do this, but it seems like a pretty easy task to do manually.
All you need is to write a function that generates random strings, and in you PHP define variables for all JavaScript functions that you have and have those get assigned random strings. Then just substitute them when you print out your code for the actual JavaScript methods. The only caveat is you need to double check that your random strings aren't ever duplicates. If you can't use numbers (as per your question) then use letters and increment them appending to the back of your random string. So in pseudo code...
$var1 = generateRandomString(); //custom method to create random string and append unique letter at end to guarantee no duplicates.
$function1 = generateRandomString();
and in javascript...
//variable assignment
<?php echo "$var1='foo'"; ?>;
//function definition
function <?php echo "$function1" ; ?>( myArg ){
alert(myArg); //this will alert 'foo'
}
//calling the function
<?php echo "$function1($var1)" ; ?>
etc.
I was wondering if I can use PHP and Javascript to get the screen resolution from my users. Altho this is a simple thing, I was wondering if I can execute the JavaScript within a PHP statement and not output the Javascript code to the browser as HTML
I thought maybe putting it in an EOF block, but that didn't work, the output was the actual script haha.
I want to be able to populate a $width and $height within my PHP script and create a variable to look something like
$resolution = 800x600
I know I can place the javascript in the HTML page and then have a PHP block capture the javascript output, but I am using the Smarty template engine and have disabled the use of PHP within the templates for security reasons.
Is there a way to accomplish this?
I don't want to use the resolution for any url manipulating but rather to store the information for my statistical reasons.
I don't think what you want is really possible. It has to be in the HTML output for the browser to execute it.
You can capture it in the page JavaScript and use an AJAX call to POST it back to the server... but at that point you may as well use Google Analytics, because I'm pretty sure that's essentially what they do (but their framework is supported by, well... Google). Using Google Analytics will also prove to be useful, since they capture a number of other statistics as well.
I currently am using PHP to render a dynamic JS+CSS+HTML website via echo statements. The PHP is filling in some of the JS variables.
I want to expand this to include If/Else statements but I have some questions about how PHP interacts with the rendered page
After the site is rendered (all the echo statements have printed) can I still call additional PHP functions? For instance, if I click something can I have that call a PHP function?
Feel free to point me toward PHP tutorials that explain how PHP interacts with the site. Ironically I have done a lot of PHP coding for other tasks I just never thought about it from the ground up
PHP does not interact with the site. PHP's only function is to output text to the browser.
Look at it this way: if you had no PHP, the website would be composed of HTML pages. HTML pages can contain JavaScript and the user can interact with them. The difference with PHP though is that you can generate these HTML pages dynamically (which by association means that you can also generate the JavaScript contained in the HTML pages dynamically). Nothing else has changed.
Basically once the PHP script has finished running and printed (echoed) all the html content to the browswer then it stops running.
Essentially if you are clicking on a web page then that can either call a new page via a form POST or a GET OR maybe javascript can handle the click. And then that Javascript can perhaps perhaps trigger a new request. And that new request can call a PHP script which performs whatever task you want it to.
So if you click on an <a href='action1.php?param1=yes'>Click here</a> link then that will call the script action1.php (with $_REQUEST['param1'] set to 'yes') on the webserver and the webbrowser displays anything it returns. And that new html replaces all the html currently in your browser window.
OR if you have a form:
<form action='action2.php' method='POST'>
<input type='text' name='stuff'>
<input type='submit>
</form>
And you click on submit then again the webserver will be called but this time the script action2.php will be called with $_POST['stuff'] set to whatever is in the text field. And whatever the script returns will be what is displayed in the browser.
Now if you want to click on something in the browser and just change something small on the page or just perform some action on the server then you should probably investigate AJAX handlers and jQuery in particular
Good Luck.
I've learned in coding to never say never....
Aside from standard Ajax, there --IS-- a way to run PHP functions asychronously: xajax In a nutshell, it allows you to call PHP functions directly without reloading the page. A word of warning-- the documentation is weak....
PHP is server side technology as others have mentioned. Getting it to run asynchronously (or after the main page has rended, as the case may be) is only facilitated with some Javascript voodoo, which is what xajax brings to the table. It does a "good enough" job making this possible. I personally have chosen to use Jquery because of the sheer power it brings for UI development. There's tons of options out there to make Ajax calls.
The key to moving your understanding forward is thinking about coding for the FRONT END. When I was beginning my career I was solely a back-end guy, focusing on the standard if/thens/elses and echoing out the relevant code. Once it was on the screen, I was done with it. Moving over to concentrate on the front end requires understanding of the dom structure -- what you'll be using to "grab" elements and then understanding of tech such as javascript to "do stuff" with your data. In a nutshell, it's just a different way of doing what you're used to with a slightly different syntax. Rather than just jumping in feet first to tackle Ajax or this specific task, take some time to familiarize yourself with the basics of traversing the Dom, and perhaps some Javascript or Jquery basics as well. It'll make your job much easier in the long run.
As i understand javascript .js files are best to put all the way at the bottom of html pages, to speed up loading of rest of page. Advised by Yslow(Yahoo) and Page Speed(google).
Now, when in the middle of page some thing RUNS a javascript script, in Internet Explorer, i see a small warning message saying that the element is: Uncaught ReferenceError: SWFObject is not defined
When i put my all.js file in the had, the error goes away but page load slows doen. What to do?
Actually, i remember it was the same with php variables. If i RUN php but the variable comes later, then it just doesnt work. must define the variable first, for it to run.
How to make this workflow better, in case of php scripts? and in case of javsscripts?
Thanks!
You should put your library scripts that are external in the head (things like swfobject, jquery, etc.). But the actual function call you make (for example to bind an event with jquery, or to initialize a swfobject embed) should go at the end.
This made even esier if you keep calling global functions outside of an event handler to a minium and dont use inline javascript or global variables.
What is that "some thing" that runs javascript in the middle of the page?
We do not use <script> tags, and all javascript code we put is js files, which are loaded in strict sequences (so I definitely know that when code is executed, everything it uses is there). (ok, to speed up page loading we append all files into few, like probably you do, "all.js")
If you use script in html attributes (like onchange events etc.) then try to use unobtrussive javascript (attach your events from javascript files).
If that does not help, then divide your javascript into few parts - minimum needed to load the page and execute some stuff before other part is loaded (in <head> of page). Bigger part of scripts you will load before </body>