insert <?php into a string in php file - php

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.

Related

php shortcode into jquery

I have a Wordpress based website, and some of the content is loaded through javascript.
For example:
jQuery(".portfolio-fs-slides").css({"display":"none"}).prepend('<div class="portfolio-fs- slide current-slide portfolio-ppreview"><div class="project-coverslide"></div><div id="content" class="content-projectc contenttextwhite"></div></div>');
What I want to do is append this shortcode: <?php echo do_shortcode('[daisy]'); ?>
But as far as I know is not really possible to append php code in javascript.
Is there any workaround to accomplish this ?
Thanks!
As #Bergi mentioned, the PHP will run serverside, and the JS will run client side. You can output JS (or parts of your JS) via PHP and have it run client side, e.g.
<script>
// extra code here
jQuery(".portfolio-fs-slides").css({"display":"none"}).prepend('<div class="portfolio-fs- slide current-slide portfolio-ppreview"><div class="project-coverslide"></div><div id="content" class="content-projectc contenttextwhite"></div></div>');
<?php echo 'we can output valid js here' ?>
// more code here
</script>
One way to think of this is that since PHP runs server side, it will always run before the JS is parsed.
Put another way, you could have a javascript line like this:
console.log(<?php echo $someVariable ?>);

AJAX - replace javascript in page: ajax won't replace the javascript

I'm trying to replace a bit of javascript in my page via AJAX, but for some reason, AJAX wont replace it...
When I use:
alert(document.getElementById('treintracking').innerHTML);
I can clearly see the javascript from the script piece: (this is the opening line of the javascript piece)
<script type="text/javascript" id="treintracking">
For replacing the script I use this:
document.getElementById('treintracking').innerHTML = responseText;
So, why does AJAX not want to replace the javascript?
I've tested, and the php file used to generate the replacement javascript, works fine.
I also took into account that the to-be-replaced javascript already has tags around it, so I removed those in the php file.
But it still wont replace the content...
Also, if it put somefunction() in that javascript, will it then run, or do I have to do something special?
Note: the javascript script is generated in a php file.
SOLUTION:
I am now using this external solution, I don't have a clue how it works, but it works perfectly:
http://www.javascriptkit.com/javatutors/loadjavascriptcss2.shtml
[I took the loading script from the page source, as it wasnt in the article itself...]
Adding JavaScript via innerHTML does not get evaluated.
If you want to add new code, just set the source to a new external JavaScript file.
So instead of using an Ajax call, you just set the src
document.getElementById('treintracking').src = "new/path.php?a=b";
Another solution [that I would avoid at all costs] is eval().
You'll probably have to embed the new javascript inside a function, which may assign new contents to other functions, and then invoke the outer function. Won't be terribly pretty.

Embedding php in javascripts

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>

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/

Get php variable within javascript

I have run into an interesting problem. I am currently developing php page and need to access a php variable within the javascript onload.
$(document).ready(function() {
var temp = <?php $page_id ?>
}
is this valid? I know that this might seem weird and not be allowed but I am developing a page that has two popup windows. The windows are created using the same view template and there is no way to distinguish between each other. If I stored a hidden value on the page with information unique to the page like so
<input type="hidden" value="<?php $page_id ?> id="page_id" />
if there are two views open at the same time there is no way for me to get a unique page id like so
var temp = $("#page_id").val();
Because there are two views with the same input id that is not unique. Long story short, is it valid to reference a php variable in the javascript?
Long story short is it valid to
reference a php variable in the
javascript.
Short answer, yes you can...PHP is server-side language, you can use it where you want.
Note: I assume that you are doing this in a file with php extension.
Long story short is it valid to reference a php variable in the JavaScript?
You are not referencing a PHP variable in JavaScript. You are simply generating the JavaScript code dynamically through PHP, where the value of the PHP variable $page_id gets hardcoded into the JavaScript code.
If you generate your JavaScript code through PHP, and you use var temp = <?php echo $page_id ?> it will work, but I wouldn't consider it best practice for bigger projects. I prefer my JavaScript code to remain static.
Your first piece of code is valid as long as you are generating the javascript. The same wont work if you put your js code in a separate .js file. Generating dynamic js is not a good practice for several reasons, like js browser caching and reuse for example.
If you want to completely separate the js code of php, you can create a client-server communication where js will ask for a specific value from a php script through ajax and later play with it in js environment.
The only thing you need is some clarification.
As a matter of fact, you cannot pass a variable. You can pass only it's value.
Also, one cannot "pass" anything from PHP to javascript. Javascript being generated by PHP. It is like HTML. You just generate any code you want. And you can use any variables, of course, with this code generation.
Your second example will work too, but you need to echo the value of the PHP variable to the page so that JavaScript can read from it. Also use htmlspecialchars to make sure you don't end up with invalid html.
<input type="hidden" value="<?php echo htmlspecialchars($page_id, ENT_QUOTES) ?>" id="page_id" />
You will find your answer in this question.

Categories