Here is the way I test JSONP: I run XAMPP, and in folder htdocs I create a javascript folder . I create json1.json file contain some data to process.
After that, I run this html file locally, and it will call a function in "other machine" (in this case is localhost)
Here is my code in this problem :
<head>
<script>
function updateSales(sales) {
alert('test jsonp');
// real code here
}
</script>
</head>
<body>
<h1>JSONP Example</h1>
<script src="http://localhost:85/javascript/json1.json?callback=updateSales"></script>
</body>
But when I run, nothing happen. But if change to other real json on the internet, it will work. It means change line :
<script src="http://localhost:85/javascript/json1.json?callback=updateSales"></script>
to line:
<script src="http://gumball.wickedlysmart.com/?callback=updateSales"></script>
It will work smoothly.
So, I don't know how to test JSONP by using localhost, please help me.
Thanks :)
JSONP is generated on the server's side. The server fetches your data, encodes it as JSON and then wrap a function call around it.
So in your case you can either modify your .json file the following way:
updateSales( { /* your data */ } );
This, however, would have a hardcoded call back method, so it wont react on changes you do at retrieving it.
The other way is to write a small PHP wrapper (or use whatever else you like) and add the function around the JSON, before sending it back to the client.
<?php
$json = file( "path/to/your/json" );
echo $_GET['callback'], '(', implode( '', $json ), ');';
?>
(The later code is by no means for any productive use, but only for local testing!)
Related
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 a page with a header include, and the include needs a phone number to change on it ONLY if the filename of the current page contains a certain word.
Normally, for a change that is not within an include, the below code would work.
<?php if (strpos($_SERVER['REQUEST_URI'],'example-match') !== false)
{
echo '555-555-5555';
}
else
{
echo '1-800-555-5555';
}
?>
However, since the code is in an included file on the page, rather than the original page itself, the server instead is returning the name of that included file.
Example: www.example.com/im-on-this-page.html returns the name of the include the php file is in - www.example.com/header-include.php.
Is there a way to grab the URL of the page the include is "included on", rather than the url of the include, from code that is within the include?
UPDATE:
The file is being included via Javascript, since the page is it being included on is an html file:
<script>
$('#Header').load('/includes/header.php');
</script>
As of your last comment:
Then it is not an include but a GET request to the PHP delivering a JavaScript. And then, the given URL is proper. In order to find out from where the script has been included you may either look for the referer header (which is instable) or pass the current file to the script itself:
<script> $('#Header')
.load('/includes/header.php?from=encodeUriComponent("<?php echo $_SERVER['REQUEST_URI'] ?php>")'); </script>
Within your script, instead of $_SERVER['REQUEST_URI'] then use $_GET['from']
As commentors have mentioned as well. This is incorrect. $_SERVER does not change for the duration of the script (and includes). Including a file will not alter it.
A javascript include, meaning it is actually called by the client by an ajax call, and not included on the server before the page is presented.
(you load a page, and then load another page which you "print" somewhere on the first)
a quick and dirty fix would be to write something along these lines on the first php file
<?php if (strpos($_SERVER['REQUEST_URI'],'example-match') !== false)
{
echo "<script> var phone_number = '555-555-5555';</script>";
}
else
{
echo "<script> var phone_number = '1-800-555-5555';</script>";
}
?>
which will create a variable on the client side, which you then can call from the loaded page as a javascript variable
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.
I have seen this answer (and a couple others as well) and it provides an understandable way of accessing a PHP array. But in the example, the PHP and the JavaScript are in the same file.
However, I can not write Javascript in my PHP file for some reasons, and what I am rather doing is invoking the JS present in another file. So I need to access an array from the PHP in the JS file. How can I do that?
I prefer it without AJAX (if possible) because I have not yet started learning AJAX.
You could use a JSONP approach:
Make your PHP file output your data wrapped in a function call - something like this:
callback(
['your', 'data', 'here']
);
To do this with a PHP variable you can do this:
callback(<?php echo json_encode($data) ?>);
Then in your JavaScript file do this:
function callback(data) {
alert( data.join(' ') ); // will alert 'your data here'
}
In your HTML file just include the above JS file and afterwards include another script tag that points to your php file:
<script src="/path/to/local.js"></script>
<script src="http://yourserver.com/path/to/server.php"></script>
The browser will grab the first file, and evaluate the function declaration. Then it will grab the second file, and see that it is a function invocation and immediately execute your function with the data as the argument.
A quick and dirty solution would be to make your JavaScript file a PHP file and pass all the variables you need when including the script:
<script type="text/javascript" language="javascript" src="./script.php?var=<?php print(json_encode($var)); ?>"></script>
In the JavaScript file you can use the PHP variables like so:
var a=JSON.parse(<?php print($_REQUEST['var']); ?>);
Originally I had the following structure:
index.html file:
...
<script src="myfunctions.js" />
...
myfunctions.js file:
...
function one() {
....
}
function two() {
....
}
function three() {
....
}
That way I got over 2 500 lines of Javascirpt written but then I had to add a PHP variable to a function so I had to rename index.html to index.php, rename myfunctions.js to myfunctions.js.php and do the following changes:
index.php file:
...
<?php
include("myfunctions.js.php");
?>
...
myfunctions.js.php file:
<script>
...
function one() {
....
}
function two() {
....
}
function three() {
....
}
function four() {
var x = <?php echo $_conf['user_id'];?>
console.log(x);
}
</script>
I have achieved my purpose of using PHP variable in JavaScript but I have noticed that the web page in the browser started to show all the included function, i.e. if in the first case when I was looking at the page with a debug tool or by saving that page on a disk I saw just some little JavaScript code contained in index.html but now looking at or saving the index.php file I see all the functions from myfunctions.js.php visible. Of course the visible content didn't change but the actual output got 2 500 lines longer. Would that be a security problem? Should I avoid this way of showing a PHP variable in JavaScript or I shouldn't be concern about it and leave it how it is?
My concern is that in the second case all my functions gets open so a malicious user can see all the server-side PHP scripts names and required parameters which gives more ways to attack.
The PHP code is processed on the server so all anyone will see if the output of that PHP. So your PHP code is still hidden.
If you're seeing PHP code in your HTML output then either your server is configured incorrectly or you have a syntax error which echo's out what you intend for the parser to process.
Using index.php is fine but you don't really want to do a PHP include of a JS file like that.
The simplest way to go about it is to include the JS file like you were doing
<script src="myfunctions.js" />
and then add a small amount of Javascript to the PHP file which outputs the user_id.
function userId() {
return <?php echo $_conf['user_id'];?>
}
Then function four can access it like
function four() {
console.log(userId());
}
Ideally you will want your functions as part of an Object or module.
Another approach would be for function four to query the server for the user_id and then cache it in some way.
Careful you aren't introducing a XSS vulerability. If $_conf['user_id'] is an integer then you should be fine, but be careful of mixing client side and server side script like this. #Paul S's comment is the way to go.
See here for more tips https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet