I have a JavaScript file (extension .js, not .html) containing several JavaScript functions.
I want to call one of the PHP functions in a PHP file containing only several PHP functions from within one of the JavaScript functions.
Is that possible?
Would I need to "include" the .php file containing the PHP function in the .js file?
How would I do that? For example, say I had a file called myLib.php containing a function called myFunc that takes two parameters (param1 and param2). Then I have a .js file containing a function called myJsFunc. How would a call the myFunc (PHP) from within the myJsFunc (JavaScript function)? Wouldn't I need to include the PHP file somehow in the .js file?
7 years later update: This is terrible advice. Please don't do this.
If you just need to pass variables from PHP to the javascript, you can have a tag in the php/html file using the javascript to begin with.
<script type="text/javascript">
var phpVars = <?php echo json_encode($vars) ?>;
</script>
<script type="text/javascript" src="yourScriptThatUsesPHPVars.js"></script>
If you're trying to call functions, then you can do this like this
<script type="text/javascript" src="YourFunctions.js"></script>
<script type="text/javascript">
// assume each element of $arrayWithVars has already been json_encoded
functionOne(<?php echo implode(', ', $arrayWithVars); ?>);
functionTwo(<?php echo json_encode($moreVars) ?>, <?php echo json_encode($evenMoreVars) ?>);
</script>
AddType application/x-httpd-php .js
AddHandler x-httpd-php5 .js
<FilesMatch "\.(js|php)$">
SetHandler application/x-httpd-php
</FilesMatch>
Add the above code in .htaccess file and run php inside js files
DANGER: This will allow the client to potentially see the contents of your PHP files. Do not use this approach if your PHP contains any sensitive information (which it typically does).
If you MUST use PHP to generate your JavaScript files, then please use pure PHP to generate the entire JS file. You can do this by using a normal .PHP file in exactly the same way you would normally output html, the difference is setting the correct header using PHP's header function, so that the correct mime type is returned to the browser. The mime type for JS is typically "application/javascript"
PHP and JS are not compatible; you may not simply include a PHP function in JS. What you probably want to do is to issue an AJAX Request from JavaScript and send a JSON response using PHP.
A slightly modified version based on Blorgbeard one, for easily referenceable associative php arrays to javascript object literals:
PHP File (*.php)
First define an array with the values to be used into javascript files:
<?php
$phpToJsVars = [
'value1' => 'foo1',
'value2' => 'foo2'
];
?>
Now write the php array values into a javascript object literal:
<script type="text/javascript">
var phpVars = {
<?php
foreach ($phpToJsVars as $key => $value) {
echo ' ' . $key . ': ' . '"' . $value . '",' . "\n";
}
?>
};
</script>
Javascript file (*.js)
Now we can access the javscript object literal from any other .js file with the notation:
phpVars["value1"]
phpVars["value2"]
This is somewhat tricky since PHP gets evaluated server-side and javascript gets evaluated client side.
I would call your PHP file using an AJAX call from inside javascript and then use JS to insert the returned HTML somewhere on your page.
Actually the best way to accomplish this is to write the javascript in a .php and use jquery in a separate file to use the Jquery get script file or jquery load use php include function in the doc where the javascript will live. Essentially this is how it will look.
Dynamic Javascript File in a .php file extension - Contains a mixture of php variables pre processed by the server and the javascript that needs these variables in scripts.
Static Js File - Using http://api.jquery.com/jquery.getscript/ or http://api.jquery.com/load/
In the main html page call the static file as a regular js file. Calling the static js file will force load the dynamic data from the server.
some file.php 1:
<?php
$somevar = "Some Dynamic Data";
?>
$('input').val(<?php echo $somevar?>);
or simply echo the script such as
echo "$('input').val(".$somevar.");";
File 2:somejsfile.js:
$("#result").load( "file.php" );
File 3 myhtml.html:
<script src="somejsfile.js"></script>
I believe this answer the question for many people looking to mix php and javascript. It would be nice to have that data process in the background then have the user have delays waiting for data. You could also bypass the second file and simply use php's include on the main html page, you would just have your javascript exposed on the main page. For performance that is up to you and how you want to handle all of that.
Instead of messing with generic php-handlers do a 1-file exception using a rewrite:
Rename the .js-file to .php and rewrite the request to make it responde to a .js request. If the file is served by apache; add in .htaccess:
RewriteEngine on
RewriteRule myjsfile\.js myjsfile.php [L]
Secondly make the .php-file pretend to be a js-file. Inside the php-file start the file with:
<?php header('Content-Type: application/javascript'); ?>
Et voilĂ , you can now use php-tags in your ".js"-file.
You can't include server side PHP in your client side javascript, you will have to port it over to javascript. If you wish, you can use php.js, which ports all PHP functions over to javascript. You can also create a new php file that returns the results of calling your PHP function, and then call that file using AJAX to get the results.
Because the Javascript executes in the browser, on the client side, and PHP on the server side, what you need is AJAX - in essence, your script makes an HTTP request to a PHP script, passing any required parameters. The script calls your function, and outputs the result, which ultimately gets picked up by the Ajax call. Generally, you don't do this synchronously (waiting for the result) - the 'A' in AJAX stands for asynchronous!
You can make a double resolution of file:
"filename.php.js" in this way.
PHP generates JS in this file.
I got all parameters from DB.
This worked for me on xampp.
There is not any safe way to include php file into js.
One thing you can do as define your php file data as javascript global variable in php file. for example i have three variable which i want to use as js.
abc.php
<?php
$abc = "Abc";
$number = 052;
$mydata = array("val1","val2","val3");
?>
<script type="text/javascript">
var abc = '<?php echo $abc?>';
var number = '<?php echo $number ?>';
var mydata = <?php echo json_encode($mydata); ?>;
</script>
After use it directly in your js file wherever you want to use.
abc.js
function test(){
alert('Print php variable : '+ abc +', '+number);
}
function printArrVar(){
alert('print php array variable : '+ JSON.stringify(mydata));
}
Beside If you have any critical data which you don't want to show publicly then you can encrypt data with js. and also get original value of it's from js so no one can get it's original value. if they show into publicly.
this is the standard way you can call php script data into js file without including js into php code or php script into js.
I have this command inside my javascript to create a cookie with a specific value.
...
document.cookie="superpage=John Doe;secure=true";
...
My goal: I want the content of this cookie inserted via PHP.
So I tried this: In a separate PHP file i declared
$myvalue = "superpage=John Doe;secure=true";
Then I changed the javascript cookie creation to this:
...
document.cookie= '<?php echo $myvalue; ?>';
...
Cookie is then created but with the value <?php echo $myvalue and not the string I defined via PHP. Any help is highly appreciated.
Put your JavaScript on a page with .php extension and your code will work, .i.e:
file.php
<?php
$myvalue = "superpage=John Doe;secure=true";
?>
then, on the same page, outside the php block:
<script>
document.cookie= '<?php echo $myvalue; ?>';
</script>
There seems to be confusion on how to mix php with javascript. The only way to do so would be with javascript inside a php file:
<?php
php code.....
$myvalue = "superpage=John Doe;secure=true";
echo '
<script>
javascript code....
document.cookie= '.$myvalue.'
</script>';
?>
i'm trying to refresh page every 3 second, the url page change with $_GET variable.
i'm trying to save $_GET var into session and cookie, but get error header has already sent.
how to change url after page reload ?
here my script :
Index.php
<?php
session_start();
$skill =$_SESSION['skill'];
?>
<script type="text/javascript">
var auto_refresh = setInterval(function () {
$('#src2').load('monitor.php?skill=<?php echo $skill;?>').fadeIn("slow");
}, 3000);
</script>
monitor.php
<?php
include "conn.php";
session_start();
$_SESSION['skill'] = $_GET['skill'];
if ($_SESSION['skill']=='')
{
$a ="bro";
$_SESSION['skill']=4;}
elseif ($_SESSION['skill']==4){
$a = "yo";
$_SESSION['skill']='5';
}
elseif ($_SESSION['skill']==5){
$a = "soo";
}
?>
First off, "headers already sent" means that whichever file is triggering that error (read the rest of the error message) has some output. The most common culprit is a space at the start of the file, before the <?php tag, but check for echo and other output keywords. Headers (including setting cookies) must be sent before any output.
From here on, this answer covers how you can implement the "refresh the page" part of the question. The code you provided doesn't really show how you do it right now, so this is all just how I'd recommend going about it.
Secondly, for refreshing the page, you will need to echo something at the end of monitor.php which your JS checks for. The easy way is to just echo a JS refresh:
echo '<script>window.location.reload();</script>';
but it's better to output some JSON which your index.php then checks for:
// monitor.php
echo json_encode(array('reload' => true));
// index.php
$('#src2').load('monitor.php?skill=<?php echo $skill;?>', function(response) {
if (response.reload) window.location.reload();
}).fadeIn('slow');
One last note: you may find that response is just plain text inside the JS callback function - you may need to do this:
// index.php
$('#src2').load('monitor.php?skill=<?php echo $skill;?>', function(response) {
response = $.parseJSON( response ); // convert response to a JS object
if (response.reload) window.location.reload();
}).fadeIn('slow');
try putting
ob_start()
before
session_start()
on each page. This will solve your problem.
Without looking at the code where you are setting the session, I do think your problem is there. You need to start the session before sending any data out to the browser.
Take a look at: http://php.net/session_start
EDIT:
Sorry, a bit quick, could it be that you send some data to the browser in the 'conn.php' file? Like a new line at the end of the file?
I have a pretty simple issue which I just can't seem to resolve. I have the following ajax request which sets a PHP Session variable
$.post("http://mytestdomain.com/test.php", {"data": 'success'});
And this code in the PHP file to generate and echo the Session variables
session_start();
$_SESSION['test_text']= $_POST['data'];
echo "Pageviews=". $_SESSION['test_text'];
However this keeps returning the following error message
Notice: Undefined index: data in /var/www/test.php on line 2
If I post a demo URL into my browser like this
http://mytestdomain.com/test.php?data=11111
Then the results are echoed correctly.
So my question is, how do I pass via jQuery Ajax data to a PHP session variable and have it saved?
Thanks
In your test.php file, try the following:
session_start();
$_SESSION['test_text']= $_REQUEST['data'];
echo "Pageviews=". $_SESSION['test_text'];
I need to send result from my PHP file to the JavaScript function/file.
I found some of answers like: var x='<?php echo $pathinfo; ?>';
or this:
myHtmlFile.html:
<script type="text/javascript" src="jquery-1.8.1.js"></script>
<script type="text/javascript" src="newEmptyPHP.php"></script>
<script language="javascript">
function test()
{
alert(result);
}
</script>
newEmptyPHP.php:
<?php
$res="it is result";
echo "var result = ".json_encode($res).";";
?>
My question is whether there is way return value from php function and not from php file.
something like this:
<?php
function phpFunction(){
$res="it is result";
return $res;
}
?>
I need simple PHP/JavaScript code without something complex.
I want keep many function in one php file and not many php files.
<?php
function phpFunction(){
$res="it is result";
return $res;
}
?>
<script>
var result = "<?php echo phpFunction() ?>";
</script>
The above method will work. However, if you want more PHP/JS combined scripts, learn AJAX.
The best way to get your data to JavaScript from PHP is to use AJAX using jQuery you have declared.
You can use $.get()
You can call you php script which contains the function with parameters in you url request.
And when a specific parameter is specified in the url, then you can call you fonction and echo whatever you want to the javascript.
Have a good day!
You can open as many php tags as you wish inside your one php document. You can then either make this php document separate from your main document (however this would require making the main document in php and using a "php include" or "php require") or you can simply just open and close php tags as necessary. You do not even have to close the line at the end of the php, for example.
<?php if (a==a) { ?>
<div>
<script>
<?php echo 'do something here'; ?>
</script>
</div>
<?php } ?>
Using the above example can provide some unique results. Just remember that anything you do with php you can just echo out the result and slot it into the middle of your javascript.