passing php variable to separate javascript file - javascript

I have been reading how to pass variables from a php webpage to a separate javascript file, but am not having any luck.
Please don't mark this as duplicate, as I know there are a ton of things out there telling the ways to do this. I recognize those posts and am more just checking my syntax or seeing if there is anything unique about my specific situation that is causing those methods not to work.
So I have a PHP webpage where I POSTed some variables to:
DOCTYPE HTML
...
<?php
$id = $_POST["id"];
$name = $_POST["name"];
?>
...
HTML code with some usage of PHP variables
javascriptFunction()
end page
Then in a separate javascript file I have:
var markerlocation = '<?php echo $point; ?>';
function javascriptFunction () {
alert("markerlocation");
});
This seems really straight forward, but for whatever reason I can't get it. I also have tried with json encode.
I can delete this when done.
Sincere thanks for any help.

My way:
Declare a Array to store variable for passing variable to JavaScript
Encode the Array to JSON in php
Decode the JSON String from php and store as a JavaScript variable
PHP
<?php
//You may declare array for javascript
$jsVal = array(
'user_name' => 'Peter',
'email' => 'peter#gmail.com',
'marker_location' => '102,300'
);
?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>var phpConfig = jQuery.parseJSON(<?=json_encode($jsVal)?>);</script>
Separated javascript file
alert(phpConfig.marker_location);
You can try it

You can point the script tag source to a .php file instead of a .js file, I think that's what you want. Works with image tags too ;)
Edit: some browsers may require the text/javascript mime header in order for it to work properly, but it's not hard with PHP I'll assume you already know how to do that.
On a side note: This option should probably only be used if you're planning on allowing the client to cache the javascript output. If you don't want the client to cache it, you need to set additional headers.

Related

JS $.post > dump PHP $_POST data to file

I've been trying this for hours and finally give up.
As you can tell I've a huge noob and have little to no idea what I'm doing...
I have some JS being called from a button onclick= which POSTs to a PHP file. I'd like to take this POST data and just write it to a file, nothing fancy, just dumping it raw.
I've tried various methods, but none seem to work - either not writing the data at all, or writing "()", "[]" (if trying to encode the POST data as JSON), or just the word "array" and so on.
Methods I've tried;
file_put_contents('test.txt', file_get_contents('php://input')); //this I thought *should* definitely work...
var_dump / var_export / print_r
I've tried storing the above as $data and writing that as well. Just nothing I do seems to work at all.
I'm mostly trying to use fopen/write/close to do the deed (because that's all I really "know"). File is writable.
(part of the) JS I'm using to POST:
(from button onclick="send('breakfast'))
function send(food){
if(food == 'breakfast'){
$.post("recorder.php?Aeggs=" + $("textarea[name=eggs]").val());
I'm not looking to extract(?) values from the POST data, just write it "as-is" to a file, and I'm not bothered on the formatting etc.
Would someone please assist in putting me out of my misery?
You could use fopen() and fwrite() to write text to a new file. print_r() could be used to get the structure of the data or you could write the post var itself to the file. But since your client side code is not sending any POST data, use $_GET on the php side instead of $_POST. Here's an example:
$f = fopen("post_log.txt", 'w'); // use 'w' to create the file if not exists or truncate anew if it does exist. See php.net for fopen() on other flags.
fwrite($f, print_r($_GET, true)); // the true on print_r() tells it to return a string
// to write just the Aeggs value to the file, use this code instead of the above fwrite:
fwrite($f, $_GET["Aeggs"]);
fclose($f);
NOTE: The 2nd param to $.post() would contain the "post" data. Since you dont have that in your code, the $_POST on the PHP side will be an empty array.

SyntaxError: in javascript php session

I am using the following code in a seperate js file to use a php $_SESSION variable. However, I am getting a syntax error of SyntaxError: missing ; before statement. I have tried putting the ; in the usual place, but still the same.
What is the correct way to use a php session in js file. Thanks
var companycode = '<?php echo $_SESSION['ls_idcode_usr']?>';
There may be special characters in the value of the session variable. Use json_encode() to output a valid Javascript literal:
var companycode = <?php echo json_encode($_SESSION['ls_idcode_usr']);?>;
You can only use PHP in files ending in .php, otherwise the web server won't parse them looking for code to execute, and it'll just get passed down to the client.
You can certainly make a whatever.js.php file, where PHP will be involved in the production of the Javascript file that is passed down to the browser.

Javascript function not working as externel file [duplicate]

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.

How to add a PHP script to a .js file?

Suppose I have an external JavaScript file named myJavascript.js which has 3 functions like the following:
function myFunc1(){
//some code
}
function myFunc2(){
//some code
}
function myFunc3(){
//some code
}
Now, I want to add some PHP script in myJavascript.js like the following, and it's from a separate PHP file named myView.ctp:
<?php
$url = Router::url($this->here, true);
$url = explode('/', $url);
$baseURL = $url[0] . '//' . $url[2] . '/' . $url[3] . '/' . $url[5];
$baseURL2 = $url[0] . '//' . $url[2]. '/' . $url[3];
?>
Why I need to add this PHP script inside myJavascript.js is this - I want to use the PHP variables $baseURL and $baseURL2 inside the 3 functions I've created.
How can I achieve this?
Edit:
I'm sorry I actually made a mistake in my question. The php view file is actually named as myView.ctp, as it's a CakePHP view file. The extension is .ctp and not .php. I've updated my question accordingly.
It's possible if you work into an internal HTML file and the extension is php.
Into your myView.php You can declare a global variable, and assign a response server value, into that file.
For example:
myView.php
<script>
var globalVar = <?php echo "your_value" ;?>
</script>
<script src="external_file.js"></script>
external_file.js
console.log(globalVar) // your_value
You cannot use php variables inside a separate javascript file. Instead what you can do is either to include the script inside the php template like
<script type="text/javascript">
....
</script>
or either to parse the url via javascript if this fits for you. You can get the current url with:
window.loacation.href
then you can parse the string as you wish.
I would definitely not do that but instead passing the args to methods or properties.
We usually have one script that takes care of initialization, lazy loading other stuff and so on. This is done in the layout.
<header>
<script src="/js/app.js">
<script>
app.init(<?php echo json_encode($this->request); ?>);
<script>
</header>
Just make sure you pass only what yo need of the request, it might contain security related data, so be careful by passing the whole thing.
In your specific views:
<script>
app.nameSpaceForView.someMethod('<?php echo $someStringVar; ?>');
</script>
You can even avoid this by implementing some logic in the above app.init() function that will check if app.controllers.ControllerName.ViewName is set based on the passed request info and if it's present execute it.
You won't need much, in the best case any, JS in your views by this.

Loading large values of data from php to javascript?

I read this question php array loading into javascript to see what I can do to load a large amount of data from PHP to Javascript, it seems I may have implemented it wrong. Javascript processes and formats the data after it comes in from PHP which loads the data from a database, the data is placed into the client-side session storage so that the data can be worked with by each page. (If there is a better way to do this please let me know).
This is in one .php file.
<?php
session_start();
require_once 'classes/Membership.php';
$membership = new Membership();
$confirmation = $membership->confirm_membership();
if ($confirmation){
$data = $membership->get_data("assump");
echo '<script>var data = '.json_encode($data) .';</script>';
}
?>
This is in a separate .js file
function loadData(){
// All sessionStorage can be accessed by any javascript file
for(var i = 0; i < data.length; i++){
sessionStorage.setItem("assump" + i, data[i]);
}
}
However no values are being loaded. Is this even possible to do?
EDIT: I moved the javascript into the .php file where var data was being created from the php script at the top of the file, I placed the function loadData() into a script tag after the body tag in the html.
This should work fine. However you may experience some problem with the scope (not 100% sure). And here is my suggestion.
Attach your variable to the window object. That's everywhere and you can access it everywhere.
echo '<script>window.mydata = '.json_encode($data) .';</script>';
Ideally you could include this line before your other scripts are included, but this should be fine. I am not sure about your session storage because I would just interact with the data directly from anywhere:
window.alert(window.mydata.blah...);
I've always found that by assigning essentially global variables, to the window object you know exactly that there are no scope problems and it's always there for you.
You can also check for it's existence using:
if(window.mydata!=undefined){ ... }
or the following but the above implies you are checking that it actually exists where as the below could not be true if window.mydata does exist but is set to false or 0 or something like that...
if(window.mydata){ ... }

Categories