I have various important variables that I need transfering from PHP to JS on the same page load. I am currently storing these variables in DOM element attributes and using jQuery to grab them out.
This works fine, although as some of the information is quite important I would rather this wasn't publicly visible in the DOM and 'hidden from prying eyes'.
So my question is: How to you transfer variables to JS or the DOM from PHP and keep them hidden from sight?
Cheers guys, hope you can help!
use an ajax request on page load. Here is a shell for jQuery:
$(function()
{
$.ajax("http://yoursite.com/phpscript.php",
{
method: "post",
dataType: "json",
success: function(data)
{
// do what you will with the data here
}
});
});
all information has to be downloaded to the person's computer at some point. You can keep it "hidden" in javascript but the end user can easily use firebug or something similar to view that data.
Everything going on in JS is potentially visible to the end user. If it is secure data you are trying to hide, perhaps you need to re-engineer your approach.
So you want data to be sent to user and not sent to user simultaneously?
If the data is sensitive, there is no way to hand it over for client-side processing while keeping it secure. That simply isn't how the web works. Everything you hand over to the client must necessarily be readable by the client. You can use technologies like SSL to protect data from being intercepted, but the intended recipient must be able to read it. You should be processing any sensitive data server-side, and outputting only the results intended for public consumption.
If you simply want to make data available to the page while hidding messy implementation details, there are many options:
<input type="hidden" />
fieldvar myValue = <?= $serverside_value ?>
or using json_encode
It's not very good to give important information to the client side (HTML/JS).
But to answer your question - you can use jQuery's AJAX methods to post a request to PHP and from PHP, you can return json_encode()'ed data back to jQuery. And if you want to keep them hidden from sight, or lets say "encrypted enough" you can run this through an SSL channel. Another option is to make the encryption yourself or use some public libraries for public-private key encryption.
For example with jQuery post :
$.post("script.php",
{requestKey : "requestValue"}, // $_POST["requestKey"] == "requestValue"
function(response) {
// if you receive JSON encoded data
// you should use JSON decoder for javasript
// or var obj = eval('(' + response + ')');
},
"json");
In PHP it will be :
$data = $_POST["requestKey"];
// do something
echo json_encode($result);