We have a PHP script that runs daily ( already working fine) that generates a PDF report for our employees. Now upon this generated PDF we need to add attachments/files that are generated by a JavaScript function. In this JavaScript function we work with data, loaded from our database. This data is different every day and saves a daily attachment file on our server.
In the PHP script mentioned above, we need to include those files/attachments created by JS.
My though was to run a JS function when the PHP script runs, daily. As I have found in this stackoverflow question ( see answer by Vladimir ) it is basically impossible to run js from a PHP script.
How can I achieve this? How can I make sure the files/attachments are generated by JS every day, before the PHP script runs?
(It is allowed for the javascript attachments/files to be generated at 2am, for example. While the PHP script can run at 3am. It doesn't have to be the exact same time).
Any suggestinos would help!
I would work toward using curl to get the JS to run by calling the html file with curl from within the PHP script.
A lot of this depends, of course, on what the JS is doing, exactly, but if you have access to both codebases, you should be able to get it to work, by saving the response from curl into a variable and then parsing and handling it appropriately.
I know this answer is a generalization, but this is because we only generally know how the JS and PHP need to interact. I will be happy to be more specific if we get a few more details.
Good luck and Take care,
JB
Related
Admittedly, I'm new to some of this...
Building a website on a local server. It has a ton of JS function in an external JS file.
Site has a MYSQL DB. (I am still learning this).
As part of my calculations from functions in that external JS file, I want to update and/or read from that DB.
I have been trying to read up on node.js and trying to read up on PHP (still learning both), but I'm not sure if I'm sniffing in the right direction.
Do I somehow invoke functions from node.js from the external JS file? Do I somehow invoke the PHP (in the form of a function, I suppose) from the external JS file?
How does one typically do this?
I have definitely learned that this in the external JS file does not do the trick. First window appears, but second doesn't:
// Activate the node.js library for MYSQL access
alert("got here 1");
var mysql = require('./mysql');
alert("got here 2"); // nope, this never pops up
Higher-level advice might be more useful than detailed in-the-weeds advice...? Still very new to this.
Thank you kindly!
-=-=-=-=-
self-muttering thoughts... I am using the external JS file to hold a bunch of functions that do all kinds of manipulation and conformation to the data that I collect on the front end:
<button class="ButtonOperation" onclick="DataLog(document.getElementById('DataWindow').value,'NE_AssembleOrder')">Log Data</button>
Am I eventually going to discover that I should instead port all of these functions over to a big PHP file instead?
-=-=-=-=-
Okay, took a while before I better understood this. So, this is the answer that would have gotten me moving in the right direction (for any future reference):
The thing to understand is that for this project, you want to manipulate data to and from a database, which means that (at least for now, for the sake of simplicity), the key is to get your data into a package and send it up to the server, and then have a function running on the server take up the yoke from there.
The way to do that (old school), is with a form.
When you SUBMIT a form, all that data on the form is bundled up and sent to the server.
In this instance you have an index.html page, and that page will open a new page for each of the functions you're trying to track. Use JavaScript to pop open the window and then when you include the URL for the window, pop in a Popup_SpecificFunction.php file. (change SpecificFunction as needed)
So far, so good. ;)
Now, in that Popup_SpecificFunction.php, you will collect all your data under a single form. A good ol' HTML form, with a [SUBMIT] button. That very same Popup_SpecificFunction.php file also has a reference in the header, referring to the big main library of PHP functions -- which is a file sitting on the server.
That [SUBMIT] button invokes a ProcessAllThisData function -- which is on the server-side PHP file. In doing this, it sends all the data from the form -- including a lot of data you include in hidden controls -- to the serverside function.
And at that point, you are basically "on the server" with all your data, and then you can just code that function in PHP and manipulate the database and other stuff as needed.
Using the form was the thought-jump you needed, because prior to this, you've generally thought of forms as standalone data, but they can have actions associated with the entire forms.
You can still use JavaScript to do client-side stuff, but here's another thing that can trip a person up:
There is a difference between these two HTML items as far as whether or not you should use them to send data to and from the server, or whether or not you are just going to JavaScript something on that button:
<button></button>
and
<input type="button"></input>
You might have to experiment a bit to figure out which is which.
This was everything you needed to get you moving in the right direction.
Sincerely,
Future Me. :)
I'm trying to write some html pages that I'm currently storing locally (on a Windows machine without any server running). I'd like to pull one file's html into another. I'm very novice when it comes to this kind of thing.
I found a couple of questions/answers on stackoverflow (1,2), but they both refer to deprecated jquery function "load". Specifically, it has a call to $("#myId").load("b.html");. Looking for how to migrate the load call to on, I see an answer that you need
$(window).on('load', function(){
// insert code here
});
Except I don't know what to put in the function itself. (The original answer just had a string that was the filename.
Any pointers?
I have a question about compiling server side functions in PHP with Ajax. I am trying to understand what happens when multiple asynchronous calls are made to the same server side script.
Lets say that I have the following php script - "msg.php":
<?php
function msg(){
$list1 = "hello world";
return $list1;
}
echo json_encode(msg());
?>
and call Ajax JQuery like this:
function get_msg() {
$.get("msg.php", function(data){console.log(JSON.parse(data));}) }
with a button in html:
input type="button" onclick="console.log(get_msg());" value="Submit" class="btn btn-info"
Assuming that everything works I am trying to understand the following:
Does the server recompile the "msg" php function each time a user clicks the button? Does it (or can it?) manage this by user? How about by session?
After multiple clicks by different users does the server destroy the "msg" function after each request? Can I save multiple versions of the same function in memory for later use? If so is it possible to reconcile the different versions?
Is there a way to pre-compile a single php function for all Ajax requests?
Is there a "proper" way to handle dynamic function calls on the server side?
I feel like recompiling it on the server side is wasteful but perhaps this is how things are supposed to work.
PHP interprets code on each request. But there is OPcache:
OPcache improves PHP performance by storing precompiled script bytecode in shared memory, thereby removing the need for PHP to load and parse scripts on each request.
This extension is bundled with PHP 5.5.0 and later, and is available in PECL for PHP versions 5.2, 5.3 and 5.4.
You can find here on SO how to enable OPcache:
Add the following line to your php.ini:
zend_extension=/full/path/to/opcache.so (nix)
zend_extension=C:\path\to\php_opcache.dll (win)
... and much, much more!
I think what you're looking for is caching. PHP by default is a scripted language so if you need to reference something repeatedly it will be executed each time since its interpreted not compiled. Caching is a way around that.
There are a few ways I can think of to store this data for later use. One is cacheing in plain text. Write out your result to a text file and then reference that for later use, using the last modified date as a way to check for freshness. I'm not a big fan of this method because I think having extraneous files written to the server is messy. (just my opinion)
http://php.net/manual/en/function.file-put-contents.php
Thats the function you would use to store your result.
Another option is writing to a database for the results and then time stamping it so you can reference that for freshness. From there you could just use PDO or mysqli to retrieve the data. Then you could use a database cache to make the response time more performant.
Another option is just using something like OPCache to store the results of the function in memory on repeated calls. ( I don't have much experience in this though )
Hopefully that puts you in the right direction.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Here is part of my Javascript function:
var x=document.getElementById('DigitalFiles').rows[R].cells;
x[0].innerHTML= $_FILES['files']['name'][1] <<<< this $_FILES is not working !
What syntax will work, please.
It seems you are confusing javascript with PHP or vice versa.
To set x[0].innerHTML to the desired value, you could use this:
x[0].innerHTML=<?php echo $_FILES['files']['name'][1]; ?>;
Or, if you are already generating the javascript code directly in PHP:
<?php
echo 'x[0].innerHTML="'.addslashes($_FILES['files']['name'][1]).'"';
?>
Generally
You cannot loop through a PHP array in javascript - unless you first make it's contents available to javascript:
<script type="text/javascript">
var _arrayFromPhp=[<?php
implode(',', $_arrayInPhp);
?>];
</script>
This would work, generally, so that you can then use _arrayFromPhp in your javascript environment. This rather abstract example also assumes that $_arrayInPhp is an array with only one level.
However, in the particular case of $_FILES this doesn't make much sense because PHP fills the $_FILES array with files that are being uploaded by the client. I cannot think of any purposeful way to process the contents of $_FILES in javascript.
If you want to use it anyway, you could go about it like this:
<script type="text/javascript">
var _arrayFromPhp=<?php
json_encode($_FILES);
?>;
</script>
After which _arrayFromPhp would contain a representation of $_FILES in javascript.
Note
If you want to somehow work with previously uploaded files in your javascript environment, you should first handle the upload in PHP itself (where $_FILES comes to play) and then apply something like the aforementioned solution to get your information from PHP into your javascript environment.
Please also note that $_FILES will only contain anything if the script is being called directly through the upload process. If you upload files and then reload the page (for example), $_FILES will be empty.
Hint
In case you are using a conventional upload form, please make sure that your form is set to the correct encoding type (by setting the attribute enctype):
<form method="post" enctype="multipart/form-data">
</form>
The $_FILES variable is specific to PHP and not JS. If you want to use JS you will have some restrictions to deal with. You may check out some HTML5 file handling at this link http://www.html5rocks.com/en/features/file_access
Let me just expand on the difference between PHP and Javascript (in this context).
This is a simplified flow;
Client (your or someone else's browser) requests the website at myURL.com. This requests hits your server (LAMP stack for instance) and Apache routes this request to the right place, and PHP is executed on your server and this generates HTML. But really, this "HTML" is just a plain string. PHP does not know what HTML is, or anything about it, and when you are echo-ing or printing etc HTML from PHP, PHP just thinks of it as a string.
PHP has the ability to interact with the database (M in LAMP for MySQL - in this imaginary case) as well as some server variables ($_SERVER and $_POST/GET). Once all the PHP executes and creates your HTML, it sends this HTML as a simple string to the client browser.
The browser gets this string and then it begins to interpret it as HTML. It reads the HTML and will start downloading your assets like javascript files, CSS files, images etc etc and begins to pull all this together. So your javascript file gets read and executed and you CSS begins to style the HTML. The Javascript can continue running on the client, or be triggered to run certain functions by certain events (clicking, timing, scrolling etc).
As you can see, the client has NO access to running PHP. All the PHP has run on the server, and returned a string. All the client does is execute Javascript, in simple terms.
Now as things get a bit more advanced you can start using AJAX. AJAX is a combination of technologies (Asynchronous JavaScript and XML) which is used to make requests to servers without reloading or redirecting the client to a new page. What this means is that you can have your client be at myURL.com and make an AJAX request to myURL.com/myAJAXHandler.php. The client stays at myURL.com, however the server basically sees it the client trying to access the myURL.com/myAJAXHandler.php page in the browser. The server does its normal thing, runs whatever PHP is at that address, and again, returns a simple string to the client. The client using Javascript gets this string and can do what it wants with it, which is usually updating the current page (still myURL.com) or any number of things.
This is a simplified explanation and I've left a lot of things out and generalised a lot but I'm just trying to give you a general idea of what happens.
Hope this helped.
I'm using W3 Schools' AJAX PHP Example (http://www.w3schools.com/ajax/ajax_aspphp.asp) as the foundation for my guestlist web app that uses data stored in LocalStorage, rather than MySQL database, in order for users to be able to search while offline. Now I'm trying to finalize the search guest part.
This is how it works (and differs from the example above):
(index.php). Placing / mirroring all records from MySQL db into
javascript arrays
(index.php). Storing the above mentioned js arrays in LocalStorage
(index.php). By using the AJAX GET code used in the example,
sending the searched item to getData.html (a html file instead of
php file as W3 does)
(getData.html). Successfully getting the searched item through the
URL parameter
(getData.html). Looping through and matching values like in the
above example (code rewriten in javascript).
BUT here ends my success. The AJAX code is identical to the one in the above supplied example (except of course the reference to getData.html), and everything else seems to be working so I won't bother you with my entire code. In the example mentioned, at the very buttom of the PHP-file it says
//output the response
echo $response;
This is where javascript seems to be failing. I've desperately been trying to echo / print the response but for some reason, it doesn't get returned to index.php properly. The only way to force it to display at least something is to either use php echo, or simply just write plain html text somewhere in the getData document within the HTML tags. I've also tried getElementById('txtHint').innerHTML = "hello"; to see if it works but with no success.
The most obvious way to do this would be to simply replace echo $response with the equivalent in js:
document.write(response);
but whatever document.write prints, nothing's dipslayed. The div in which the "hint" is supposed to pop up is yet empty. I've googled solutions, different ways of printing js variables with no further success. Perhaps, document.write is not "compatible" with XML or AJAX responseText? There must be a simple solution to this. Hope you guys can help me out. Thanks!
php is of course a server-side language that emits a page and runs on your back end.
js is of course a client-side language that runs on the user's front end.
document.write() is the proper function for emitting client-side text; it runs at page load time. Example:
<b>My domain is: <script>document.write(document.domain);</script></b>
properly gives
My domain is: www.mydomain.com