My goal is to generate an html file in javascript (based on form inputs), and use Angular's $http to send this generated file to the server (php) for storage. Is this possible?
So far I've tried generating HTML strings on the client side and send the string over, and use php's file_put_contents() to generate the html file. But I would like to generate the html file on the client side. As the html gets more complex, I don't want to be sending long and complex strings.
Javascript (inside the controller)
$http({
url: "/test.php",
method: "POST",
data: {"content":"<h1>hello world</h1>"}
});
test.php
<?php
$input = file_get_contents("php://input");
$data = json_decode($input);
file_put_contents("index.html", $data->content);
?>
I prefer to generate the html file on the client side because I want to reduce server load.
Thanks for any advice.
You can use Twig for PHP templating. Or PHP Plates - http://platesphp.com/
Read the POSTed data from PHP and generate using the template.
Pseudo codes:
<?php
$input = $_POST['content'];
$html = generateTemplate($input);
file_put_contents($fileName, $html);
?>
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 like to get fingerprint as php variable, I get the follow but do not want to work.
<p>fingerprint2: <strong id="fp2"></strong></p>
<script src="/fingerprintjs2/fingerprint2.js"></script>
<script>
var fp2 = new Fingerprint2();
fp2.get(function(result) {
console.log(result);
$("#fp2").text(result);
});
</script>
$myphpvar = "<script>document.write(fp2.get());</script>";
echo $myphpvar;
That's really not how PHP works at all. PHP cannot process client side JavaScript. If you want access to client side information in PHP then you should probably put it in a form and post it to another page in PHP. There are many good tutorials on PHP forms, such as this one.
The Javascript is run after the PHP has completed. Client side VS server side code. I have solved this in the past by running the PHP within a PHP file that renders an image. This method is often referred to pixel tracking.
Here are the basics, you need to pass your variables in Javascript to a PHP file that renders an image:
document.write("<img src=fingerprint.php?x="+x+"&y="+y+" width=1 height=1>");
In the above case it passed Javascript variables x and y to the PHP image.
Then the fingerprint.php script looks like:
<?php
header("Content-type: image/png");
session_start();
$x = $_REQUEST['x'];
$y = $_REQUEST['y'];
$_SESSION['x'] = $x;
$_SESSION['y'] = $y
// SHOW THE IMAGE
$im = imagecreatefrompng("fingerprint.png");
imagepng($im);
imagedestroy($im);
?>
The png image can be anything you want as it will just be a 1 x 1 image on your final screen. You now have the Javascript variables in your PHP. As the code starts a session you could write the variables to a session and collect them later in another script, or write them to a database and recover later. Try with my simple example to ensure you have it working then expand from there.
There are lots of ways you can send data from JavaScript back serverside
set a cookie and read it in the next request
request further content by injecting a script / IMG / iframe tag (but not using document.write) adding the fingerprint in the query of the url
make an AJAX request
add a hidden input to a form on the page - requires the user to navigate out of the page using the form
Just learning php. I am trying to connect PHP with Javascript through AJAX call.
My javascript file looks like this:
$.ajax({
type:"GET",
url:"test.php",
success:function(data) {
console.log(data); // to check response
}
});
and my php file looks like:
<?php
include('example.php');
header("Content-type: text/javascript");
$key = '4e899892ede0f86b7cb65f974cede5ff';
$latitude = $_GET['latitude'];
$longitude = $_GET['longitude'];
$timestamp = $_GET['timestamp'];
$weather = new WeatherAPIConnector('4e899892ede0f86b7cb65f974cede5ff');
$condition = $weather->getCurrentForecast($latitude,$longitude,$timestamp);
echo $condition;
$conditi = array();
$conditi = $weather->getTodaysTemp($latitude,$longitude);
echo $conditi;
?>
The console shows the entire php file(console.log(data)):
Please let me know how to get the value of $conditi alone
Judging by your words
Just learning php.
I believe you haven't setup a php webserver yet. To use PHP you need to do one of the following:
Setup a web server - you can use software such as XAMP.
Use free / paid Webhosting such as HostGator or any other webhosting provider. and upload your php file there.
Use http://phptester.net/.
And while you are at it, can you post the URL on your address bar?
Check you web server configuration. It looks like the php is not executed but delivered as static content.
Try to open it directly in the browser. Does it also show the php source code?
I went through the same issue, thinking I coded something wrong.
Solution:
In CentOS7 for PHP7.2
sudo yum-config-manager --enable remi-php72
sudo yum install php php-common php-opcache php-mcrypt php-cli php-gd php-curl php-mysqlnd
The one enabling you to cURL data between your FRONT-SERVERS is the second line.
Each PHP7.x version has it own modules ...
Read this article, this is where I found the solution.
https://linuxize.com/post/install-php-7-on-centos-7/
You can find the same php-modules in different distros, just need to research.
I got stuck when using ajax as primary request sender to php.
I was trying to send data to php file and then take that data to view in another file, but the problem is I don't know how to do it .
I tried
var ajax = ajaxObj("POST", "function.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
window.location = "view.php";
}
}
ajax.send("a="+a+"&b="+b);
it locate view.php and I want to take contents that sent
function.php and view it's contents in view.php.
That is where my problem occurs.
So, my question is HOW TO TAKE THOSE CONTENTS
I think you don't understand the use of ajax... here you don't need ajax at all. Ajax is used to update/send content without refreshing the page. So if you want to pass data to a new php file, just pass the variables directly to view.php in your case.
For instance:
go to view.php?a=[your value]&b=[your value]
in view.php you can get the values:
$a = $_GET['a'];
$b = $_GET['b'];
and pass it to your function.php
Use Jquery to avoid dealing with browsers specifications and also jquery is pretty popular and simple to use library
Assuming you are familiar with php and JavaScript
first you have to do all this work in you www or htdocs folder depending on the stack you are using whether it is XAMPP,WAMP or LAMP
let's say as an example we want to send post request to function.php file and that file should verify the existance of $_POST['username'] and return the length of username otherwise it returns 0
so the function.php file should be something like this :
if(isset($_POST['username'])){
echo strlen($_POST['username']);
}else{
echo 0;
}
and the view.php file is the file used to send post request and get the response and displays it in a #display div
so here is the content of view.php
// first you should include jquery
// here is a cdn link
// https://code.jquery.com/jquery-2.1.3.min.js
// or you can use a local jquery file it is up to you
<div id="display">
</div>
// here is the simple js code to send and get the data from function.php file
<script>
$(document).ready(function(){
// waiting for the document until it is ready to use
$.post('function.php',{username:'myusername'},function(data){
// data here is the returned data from the function.php file
$('#display').text('username length is : '+data);
});
});
</script>
i'm trying to update is a javascript which when you hover over an image, a div object floats near your mouse with information, this information is stored in a .js file as an array,
eg.
Text[0]=["image 1","data 1"]
Text[1]=["image 2","data 2"]
in the past if this array is change/data added to/removed from it would require uploading a new copy of the .js file, if data was added to/removed from it would also require a change to the .dwt file for the new image which would update every file that use the .dwt file as the main template which could result in 20+ pages being uploaded
i figured i can automate this by using the database by flagging records if they are active and using a mysql query to get only those which are active, this way a blackened app can add to the database and deactivate record thus eliminating having to upload files every so soften.
to do this, i had planned on storing the information in the database and building the above array based off the results, researching how to use mysql queries in javascript lead me to code like this
$.ajax( "path/to/your.php" )
.done(function() { alert("success"); })
.fail(function() { alert("error"); })
now i understand that i need to make a .php file which runs my query and that my formatting of the query results into the array would be one in the .done part but what i don't understand is what i'm supposed to do in the .php file to output the query results how in the .done part i'm supposed to reference the output
bellow is the code i use to echo my query results to the page to ensure i am getting results
$resultIndex = 0
while($row = $results->fetch_array(MYSQLI_ASSOC))
{
echo '<'.strval($resultIndex).'><br>';
echo 'id = 'strval($row['id']).'<br>';
echo 'name = 'strval($row['name']).'<br>';
echo 'desc = 'strval($row['desc']).'<br>';
echo 'active = 'strval($row['active']).'<br>';
echo '-----------------------<br>';
$resultIndex += 1;
}
i am wondering 2 things
do i just echo or print_r what i want returned from my .php file
how to i access what my .php file returns in .done
I recommend using http://www.php.net/json_encode to output into Json. Yes, just echo the output. On success, a callback is called passed with the data from server.
$.post (url, function (data){
//do some stuff with data from server
});
See http://api.jquery.com/jQuery.post/
Your $.ajax function just points to a page and reads the data on that page. If you want that page to use MySQL, you will need to use php to set up the MySQL query and print the data. The layers of a web app are complicated, but I'll try to break it down for you.
A traditional php/mysql setup works like this:
Javascript:
Client side, only deals with content already available on the page. Often edits html based on user interaction.
HTML
Client side, defines the content on a page
PHP
Server side, runs on the server and construct the html
MYSQL
Server side, used to communicate between the php and the database
Database
Server side, used to permanently store data
Ajax is a way for the Javascript layer to call some php in the background. That php can use MySQL to access data in the database and print it out in a format that the javascript can parse and use. Typically the javascript will then edit the HTML.