Set phps $_REQUEST['variable_name'] in JavaScript - php

is it possible to store a variable through javascript so that I can read it in php using $_REQUEST['variable_name'].
for eg.
let's say i have
$adcategory=$_REQUEST['category_id'];
somewhere in the php page, and I would like to pre set that "variable" somewhere before that in javascript, so that it could be read through php.
Does this make any sense? Is this possible?
Thank you for your time!
Andrej

It's less of a technical problem, more of how you structure your code and interaction between the PHP backend and in-page Javascript.
To get the $category_id variable into Javascript, the typical approach is:
<?php print "<script>category_id = $category_id;</script>";
To have your Javascript code send a catid back to a PHP page:
$("#id").load("page.php?category_id="+category_id);
This would ping it back to PHPs $_REQEUST[] array. But the question is why you need the variable available in Javascript first.

Does this make any sense? Is this possible?
No and no :)
PHP executes on server side before anything else, Javascript in the browser. The only way to do this in JavaScript would be to manipulate the form that makes that request before it gets submitted.

Assuming you are using Apache:
Try setting the default in a file (called "my_vars.php" in this example), then in your .htaccess file:
php_value auto_prepend_file /absolute/path/to/my_vars.php
For the js side, take the value of what you set in that file at page load.
<script type="text/javascript">
var = <?=$what_i_set_in_my_vars?>;
</script>
Research:
http://www.google.com/search?aq=f&sourceid=chrome&ie=UTF-8&q=php_value+auto_prepend_file
I have found that auto prepend is good if you want to use a sort of settings file for storing stuff like this, IMHO. That way you don't need to jump through hoops, the draw back is that it will be included on each page.

Does this make any sense? Is this possible?
Yes, you need to bind it to the request string.
If you're calling foobar.php, change the onsubmit behavior of the form and make it:
'foobar.php?category_id=' + your_javascript_category_id_value

Related

Pass a session from PHP to HTML?

G'day,
This is for my tutorial purpose.
I have 3 files
1. mlogin.htm - Takes the input from the user (login name and password). The action is set to the next file so the details can be checked.
<form id="logIn" name="logIn" method="get" action="mlogin.php">
2. mlogin.php - Takes the value from mlogin.htm using GET method. If the details match the details in XML file, the user is redirected to the next file
$musername = $_GET['username'];
$mpassword = $_GET['password'];
exit(header('Refresh:5; url=mloginsuccess.htm'));
3. mloginsuccess.htm - Displays the menu.
Now, what I'm trying to do is to show the username in the 3rd file so it's something like
Welcome, John
I do realise that I can do this using a session by changing the 3rd file to a
mloginsuccess.php
but it MUST be a
mloginsuccess.htm
I was wondering if this is possible.
Any help is appreciated :)
Suppose for a moment that you actually do want to follow your instructions to the letter. (You don't really want to do this, probably... interpreting requirements, rather than following them exactly, is a key trait of a decent software engineer.) If your requirement is that you must use a static page, you have a couple options for getting data accessible on that page. All of which require JavaScript.
Cookies
Query String
Anchor Fragment
Basically, you need to set this data in one of these three places so that you can access it with JavaScript from your static HTML page later on. To set a cookie with PHP, use setcookie(). To read it with JavaScript, use document.cookie, or one of the many snippets of code to make this easier.
To set the query string, simply do so in your redirect:
header('Location: http://www.example.com/mloginsuccess.htm?name=' . urlencode($_GET['username']));
See this question for the JavaScript needed to read the query string: How to get the value from the GET parameters?
Finally, for the anchor fragment, you can often redirect to it the same way. (However note that not all browsers are guaranteed to follow the anchor fragment part of the URL!) To read the anchor fragment, use window.location.hash.
I hope that in the end, you will choose to do none of these and keep your auth logic in a sensible place. Literal interpretation of requirements rarely leads to good code and application design. At a minimum, you can hack around the URL requirement with a rewrite rule, making whatever.html be an alias to whatever.php. The client doesn't know or care what is actually running on the server... that's the server's job. I would tell you how to write a rewrite rule, but you didn't specify which server you are using, so I'll leave that part up to you to Google.
How can you expect to use a php feature(SESSION) in a file which is not php(.HTML).
However you are allowed to use html inside a php file as php is a template engine and process the html ...refer this for for indepth
What renders the HTML?
just convert your .html to .php and
<?php>
session_start();
$_SESSION['username']=$_GET['username']
?>
<html>....<body>welcome <?=$_SESSION['username']?></body>...</html>
or however your html tags are.
Maybe you can use AJAX to load session details. For example, using JQuery,
<script>
...
$(document).ready(function(){
$.ajax({
url: "load_session.php",
success: function(uname){
$("#uname").html(uname);
}
});
});
...
</script>
...
Welcome, <span id="uname"></span>

Accessing session variables in a php file using javascript?

I want to know if there is a way to access the variables set by php using java-script, so that on one page the php variables are set. And then on the next page, i can use java-script to interrogate the PHP file in order to extract the variables, so that they can be displayed on another page?
Thanks in advance!
Not sure if this works, works for my get and post variables
var mySessionVariable = "<?php echo $_SESSION['sessionVariable']; ?>";
The only way, you would do it, is by setting cookies from PHP (or Javascript), and access these.. You can access cookies via PHP using $_COOKIE['var'], and via Js by, document.cookie("var")

Can I use window.open to open an existing php file and pass a javascript variables to that php page?

I have some JavaScript variable in the parent browser window and now I want to open a new window(an existing php file) by clicking a certain button and pass those variable to the opened page. I know I can achieve that by GET method and I just wonder if there is a clearer way I can do it so I don't have to append the variable value at the end of the URL. I also searched on google and SO, someone suggested using window.opener somehow it seemed not to apply to php. I'm still a newbie. Any help is appreciated. Thanks in advance.
scripts in the opener page
var newWindow = window.open ("myfile.php" ,"_blank");
newWindow.var1="hello";
newWindow.var2="world";
myfile.php
//Is it possible to use the variables in php page as below?
window.opener.var1;
window.opener.var2;
If you want those variables to be accessible to the PHP code, then no, the GET method is the easiest and most clear way of doing it.
No JS needed to open new window:
mylink
JS method:
window.open("http://mysite.com/myfile.php?var1=foo&var2=bar");
myfile.php
<?php
$var1 = $_GET['var1'];
$var2 = $_GET['var2'];
...
?>
You can use a form with POST method and target="_blank", but other than that your options are limited.
People don't like popups anyway.

Disable php script via Javascript

I have a situation like this.
<php>
<redirect the page >
<exit>
<javascript>
<redirect the page again>
I want to have javascript that basicall disables the PHP redirect. So if Javascript is enabled on the browser, the javascript redirect will work, if it disable, the PHP redirect will work. Should I just enclose the PHP code in span and make it invisible? Any ideas?
Addition ok this is not a simple redirect. the form authentication is rather odd. Register.php -> register_submit.php -> Was there an error -> yes go back to register.php (everything is javascript at this point). What I have added is PHP authentication as well so if I see javascript is not enabled, I take the user to register.php *after it does the regular checking of fields *.
PHP is a server-side technology. By the time Javascript even sees what's happened, it's too late.
Short answer, JS can't intercept/block PHP (as long as PHP is being called first).
Order of events:
Client requests page
PHP executes and generates output of page
Browser receives output
Browser begins parsing what was sent by what PHP already spit out.
Remove your PHP redirection and add this in your <head>:
<noscript>
<meta http-equiv="refresh" content="0; http://www.example.com/1" />
</noscript>
<script>
window.location = 'http://www.example.com/2';
</script>
This will redirect to http://www.example.com/1 when javascript is disabled, and to http://www.example.com/2 when it's enabled.
PHP code is executed on the server-side, while JS is client-side. So with that structure the PHP will kick in before the JS is executed. If you want JS to control PHP you need to make use of AJAX to control it.
Also enclosing PHP code in a "span" won't have any effect.
Javascript and PHP do not directly interact (exceptions apply, don't worry about them now :D). The best way to implement this type of interaction between these two disparate languages is to use the query string or cookies.
I think there may be some confusion here about when and how PHP is executed as opposed to when and how javascript is executed. Think of PHP as the factory - the goods are physically produced there. Think of your server as the loading dock, the internet as the shipping company. Your browser is the store, HTML is the shelves; Javascript is the window decorations on the store that sells the merchandise. The window decorations have no affect on the production, the factory can make some window decorations, but it doesn't use them, it just ships them right along with the merchandise for the store to use. PHP is the factory, javascript is the decoration. There are some problems with taking this analogy too literally, but there it is in a nutshell.
You can make the PHP redirect conditional on the presence or absence of a specific query string variable:
<?php
// redirect if $_GET['no_redirect'] is NOT set. Reverse the true/false to invert this rule
$do_redirect = (isset($_GET['no_redirect']) === false ? true : false);
// perform the redirect, if required
if ($do_redirect === false)
header('Location:http://mydomain.com');
?>
Javascript:
window.location = 'http://mydomain.com/?no_redirect=1';
EDIT If you're trying to detect if javascript is enabled, then the best way is for javascript to set a cookie if it is enabled. PHP can then check for this cookie, and if it isn't found then you'll know that javascript didn't get a chance to set it, so it must be disabled (or the user edited their cookies).
Take a look at some code snippets for dealing with cookies in javascript, and check out the documentation for dealing with cookies in PHP.

setting array session value inside jquery

I am trying to set session array in jquery which I call inside of javascript function that is called onClick event for link.
But it keeps setting me my last choice that I click.
This is code I used for setting session array(I wanted to add new element to session array everytime when someone clicks on the link):
$_SESSION['Ticket'][]=$IDGame;
You are mixing up server-side and client-side languages. If you want to add something to your $_SESSION variable (server-side), you will need to make an ajax request in javascript (client-side) to the server.
I think this is what you're getting at....
$.isArray($_SESSION['Ticket']) ? $_SESSION['Ticket'].push($IDGame) : $_SESSION['Ticket'] = [$IDGame];
You cannot use PHP code within jQuery (not in this case at least). There is a plugin for jQuery (http://plugins.jquery.com/files/jquery.cookie.js.txt) based on the parameters that are given you can setup a cookie or a session for the current user. For instance:
$('#element').click(function(e) {
e.preventDefault();
$.cookie('Ticket[]', $('#IDGame').val();
});
This code assumed the $IDGame is stored in a (hidden) textfield with ID = IDGame. This is the proper way using jQuery with sessions and cookies. If you want to use PHP Code per sé, than you should consider loading a PHP file with the getJSON function and sending the ID as a parameter to the file and adding a new key to the session in the background.

Categories