Embedding php in javascripts - php

I was trying to embed some PHP into a javscript function that gets called from an onChange in a drop down list. the javascript function is in a .js file, I can get the DDL to call the function, however i cannot get the function to work with the php... eventually i am going to use the value selected in the DDL to access a DB and populate other fields from there, right now i am trying to get it to work with the php:
function controllerType(){
alert('outside php');
<?php
$message = "inside php";
echo "alert('$message');";
?>
}
The function prints the first alert but not the alert called in the php.

Your webserver probably isn't looking for PHP code in .js files by default. You'll have to tell it to either look for PHP in those files or change the file extension to .php.
If you you want to try the former and you're running an Apache web server, try adding the following line to your .htaccess file:
AddHandler application/x-httpd-php .js

Try the following
function controllerType() {
alert('outside php');
alert('<?php echo $message; ?>');
}

You can't call an alert() in PHP.
PHP can just echo text the JavaScript interpreter can interpret as JavaScript.
As for the code you posted, that should all be ran by JavaScript fine. CodePad.

I think the problem might be that your javascript is not being evaluated by your PHP parser.
You might have to create a separate document for that function which ends in .php or using a .htaccess (assuming you're using apache) to tell your php handler to parse .js files

From your following sentence:
eventually i am going to use the value
selected in the DDL to access a DB and
populate other fields from there
It really sounds like you are trying to have the PHP code execute at runtime within the browser. PHP is a server side language and you cannot simply use it in a javascript file as you are trying to.
You will need to have the javascript function post the value from the drop down list to a PHP page through a HTML form or through AJAX.
Forgive me if I misunderstood you.

<?php
$message = "inside php";
?>
<script type="text/javascript">
function controllerType(){
alert('outside php');
alert(<?=$message;?>);
}
</script>

Related

What is the proper way to execute JS?

Is it possible to use JS/JQuery from an external file? If so, what is the best practice?
What is the best practice to call a JQuery function inside a PHP or HTML page?
Here is file.php
echo "<table..";
echo "some code...";
echo "</table>":
<script type="javascript">
$('table').hide().fadeIn(700);
</script>
or:
echo '<script type="javascript">';
echo '$('#foo').toggle("slow");';
echo '</script>';
So, besides a best practice. is any of this possible? I can't seem to make it work from external file or directly.
also from external.js
$(document).ready(function(){ $('table').css({ // code here ... }); });
You can certainly echo jquery (or any html code) directly from PHP
echo '<script type="javascript">
$(\'#foo\').toggle("slow");
</script>';
Your issue in that one was the un-escaped quotes around #foo
I'm not really sure what you meant in the first part of your question, but since you have php I would use this option rather than trying to add jquery into an html file from another javascript file (if that's what you were trying to do)
Both internal and external javascript/jquery code should work.
Make sure you jquery script tag was include in you header/body
If external, make sure to include the external.js script tag after the jquery script tag
Make sure the document was ready first ( $(document).ready() ), and check again the selector either they are exist or not.
For more clean code, no need to echo every single line html code. Just close the php ( ?> ) and write the html as usual.
Please provide as much information as you can so that we know exactly what's the problem was.

Placing javascript/jquery functions in a universally accessible page

I am trying to clean up my pages, and one of the major ways that I am doing so is to put JavaScript and JQuery functions into a file called 'scripts.js' that is automatically accessed upon page load.
I've run into a problem with functions that use php to call from the page itself. For example, the following function doesn't work, and in fact 'kills' the script for all pages (so now things that were supposed to be hidden are not, and things are not loading properly). I've narrowed it down to the fact that I use to call a variable. I would really like to be able to keep functions using PHP in this universal file as opposed to clogging up the HTML template pages, any thoughts on either how to make this work, or if not how else I may be able to call the values needed? They are always extracted to the page before rendering if that helps.
function positiveSelect()
{
var size = <?php echo $idea[0]["size"]; ?> * 1;
if (size > 5)
return true;
else
return false;
}
if you can't retrive your data form the DOM itself you can store values with the corresponding object:
<div data-size=20>
and then retrive it with:
$(element).data("size");
or if you have global data you want to store you can create a value "container" in the head of you html document like this:
<script type="text/x-json" class="global-data">{"value1":"1","value2":"2"}</script>
and then read the content of that element and parse it with JSON.parse
If this function is that specific to a certain page, you might want to add a second js script that just gets loaded on that page.
An alternative would be to echo out a js variable in that php page and have your code call that function with that variable as a parameter.
You can give the javascript a ".php" extension and call it in the script in the same exact way:
<script type="javascript" src="path/to/scripts.php"></script>
You could just name the generate scripts file scripts.php or scripts.js.php; then the PHP preprocessor will process the file and the PHP statements will be evaluated.
When mixing php or any server side language with javascript you need to be aware that the php gets executed only once when the javascript file is created on the client side.
This is probably why you are getting unexpected results. As you move from page to page the php snippet in your global scripts.js will not get updated.

Javascript isn't running in php function

Where am I going wrong with my programming logic here?
I have 2 php files. File 1 includes File 2. File 1 calls a php function from File 2. Inside the php function there is a bunch of html. The html works perfectly. At the end of the function I have this javascript....
<script type="text/javascript">
alert('hello');
</script>
This javascript isn't alerting "hello".
What am I doing wrong?
Thank you in advance.
EDIT: New question because I skrewed the last one up.
In theory would the code below run properly? (yes/no)
<?php function AlertHelp(){
?><script>
alert('help');
</script><?
AlertHelp();
?>
Long shot on a wild guess here with the limited information you gave.
My assumption is that you are not "including" the file via PHP's include, require, include_once or require_once functions, but are in fact using AJAX to load in the page's content.
If this is the case, then I shall also assume you're using innerHTML to put the content on the page.
Suddenly the solution is obvious: <script> tags added by innerHTML are not parsed and run. You could probably do something like this:
// assume `result` is the variable containing the AJAX response and `elem` the element it goes in
elem.innerHTML = result; // this doesn't change
result.match(/<script[^>]*>([\s\S]*?)<\/script>/i,function(m) {eval(m[1]);});
Please note however that eval should be avoided if possible. Consider redesigning your layout to use callbacks instead.

insert <?php into a string in php file

i would like to create a JavaScript string that holds a dynamic php page
for the
newwindow=window.open();
newdocument=newwindow.document;
newdocument.write(HTMLstring);
newdocument.close();
functions.
when i try to insert the first part of the page it starts a php block
HTMLstring+='<?php';
HTMLstring+='echo "this should print";';
HTMLstring+='?>';
i have tried to start with
HTMLstring+='<\?php';
but i get
<!--?phpecho "this should print";?-->
is there a way to do this in JavaScript?
thank you
You are misunderstanding how JavaScript and PHP work. PHP runs on the server, JavaScript runs in the client. Using JavaScript to create PHP code is fundamentally impossible.
In your case, it should be possible to use PHP to output the string into JavaScript directly (like
<script> var myHTML = "<? echo $variable; ?>"; </script>
the other common workaround for when you need to access PHP from within JavaScript is Ajax.

Calling a JavaScript function from PHP

I have a php script that is a bit of a mess and after a form entry, I need to get an address, and display it on a google map. The html and php is crammed into the same script so I essentially need to call the JavaScript as the PHP is happening. Is there a way to do this?
Thanks,
Alex
You can POST your from to a different frame (or iframe), so your page would not reload. The response of your PHP file which comes back to that frame can contain JavaScript code, which will be executed. Something like:
echo('<script type="text/javascript"> alert("Executed on client side"); </script>');
No, PHP executed by the server and returns the full response to the browser. JavaScript in the page is then executed by the client.
You can't call Javascript functions from PHP. You can set the Javascript to run when the page loads instead.
What you want is something like this:
<script type="text/javascript"></script>
var userAddress = "<?php echo $_POST['address']; ?>";
doSomethingWithAddress(userAddress);
</script>
If that code is on the page which you are POSTing the address to, it would take the address from the user, and write it into a javascript tag. The PHP will get executed first on the server, before building the HTML document. This new document has the variable available to the javascript.
I don't know how you would go about doing that, but this seems like a good place to start looking:
http://code.google.com/intl/en/

Categories