i need to have some php code inside javascript
<script ...>
<?php
echo " ... ";
?>
</script>
but this doesnt work. how can u implement php inside javascript that is in a own file javascript.php?
That doesn't do what you probably think it does. It'll work, but the PHP gets run once, when the page is loaded, not every time the JavaScript function is called.
Just for clarification, this is what will happen
index.php
<script type="text/javascript">
<?php echo "alert('hello!');"; ?>
</script>
output html in browser
<script type="text/javascript">
alert('hello!');
</script>
If that is what you want to do, then you can output all the javascript you like. What you cannot do is execute PHP code in the user's browser.
your can use php to dynamically generate javascript code, but you cannot execute php client side. If you need to execute php you will need to postback or use AJAX
There seems to be a good bit of misunderstanding of the question... Here is what you want to do to generate JS from PHP on the server:
file javascript.js.php
<?php
header('Content-Type: text/javascript');
?>
// javascript code here
function PrintTime()
{
alert("The time is " + <?php echo json_encode(time()); ?>);
}
Now, include it on the HTML page using normal script tags:
<script type="text/javascript" src="/url/to/javascript.js.php"></script>
The server will process the PHP file, and return javascript from it.
You can't run PHP inside a javascript file. Primarily because PHP runs server side and is processed before the client is sent any actual http info. JavaScript is processed by the browser on the client side and is sent as text.
It looks like you want to pass some kind of dynamic info to the JavaScript. You can do this by passing a variable like this:
<?php $variable="its me"; ?>
<script>
alert('<?php print($variable)?>')
</script>
The output passed to the client is:
<script>
alert('its me')
</script>
What are you trying to accomplish and maybe we can help you come up with a better solution?
Related
This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 9 years ago.
i have this php and js code:
<script type="text/javascript">
function StartScript(script)
{
<?php require("StartScript.php"); ?>
}
</script>
Start
How can i get the "script" from the javascript function onto the end of the php file?
for example rather than:
<?php require("StartScript.php"); ?>
to have:
<?php require("StartScript.php?script=scriptname"); ?>
The full excerpt (provided that StartScript.php at the same level of current page, otherwise add absolute path):
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
function StartScript(script) {
jQuery.getScript('StartScript.php?script=' + escape(script));
}
</script>
This will call StartScript.php with the parameter script. StartScript.php will generate the JavaScript code which will be executed in the client browser.
Reference: http://api.jquery.com/jQuery.getScript/
It's impossible to write server-side code (PHP) with a client-side code (Javascript). This will not work unless you use something like Ajax.
Maybe I misunderstood your question but this seems pretty easy...I would include all the js in the php file so the html side of things would have only....
<?
$script = "Page1";
include("StartScript.php");
?>
and the php would be...
<? if ($script == "Page1"){ ?>
function StartScript(script)
{
alert("IN");
}
</script>
<? } ?>
The problem is that you're mixing up the client (JS) and the server (PHP). PHP is executed on the server and produces some HTML which gets sent to the browser ("the client"). Browsers cannot run PHP because it's a server-side language.
You should evaluate what the desired interaction is between the client and the server here. For example, if you just need to execute some PHP to pass data to JavaScript, you can build up a JavaScript object:
<script type="text/javascript">
<?php // include script that gives you back some data, e.g.: ?>
<?php $somePhpData = array('red', 'yellow', 'blue'); ?>
<?php $jsonData = json_encode($somePhpData); ?>
var dataFromPhpScript = <?php echo $jsonData; ?>
// do something with the data
</script>
Otherwise, if you really need JavaScript to trigger a PHP script running, you're essentially doing AJAX. You'll likely want some sort of REST API. The idea is that you expose a URL from PHP that the JavaScript can call:
<script type="text/javascript">
jQuery(document).ready(function() {
function startScript(scriptName, success) {
$.get('/path/StartScript.php?script-name=' + scriptName)
.done(success)
.fail(fail);
}
startScript('name-of-php-script', function(data) {
// trigger some JavaScript that relies on the output of the PHP script
});
});
</script>
so I have this in my HTML file
<script type="text/javascript" src="load.js"> </script>
<script type="text/javascript" src="load2.php"> </script>
Saw somewhere you could call an external php file using the js script tag and whatever js in the php file would be rendered first.
But my problem is, I can't assign no JS variable from load.js to a php variable in load2.php but, however, I could alert using echo "alert(js variable);"; So that tells me it finds the variable and I could use it, but I can't assign it to a php variable :/ any help please?
When working between JavaScript and php you must remember one is client side (JavaScript) and the other server side (php). Therefore php can insert values into javascript before it is sent to the client and then rendered (processed). Although the reverse cannot happen as the "scope" of JavaScript is on the clients computer.
The way around this is to use AJAX requests from the client back to the server sending back the data / variable values you need.
JQuery provides an easy to use library with AJAX functionality.
Please see http://api.jquery.com/jQuery.ajax/
PHP is server-side, JS is client side. This means the PHP will run far before the JS ever gets assigned. The only way a PHP file is going to get a JS variable is if you post it using Ajax
One option would be to dynamically load the PHP-generated script and pass some GET parameters to the PHP. This would still require ajax, but could be done cleanly with jQuery. If you go with jQuery, this is the documentation for getScript.
EDIT
So, your HTML file should look like this:
<!-- your first javascript file -->
<script type="text/javascript" src="load.js"></script>
<!-- load jQuery library -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript>
// get the variable from your first javascript file
// via a getter function or global variable
var x = getVarFromFirstFile();
// this will load your second 'javascript' (generated by php) file
// and will pass the variable 'x' as a GET parameter to the php
$.getScript("load2.php?x="+x);
</script>
Then the php in load2.php could access the variable x (originally from load.js) like this:
<?php
$x = $_GET['x'];
...
<html>
<body>
<button type="button" onclick="myFunc()">Click</button>
</body>
</html>
<?php
function myFunc() {
echo "Hello world";
}
?>
I made a code like that and tested it but nothing happened. So is it even possible to do it like that or should I just use JavaScript instead?
Use javascript instead. PHP is not meant to do that.
PHP runs on server side but javascript runs on client side.
<html>
<head>
<script>
function myFunc(){
document.getElementById('content').innerHTML = "Hello world";
}
</script>
</head>
<body>
<button type="button" onclick="myFunc()">Click</button><div id="content"></div>
</body>
</html>
jsFiddle
To understand it simply, the PHP interpreter first pre-process your PHP file (hence its name - PHP: Hypertext Preprocessor), and interpret anything inside <?php and ?> tags and turn it into HTML, response header, and so on...
In your case, you define a PHP function and that's all. The function is unused - but the interpreter doesn't care.
After that, the server sends the preprocessed HTML to client side, and anything inside PHP tags are stripped.
Client (mostly, web browsers) will then parse the HTML as is. Client does not receive any PHP at all as they are gone before they are sent, and of course, the browser won't see your PHP function.
And yes, if the PHP depends on client input, you have to use form submission, Ajax, or anything like that.
You have to do JavaScript for this, all PHP code is only executed on server-side.
If you need some dynamic information from a PHP file you have to call it via Ajax (so again JavaScript)
How do I enter a <? echo "hello"; ?> in a .js file.
This is a jquery app, therefore the js file.
Thanks
Jean
You would only be able to do this if the PHP interpreter is configured to run on *.js files, which by default it won't be. Quite honestly, I wouldn't recommend this behavior.
What I'd do instead is something like this (This method can be used for CSS files, too.):
<script type="text/javascript" src="js.php"></script>
js.php
<?php
//GZIP the file and set the JavaScript header
ob_start("ob_gzhandler");
header("Content-type: text/javascript");
//Set a JavaScript variable based on PHP work
echo 'var logged_in_user = "'.$_SESSION['username'].'";';
//Require an external script
require_once($_SERVER['DOCUMENT_ROOT']."/path/to/jquery.js");
?>
//More Javascript functions and code here
$(document).ready(function() {
$('#mydiv').tipsy();
});
<?php
//Flush the output buffer
ob_end_flush();
?>
I personally do this for many reason.
I have many jQuery files I want to include, but I don't want my browser doing 5+ HTTP requests. Including them all in one file means less HTTP requests.
GZIP! I'm significantly reducing the size of the file be transferred and that speeds things up for the visitor.
It's a central location to add, remove, or modify my JavaScript for the whole site. I can even use $_GET checks to make certain scripts conditional based on how I wrote the <script> tag.
For example, <script type="text/javascript" src="js.php?var=1"></script>. I can then check $_GET['var'] within the js.php file.
You regularly don't use PHP within your JavaScript files. Javascript is a client-side language which is interpreterred in your web browser. PHP is run on the web server.
However, if you need to pass data from your PHP-code to your javascript document, you can do something like:
$js = "<script> myObject = " . json_encode($your_data) . " </script>";
print $js;
If you do this in your <head>-part of your HTML-document, you will have access to myObject in other JS files you load after that.
$your_data can be an array or any kind of object, string or integer. Look for PHP JSON around the interwebs.
I think is not possible to enter a php in the js file, but:
try to create an element div for example or an input ...
and then use this functions to get the value of the div tag.
function AddHiddenValue(oForm) {
var strValue = document.getElementById("city").value;
alert("value: " + strValue);
var oHidden = document.createElement("input");
oHidden.name = "printthisinput";
oHidden.value = strValue;
oForm.appendChild(oHidden);
}
It come from another object form (select .. )
document.getElementById("city").value;
Ok guys here is the answer
The Q: I want to input a value for a variable into a .js file, php tags are not permitted and the js would throw an error.
The A: write a
<script> <? var value_pass = echo "hello"; ?> </script> before the said .js file
In the said .js file
var value=value_pass;
So there is no need to have any of the ob_end_flush.
If this is not viable please let me know.
Thanks
Jean
echo "<a href=#> Delete </a>";
Whenever a user hits Delete, a javascript function should be called for confirmation. Somewhere in the Javascript function, php code should be used for delete operation. How do I do that? Use something like "some php code goes here" and "some javascript function();" for me to know where to put what. Thanks.
This assumes that you are using jQuery...
<a href='javascript:delete();'>Delete</a>
<script type="text/javascript">
function delete()
{
$.post("/your_script.php", {}, function(result) {
});
}
</script>
JavaScript functions execute on the client (in the browser) and PHP executes on a server. So, the JavaScript must send a message - via HTTP - to the server to be handled by PHP. The PHP would perform the delete. Make sense?
The message sent to the server might be sent via AJAX.
Maybe you should use Ajax: http://en.wikipedia.org/wiki/Ajax_%28programming%29
PHP is a server-side technology, while JS is a client-side. They cannot interact with each other - in other words: they're completely independent.
PHP can only output code that is a JS code:
echo 'document.getElementById("test").appendChild(document.createTextNode("' . $myVar . '");';
It's all PHP can do. JavaScript cannot direct interact with PHP as well. You'll have to use AJAX to send a new HTTP request and process returned data.
PHP is a server-side language, thus you can not output PHP script to the browser and expect that it will parse it with the PHP engine.
What you're looking for is probably AJAX, or simply redirecting the user to another page (with different URL parameters) or submitting a form.
AJAX doesn't require from the browser to reload the page, while the two other methods does.
Anyway, you can execute a JS script with the "onclick" method, that's executed when the user clicks on the element: Delete
But the following approach looks better and considered as an ideal one:
Delete
<script type="text/javascript">
document.getElementById("myId").onclick = myFunc;
</script>
Since this involves Ajax, let's assume you can use jQuery to handle the XHR an so on.
<script>
$('#del').click(function(ev){
ev.preventDefault();
var del_conf=confirm('Are you sure you want to delete this item?');
if(del_conf){ $.post('delete.php',{'del':1,'id':123123},function(data){
alert(data.result);},'json');
}
});
</script>
<a id='del'>Delete</a>
Okay, so that's some JS and HTML. Now, you need a separate PHP script to handle the post. To go with the example, this would be saved in the same directory, named 'delete.php'.
<?php
$del=(int)$_POST['del'];
$id=(int)$_POST['id']
if($del<1 || $id<1){ exit; }
else{
//do your DB stuff
}
if($db_success){
echo json_encode(array('result'=>'success'));
}
else{
echo json_encode(array('result'=>'error'));
}
here is another example using jQuery:
<div id="message"></div>
<a class="action" type="delete" rel="1234567">delete</a>
<script type="text/javascript">
$('a.action').click(function(){
var $this = $(this);
var processResponse = function(data){
//optionaly we can display server response
$('#message').html(data);
return;
};
var postPparams = {
module:'my_module_name',
action:$this.attr('type'),
record_id: $this.attr('rel')
};
$.post('/server.php',postPparams, processResponse);
});
</script>